123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779 |
- import { CommonModule } from '@angular/common';
- import { RouterModule } from '@angular/router';
- import { Subscription } from 'rxjs';
- import { signal, Component, OnInit, AfterViewInit, OnDestroy, computed } from '@angular/core';
- import { AdminDashboardService } from './dashboard.service';
- import { FmodeQuery, FmodeObject, FmodeUser } from 'fmode-ng/core';
- import { WxworkAuth } from 'fmode-ng/core';
- import * as echarts from 'echarts';
- @Component({
- selector: 'app-admin-dashboard',
- standalone: true,
- imports: [CommonModule, RouterModule],
- templateUrl: './dashboard.html',
- styleUrl: './dashboard.scss'
- })
- export class AdminDashboard implements OnInit, AfterViewInit, OnDestroy {
- // 统计数据
- stats = {
- totalProjects: signal(128),
- activeProjects: signal(86),
- completedProjects: signal(42),
- totalDesigners: signal(24),
- totalCustomers: signal(356),
- totalRevenue: signal(1258000)
- };
- // 图表周期切换
- projectPeriod = signal<'6m' | '12m'>('6m');
- revenuePeriod = signal<'quarter' | 'year'>('quarter');
- // 详情面板
- detailOpen = signal(false);
- detailType = signal<'totalProjects' | 'active' | 'completed' | 'designers' | 'customers' | 'revenue' | null>(null);
- detailTitle = computed(() => {
- switch (this.detailType()) {
- case 'totalProjects': return '项目总览';
- case 'active': return '进行中项目详情';
- case 'completed': return '已完成项目详情';
- case 'designers': return '设计师统计详情';
- case 'customers': return '客户统计详情';
- case 'revenue': return '收入统计详情';
- default: return '';
- }
- });
- // 明细数据与筛选/分页状态
- detailData = signal<any[]>([]);
- keyword = signal('');
- statusFilter = signal('all');
- dateFrom = signal<string | null>(null);
- dateTo = signal<string | null>(null);
- pageIndex = signal(1);
- pageSize = signal(10);
- // 过滤后的数据
- filteredData = computed(() => {
- const type = this.detailType();
- let data = this.detailData();
- const kw = this.keyword().trim().toLowerCase();
- const status = this.statusFilter();
- const from = this.dateFrom() ? new Date(this.dateFrom() as string).getTime() : null;
- const to = this.dateTo() ? new Date(this.dateTo() as string).getTime() : null;
- // 关键词过滤(对常见字段做并集匹配)
- if (kw) {
- data = data.filter((it: any) => {
- const text = [it.name, it.projectName, it.customer, it.owner, it.status, it.level, it.invoiceNo]
- .filter(Boolean)
- .join(' ')
- .toLowerCase();
- return text.includes(kw);
- });
- }
- // 状态过滤(不同类型对应不同字段)
- if (status && status !== 'all') {
- data = data.filter((it: any) => {
- switch (type) {
- case 'active':
- case 'completed':
- case 'totalProjects':
- return (it.status || '').toLowerCase() === status.toLowerCase();
- case 'designers':
- return (it.level || '').toLowerCase() === status.toLowerCase();
- case 'customers':
- return (it.status || '').toLowerCase() === status.toLowerCase();
- case 'revenue':
- return (it.type || '').toLowerCase() === status.toLowerCase();
- default:
- return true;
- }
- });
- }
- // 时间范围过滤:尝试使用 date/endDate/startDate 三者之一
- if (from || to) {
- data = data.filter((it: any) => {
- const d = it.date || it.endDate || it.startDate;
- if (!d) return false;
- const t = new Date(d).getTime();
- if (from && t < from) return false;
- if (to && t > to) return false;
- return true;
- });
- }
- return data;
- });
- // 分页后的数据
- pagedData = computed(() => {
- const size = this.pageSize();
- const idx = this.pageIndex();
- const start = (idx - 1) * size;
- return this.filteredData().slice(start, start + size);
- });
- totalItems = computed(() => this.filteredData().length);
- totalPagesComputed = computed(() => Math.max(1, Math.ceil(this.totalItems() / this.pageSize())));
- private subscriptions: Subscription = new Subscription();
- private projectChart: any | null = null;
- private revenueChart: any | null = null;
- private detailChart: any | null = null;
- private wxAuth: WxworkAuth | null = null;
- private currentUser: FmodeUser | null = null;
- constructor(private dashboardService: AdminDashboardService) {
- this.initAuth();
- }
- async ngOnInit(): Promise<void> {
- await this.authenticateAndLoadData();
- }
- // 初始化企业微信认证
- private initAuth(): void {
- try {
- this.wxAuth = new WxworkAuth({
- cid: 'cDL6R1hgSi' // 公司帐套ID
- });
- console.log('✅ 管理员仪表板企业微信认证初始化成功');
- } catch (error) {
- console.error('❌ 管理员仪表板企业微信认证初始化失败:', error);
- }
- }
- // 认证并加载数据
- private async authenticateAndLoadData(): Promise<void> {
- try {
- // 执行企业微信认证和登录
- const { user } = await this.wxAuth!.authenticateAndLogin();
- this.currentUser = user;
- if (user) {
- console.log('✅ 管理员登录成功:', user.get('username'));
- this.loadDashboardData();
- } else {
- console.error('❌ 管理员登录失败');
- }
- } catch (error) {
- console.error('❌ 管理员认证过程出错:', error);
- }
- }
- ngAfterViewInit(): void {
- this.initCharts();
- window.addEventListener('resize', this.handleResize);
- }
- ngOnDestroy(): void {
- this.subscriptions.unsubscribe();
- window.removeEventListener('resize', this.handleResize);
- this.disposeCharts();
- }
- private disposeCharts(): void {
- if (this.projectChart) { this.projectChart.dispose(); this.projectChart = null; }
- if (this.revenueChart) { this.revenueChart.dispose(); this.revenueChart = null; }
- if (this.detailChart) { this.detailChart.dispose(); this.detailChart = null; }
- }
- async loadDashboardData(): Promise<void> {
- try {
- // 加载项目统计数据
- await this.loadProjectStats();
- // 加载用户统计数据
- await this.loadUserStats();
- // 加载收入统计数据
- await this.loadRevenueStats();
- console.log('✅ 管理员仪表板数据加载完成');
- } catch (error) {
- console.error('❌ 管理员仪表板数据加载失败:', error);
- // 降级到模拟数据
- this.loadMockData();
- }
- }
- // 加载项目统计数据
- private async loadProjectStats(): Promise<void> {
- try {
- const projectQuery = new FmodeQuery('Project');
- projectQuery.equalTo('company', localStorage.getItem("company") || 'unknonw');
- // 总项目数
- const totalProjects = await projectQuery.count();
- this.stats.totalProjects.set(totalProjects);
- // 进行中项目数
- projectQuery.equalTo('status', '进行中');
- const activeProjects = await projectQuery.count();
- this.stats.activeProjects.set(activeProjects);
- // 已完成项目数
- projectQuery.equalTo('status', '已完成');
- const completedProjects = await projectQuery.count();
- this.stats.completedProjects.set(completedProjects);
- console.log(`✅ 项目统计: 总计${totalProjects}, 进行中${activeProjects}, 已完成${completedProjects}`);
- } catch (error) {
- console.error('❌ 项目统计加载失败:', error);
- throw error;
- }
- }
- // 加载用户统计数据
- private async loadUserStats(): Promise<void> {
- try {
- // 设计师统计
- const designerQuery = new FmodeQuery('Profile');
- designerQuery.contains('roleName', '设计师');
- designerQuery.equalTo('company', localStorage.getItem("company") || 'unknonw');
- const designers = await designerQuery.count();
- this.stats.totalDesigners.set(designers);
- // 客户统计
- const customerQuery = new FmodeQuery('ContactInfo');
- customerQuery.equalTo('company', localStorage.getItem("company") || 'unknonw');
- const customers = await customerQuery.count();
- this.stats.totalCustomers.set(customers);
- console.log(`✅ 用户统计: 设计师${designers}, 客户${customers}`);
- } catch (error) {
- console.error('❌ 用户统计加载失败:', error);
- throw error;
- }
- }
- // 加载收入统计数据
- private async loadRevenueStats(): Promise<void> {
- try {
- // 从订单表计算总收入
- const orderQuery = new FmodeQuery('Order');
- orderQuery.equalTo('status', 'paid');
- const orders = await orderQuery.find();
- let totalRevenue = 0;
- for (const order of orders) {
- const amount = order.get('amount') || 0;
- totalRevenue += amount;
- }
- this.stats.totalRevenue.set(totalRevenue);
- console.log(`✅ 收入统计: 总收入 ¥${totalRevenue.toLocaleString()}`);
- } catch (error) {
- console.error('❌ 收入统计加载失败:', error);
- throw error;
- }
- }
- // 降级到模拟数据
- private loadMockData(): void {
- console.warn('⚠️ 使用模拟数据');
- this.subscriptions.add(
- this.dashboardService.getDashboardStats().subscribe(stats => {
- this.stats.totalProjects.set(stats.totalProjects);
- this.stats.activeProjects.set(stats.activeProjects);
- this.stats.completedProjects.set(stats.completedProjects);
- this.stats.totalDesigners.set(stats.totalDesigners);
- this.stats.totalCustomers.set(stats.totalCustomers);
- this.stats.totalRevenue.set(stats.totalRevenue);
- })
- );
- }
- // ====== 顶部两张主图表 ======
- initCharts(): void {
- this.initProjectChart();
- this.initRevenueChart();
- }
- private initProjectChart(): void {
- const el = document.getElementById('projectTrendChart');
- if (!el) return;
- this.projectChart?.dispose();
- this.projectChart = echarts.init(el);
- const { x, newProjects, completed } = this.prepareProjectSeries(this.projectPeriod());
- this.projectChart.setOption({
- title: { text: '项目数量趋势', left: 'center', textStyle: { fontSize: 16 } },
- tooltip: { trigger: 'axis' },
- legend: { data: ['新项目', '完成项目'] },
- xAxis: { type: 'category', data: x },
- yAxis: { type: 'value' },
- series: [
- { name: '新项目', type: 'line', data: newProjects, lineStyle: { color: '#165DFF' }, itemStyle: { color: '#165DFF' }, smooth: true },
- { name: '完成项目', type: 'line', data: completed, lineStyle: { color: '#00B42A' }, itemStyle: { color: '#00B42A' }, smooth: true }
- ]
- });
- }
- private initRevenueChart(): void {
- const el = document.getElementById('revenueChart');
- if (!el) return;
- this.revenueChart?.dispose();
- this.revenueChart = echarts.init(el);
- if (this.revenuePeriod() === 'quarter') {
- this.revenueChart.setOption({
- title: { text: '季度收入统计', left: 'center', textStyle: { fontSize: 16 } },
- tooltip: { trigger: 'item' },
- series: [{
- type: 'pie', radius: '65%',
- data: [
- { value: 350000, name: '第一季度' },
- { value: 420000, name: '第二季度' },
- { value: 488000, name: '第三季度' }
- ],
- emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' } }
- }]
- });
- } else {
- // 全年:使用柱状图展示 12 个月收入
- const months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
- const revenue = [120, 140, 160, 155, 180, 210, 230, 220, 240, 260, 280, 300].map(v => v * 1000);
- this.revenueChart.setOption({
- title: { text: '全年收入统计', left: 'center', textStyle: { fontSize: 16 } },
- tooltip: { trigger: 'axis' },
- xAxis: { type: 'category', data: months },
- yAxis: { type: 'value' },
- series: [{ type: 'bar', data: revenue, itemStyle: { color: '#165DFF' } }]
- });
- }
- }
- private prepareProjectSeries(period: '6m' | '12m') {
- if (period === '6m') {
- return {
- x: ['1月','2月','3月','4月','5月','6月'],
- newProjects: [18, 25, 32, 28, 42, 38],
- completed: [15, 20, 25, 22, 35, 30]
- };
- }
- // 12个月数据(构造平滑趋势)
- return {
- x: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
- newProjects: [12,18,22,26,30,34,36,38,40,42,44,46],
- completed: [10,14,18,20,24,28,30,31,33,35,37,39]
- };
- }
- setProjectPeriod(p: '6m' | '12m') {
- if (this.projectPeriod() !== p) {
- this.projectPeriod.set(p);
- this.initProjectChart();
- }
- }
- setRevenuePeriod(p: 'quarter' | 'year') {
- if (this.revenuePeriod() !== p) {
- this.revenuePeriod.set(p);
- this.initRevenueChart();
- }
- }
- // ====== 详情面板 ======
- async showPanel(type: 'totalProjects' | 'active' | 'completed' | 'designers' | 'customers' | 'revenue') {
- this.detailType.set(type);
- // 重置筛选与分页
- this.keyword.set('');
- this.statusFilter.set('all');
- this.dateFrom.set(null);
- this.dateTo.set(null);
- this.pageIndex.set(1);
- // 加载本次类型的明细数据
- await this.loadDetailData(type);
- // 打开抽屉并初始化图表
- this.detailOpen.set(true);
- setTimeout(() => this.initDetailChart(), 0);
- document.body.style.overflow = 'hidden';
- }
- closeDetailPanel() {
- this.detailOpen.set(false);
- this.detailType.set(null);
- this.detailChart?.dispose();
- this.detailChart = null;
- document.body.style.overflow = 'auto';
- }
- private initDetailChart() {
- const el = document.getElementById('detailChart');
- if (!el) return;
- this.detailChart?.dispose();
- this.detailChart = echarts.init(el);
- const type = this.detailType();
- if (type === 'totalProjects' || type === 'active' || type === 'completed') {
- const { x, newProjects, completed } = this.prepareProjectSeries('12m');
- this.detailChart.setOption({
- title: { text: '项目趋势详情(12个月)', left: 'center' },
- tooltip: { trigger: 'axis' },
- legend: { data: ['新项目','完成项目'] },
- xAxis: { type: 'category', data: x },
- yAxis: { type: 'value' },
- series: [
- { name: '新项目', type: 'line', data: newProjects, smooth: true, lineStyle: { color: '#165DFF' } },
- { name: '完成项目', type: 'line', data: completed, smooth: true, lineStyle: { color: '#00B42A' } }
- ]
- });
- return;
- }
- if (type === 'designers') {
- this.detailChart.setOption({
- title: { text: '设计师完成量对比', left: 'center' },
- tooltip: { trigger: 'axis' },
- legend: { data: ['完成','进行中'] },
- xAxis: { type: 'category', data: ['张','李','王','赵','陈'] },
- yAxis: { type: 'value' },
- series: [
- { name: '完成', type: 'bar', data: [18,15,12,10,9], itemStyle: { color: '#00B42A' } },
- { name: '进行中', type: 'bar', data: [8,6,5,4,3], itemStyle: { color: '#165DFF' } }
- ]
- });
- return;
- }
- if (type === 'customers') {
- this.detailChart.setOption({
- title: { text: '客户增长趋势', left: 'center' },
- tooltip: { trigger: 'axis' },
- xAxis: { type: 'category', data: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'] },
- yAxis: { type: 'value' },
- series: [{ name: '客户数', type: 'line', data: [280,300,310,320,330,340,345,350,355,360,368,380], itemStyle: { color: '#4E5BA6' }, smooth: true }]
- });
- return;
- }
- // revenue
- this.detailChart.setOption({
- title: { text: '收入构成(年度)', left: 'center' },
- tooltip: { trigger: 'item' },
- series: [{
- type: 'pie', radius: ['35%','65%'],
- data: [
- { value: 520000, name: '设计服务' },
- { value: 360000, name: '材料供应' },
- { value: 180000, name: '售后与增值' },
- { value: 198000, name: '其他' }
- ]
- }]
- });
- }
- private handleResize = (): void => {
- this.projectChart?.resize();
- this.revenueChart?.resize();
- this.detailChart?.resize();
- };
- formatCurrency(amount: number): string {
- return '¥' + amount.toLocaleString('zh-CN');
- }
- // 兼容旧模板调用(已调整为 showPanel)
- showProjectDetails(status: 'active' | 'completed'): void {
- this.showPanel(status);
- }
- showCustomersDetails(): void { this.showPanel('customers'); }
- showFinanceDetails(): void { this.showPanel('revenue'); }
- // ====== 明细数据:加载、列配置、导出与分页 ======
- private async loadDetailData(type: 'totalProjects' | 'active' | 'completed' | 'designers' | 'customers' | 'revenue') {
- try {
- switch (type) {
- case 'totalProjects':
- case 'active':
- case 'completed':
- await this.loadProjectDetailData(type);
- break;
- case 'designers':
- await this.loadDesignerDetailData();
- break;
- case 'customers':
- await this.loadCustomerDetailData();
- break;
- case 'revenue':
- await this.loadRevenueDetailData();
- break;
- }
- } catch (error) {
- console.error('❌ 详情数据加载失败:', error);
- this.loadMockDetailData(type);
- }
- }
- // 加载项目详情数据
- private async loadProjectDetailData(type: 'totalProjects' | 'active' | 'completed'): Promise<void> {
- const projectQuery = new FmodeQuery('Project');
- projectQuery.include("onwer")
- if (type === 'active') {
- projectQuery.equalTo('status', '进行中');
- } else if (type === 'completed') {
- projectQuery.equalTo('status', '已完成');
- }
- const projects = await projectQuery.descending('createdAt').find();
- const detailItems = projects.map((project: FmodeObject) => ({
- id: project.id,
- name: project.get('name') || '未命名项目',
- owner: project.get('owner')?.get('name') || '未分配',
- status: project.get('status') || '未知',
- startDate: project.get('startDate') ? new Date(project.get('startDate')).toISOString().slice(0,10) : '',
- endDate: project.get('endDate') ? new Date(project.get('endDate')).toISOString().slice(0,10) : '',
- date: project.get('createdAt') ? new Date(project.get('createdAt')).toISOString().slice(0,10) : ''
- }));
- this.detailData.set(detailItems);
- }
- // 加载设计师详情数据
- private async loadDesignerDetailData(): Promise<void> {
- const designerQuery = new FmodeQuery('Profile');
- designerQuery.equalTo('roleName', '组员');
- const designers = await designerQuery.descending('createdAt').find();
- const detailItems = designers.map((designer: FmodeObject) => ({
- id: designer.id,
- name: designer.get('name') || '未命名',
- level: designer.get('level') || 'junior',
- completed: designer.get('completedProjects') || 0,
- inProgress: designer.get('activeProjects') || 0,
- avgCycle: designer.get('avgCycle') || 7,
- date: designer.get('createdAt') ? new Date(designer.get('createdAt')).toISOString().slice(0,10) : ''
- }));
- this.detailData.set(detailItems);
- }
- // 加载客户详情数据
- private async loadCustomerDetailData(): Promise<void> {
- const customerQuery = new FmodeQuery('ContactInfo');
- const customers = await customerQuery.descending('createdAt').find();
- const detailItems = customers.map((customer: FmodeObject) => ({
- id: customer.id,
- name: customer.get('name') || '未命名',
- projects: customer.get('projectCount') || 0,
- lastContact: customer.get('lastContactAt') ? new Date(customer.get('lastContactAt')).toISOString().slice(0,10) : '',
- status: customer.get('status') || '潜在',
- date: customer.get('createdAt') ? new Date(customer.get('createdAt')).toISOString().slice(0,10) : ''
- }));
- this.detailData.set(detailItems);
- }
- // 加载收入详情数据
- private async loadRevenueDetailData(): Promise<void> {
- const orderQuery = new FmodeQuery('Order');
- orderQuery.equalTo('status', 'paid');
- const orders = await orderQuery.descending('createdAt').find();
- const detailItems = orders.map((order: FmodeObject) => ({
- invoiceNo: order.get('invoiceNo') || `INV-${order.id}`,
- customer: order.get('customer')?.get('name') || '未知客户',
- amount: order.get('amount') || 0,
- type: order.get('type') || 'service',
- date: order.get('createdAt') ? new Date(order.get('createdAt')).toISOString().slice(0,10) : ''
- }));
- this.detailData.set(detailItems);
- }
- // 降级到模拟详情数据
- private loadMockDetailData(type: 'totalProjects' | 'active' | 'completed' | 'designers' | 'customers' | 'revenue'): void {
- const now = new Date();
- const addDays = (base: Date, days: number) => new Date(base.getTime() + days * 86400000);
- if (type === 'totalProjects' || type === 'active' || type === 'completed') {
- const status = type === 'active' ? '进行中' : (type === 'completed' ? '已完成' : undefined);
- const items = Array.from({ length: 42 }).map((_, i) => ({
- id: 'P' + String(1000 + i),
- name: `项目 ${i + 1}`,
- owner: ['张三','李四','王五','赵六'][i % 4],
- status: status || (i % 3 === 0 ? '进行中' : (i % 3 === 1 ? '已完成' : '待启动')),
- startDate: addDays(now, -60 + i).toISOString().slice(0,10),
- endDate: addDays(now, -30 + i).toISOString().slice(0,10),
- date: addDays(now, -i).toISOString().slice(0,10)
- }));
- this.detailData.set(items);
- return;
- }
- if (type === 'designers') {
- const items = Array.from({ length: 36 }).map((_, i) => ({
- id: 'D' + String(200 + i),
- name: ['张一','李二','王三','赵四','陈五','刘六'][i % 6],
- level: ['junior','mid','senior'][i % 3],
- completed: 10 + (i % 15),
- inProgress: 1 + (i % 6),
- avgCycle: 7 + (i % 10),
- date: addDays(now, -i).toISOString().slice(0,10)
- }));
- this.detailData.set(items);
- return;
- }
- if (type === 'customers') {
- const items = Array.from({ length: 28 }).map((_, i) => ({
- id: 'C' + String(300 + i),
- name: ['王先生','李女士','赵先生','陈女士'][i % 4],
- projects: 1 + (i % 5),
- lastContact: addDays(now, -i * 2).toISOString().slice(0,10),
- status: ['潜在','跟进中','已签约'][i % 3],
- date: addDays(now, -i * 2).toISOString().slice(0,10)
- }));
- this.detailData.set(items);
- return;
- }
- // revenue
- const items = Array.from({ length: 34 }).map((_, i) => ({
- invoiceNo: 'INV-' + String(10000 + i),
- customer: ['华夏地产','远景家装','绿洲装饰','宏图设计'][i % 4],
- amount: 5000 + (i % 12) * 1500,
- type: ['service','material','addon'][i % 3],
- date: addDays(now, -i).toISOString().slice(0,10)
- }));
- this.detailData.set(items);
- }
- getColumns(): { label: string; field: string; formatter?: (v: any) => string }[] {
- const type = this.detailType();
- if (type === 'totalProjects' || type === 'active' || type === 'completed') {
- return [
- { label: '项目编号', field: 'id' },
- { label: '项目名称', field: 'name' },
- { label: '负责人', field: 'owner' },
- { label: '状态', field: 'status' },
- { label: '开始日期', field: 'startDate' },
- { label: '结束日期', field: 'endDate' }
- ];
- }
- if (type === 'designers') {
- return [
- { label: '设计师', field: 'name' },
- { label: '级别', field: 'level' },
- { label: '完成量', field: 'completed' },
- { label: '进行中', field: 'inProgress' },
- { label: '平均周期(天)', field: 'avgCycle' },
- { label: '统计日期', field: 'date' }
- ];
- }
- if (type === 'customers') {
- return [
- { label: '客户名', field: 'name' },
- { label: '项目数', field: 'projects' },
- { label: '最后联系', field: 'lastContact' },
- { label: '状态', field: 'status' }
- ];
- }
- // revenue
- return [
- { label: '发票号', field: 'invoiceNo' },
- { label: '客户', field: 'customer' },
- { label: '金额', field: 'amount', formatter: (v: any) => this.formatCurrency(Number(v)) },
- { label: '类型', field: 'type' },
- { label: '日期', field: 'date' }
- ];
- }
- // 状态选项(随类型变化)
- getStatusOptions(): { label: string; value: string }[] {
- const type = this.detailType();
- if (type === 'totalProjects' || type === 'active' || type === 'completed') {
- return [
- { label: '全部状态', value: 'all' },
- { label: '进行中', value: '进行中' },
- { label: '已完成', value: '已完成' },
- { label: '待启动', value: '待启动' }
- ];
- }
- if (type === 'designers') {
- return [
- { label: '全部级别', value: 'all' },
- { label: 'junior', value: 'junior' },
- { label: 'mid', value: 'mid' },
- { label: 'senior', value: 'senior' }
- ];
- }
- if (type === 'customers') {
- return [
- { label: '全部状态', value: 'all' },
- { label: '潜在', value: '潜在' },
- { label: '跟进中', value: '跟进中' },
- { label: '已签约', value: '已签约' }
- ];
- }
- return [
- { label: '全部类型', value: 'all' },
- { label: 'service', value: 'service' },
- { label: 'material', value: 'material' },
- { label: 'addon', value: 'addon' }
- ];
- }
- // 交互:筛选与分页
- setKeyword(v: string) { this.keyword.set(v); this.pageIndex.set(1); }
- setStatus(v: string) { this.statusFilter.set(v); this.pageIndex.set(1); }
- setDateFrom(v: string) { this.dateFrom.set(v || null); this.pageIndex.set(1); }
- setDateTo(v: string) { this.dateTo.set(v || null); this.pageIndex.set(1); }
- resetFilters() {
- this.keyword.set('');
- this.statusFilter.set('all');
- this.dateFrom.set(null);
- this.dateTo.set(null);
- this.pageIndex.set(1);
- }
- get totalPages() { return this.totalPagesComputed(); }
- goToPage(n: number) { const tp = this.totalPagesComputed(); if (n >= 1 && n <= tp) this.pageIndex.set(n); }
- prevPage() { this.goToPage(this.pageIndex() - 1); }
- nextPage() { this.goToPage(this.pageIndex() + 1); }
- // 生成页码列表(最多展示 5 个,居中当前页)
- getPages(): number[] {
- const total = this.totalPagesComputed();
- const current = this.pageIndex();
- const max = 5;
- let start = Math.max(1, current - Math.floor(max / 2));
- let end = Math.min(total, start + max - 1);
- start = Math.max(1, end - max + 1);
- const pages: number[] = [];
- for (let i = start; i <= end; i++) pages.push(i);
- return pages;
- }
- // 导出当前过滤结果为 CSV
- exportCSV() {
- const cols = this.getColumns();
- const rows = this.filteredData();
- const header = cols.map(c => c.label).join(',');
- const escape = (val: any) => {
- if (val === undefined || val === null) return '';
- const s = String(val).replace(/"/g, '""');
- return /[",\n]/.test(s) ? `"${s}"` : s;
- };
- const lines = rows.map(r => cols.map(c => escape(c.formatter ? c.formatter((r as any)[c.field]) : (r as any)[c.field])).join(','));
- const csv = [header, ...lines].join('\n');
- const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- const filenameMap: any = { totalProjects: '项目总览', active: '进行中项目', completed: '已完成项目', designers: '设计师统计', customers: '客户统计', revenue: '收入统计' };
- a.download = `${filenameMap[this.detailType() || 'totalProjects']}-明细.csv`;
- a.click();
- URL.revokeObjectURL(url);
- }
- }
|