import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import * as echarts from 'echarts';
import { CommonModule, NgIf, NgForOf } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { SettingDialogComponent } from './setting-dialog/setting-dialog'; // @ts-ignore: Component used in code but not in template
import { MatDialog } from '@angular/material/dialog';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu';
import { MatCheckboxModule } from '@angular/material/checkbox';

// 定义工作流阶段接口
interface WorkflowStage {
  id: string;
  name: string;
  order: number;
  description: string;
  isActive: boolean;
}

// 定义SOP模板接口
interface SOPTemplate {
  id: string;
  name: string;
  description: string;
  steps: string[];
  // 新增：模板分类，供对话框使用
  category?: string;
  isActive: boolean;
}

// 定义报价规则接口
interface PricingRule {
  id: string;
  name: string;
  description: string;
  // 调整为与对话框一致的字段
  formula: string;
  category: string;
  isActive: boolean;
}

// 定义绩效规则接口
interface PerformanceRule {
  id: string;
  name: string;
  description: string;
  metric: string;
  threshold: number;
  reward: string;
  isActive: boolean;
}

@Component({
  selector: 'app-system-settings',
  standalone: true,
  imports: [
    CommonModule,
    NgIf,
    NgForOf,
    RouterModule,
    FormsModule,
    MatFormFieldModule,
    MatSelectModule,
    MatSlideToggleModule,
    MatDialogModule,
    MatButtonModule,
    MatInputModule,
    MatMenuModule,
    MatCheckboxModule
  ],
  templateUrl: './system-settings.html',
  styleUrls: ['./system-settings.scss']
})
export class SystemSettings implements OnInit {
  // 当前激活的标签页
  activeTab: string = 'workflow';
  
  // 搜索关键词
  workflowSearchTerm: string = '';
  sopSearchTerm: string = '';
  pricingSearchTerm: string = '';
  performanceSearchTerm: string = '';
  
  // 数据列表
  workflowStages: WorkflowStage[] = [];
  sopTemplates: SOPTemplate[] = [];
  pricingRules: PricingRule[] = [];
  performanceRules: PerformanceRule[] = [];
  
  // 过滤后的数据列表
  filteredWorkflowStages: WorkflowStage[] = [];
  filteredSOPTemplates: SOPTemplate[] = [];
  filteredPricingRules: PricingRule[] = [];
  filteredPerformanceRules: PerformanceRule[] = [];
  
  // 核心阶段（用于横向时间轴显示 1~4 阶段）
  coreWorkflowStages: WorkflowStage[] = [];
  
  // 常用指标
  performanceMetrics = ['项目完成率', '客户满意度', '按时交付率', '产值'];
  // 新增：分类选项
  sopCategories: string[] = ['客户接入', '项目开发', '运维保障', '质量流程'];
  pricingCategories: string[] = ['设计', '开发', '服务', '其他'];
  
  // 批量模式状态与选择集（用于模板绑定）
  isBulkMode: boolean = false;
  bulkSelectedIds: Set<string> = new Set<string>();
  get bulkSelectedCount(): number { return this.bulkSelectedIds.size; }
  
  // 图表实例引用
  @ViewChild('dataUsageChart') private dataUsageChart!: ElementRef;
  @ViewChild('backupHistoryChart') private backupHistoryChart!: ElementRef;
  @ViewChild('systemPerformanceChart') private systemPerformanceChart!: ElementRef;
  
  // 数据统计信息
  systemStats = {
    totalDataSize: 128,
    usedDataSize: 76,
    backupCount: 12,
    activeUsers: 32,
    systemUptime: '99.9%',
    lastBackup: '2025-09-15 02:00:00'
  };
  
  // 系统配置选项
  systemOptions = {
    enableAuditLog: true,
    enableNotification: true,
    autoBackupEnabled: true,
    backupFrequency: 'daily',
    dataRetentionDays: 365,
    enableDataExport: true
  };
  
  // 备份历史数据
  backupHistory = [
    { date: '2025-09-15', size: 6.2, status: 'success' },
    { date: '2025-09-14', size: 6.1, status: 'success' },
    { date: '2025-09-13', size: 6.0, status: 'success' },
    { date: '2025-09-12', size: 5.9, status: 'success' },
    { date: '2025-09-11', size: 5.8, status: 'success' },
    { date: '2025-09-10', size: 5.7, status: 'warning' },
    { date: '2025-09-09', size: 5.6, status: 'success' },
    { date: '2025-09-08', size: 5.5, status: 'error' },
    { date: '2025-09-07', size: 5.4, status: 'success' },
    { date: '2025-09-06', size: 5.3, status: 'success' },
    { date: '2025-09-05', size: 5.2, status: 'success' },
    { date: '2025-09-04', size: 5.1, status: 'success' }
  ];
  
  // 系统性能数据
  systemPerformance = [
    { time: '00:00', cpuUsage: 15, memoryUsage: 30, diskIO: 10 },
    { time: '04:00', cpuUsage: 10, memoryUsage: 25, diskIO: 5 },
    { time: '08:00', cpuUsage: 25, memoryUsage: 40, diskIO: 25 },
    { time: '12:00', cpuUsage: 40, memoryUsage: 55, diskIO: 45 },
    { time: '16:00', cpuUsage: 35, memoryUsage: 50, diskIO: 40 },
    { time: '20:00', cpuUsage: 20, memoryUsage: 35, diskIO: 20 }
  ];
  
  // 数据类型分布
  dataDistribution = [
    { name: '项目数据', value: 35 },
    { name: '客户数据', value: 25 },
    { name: '日志数据', value: 20 },
    { name: '配置数据', value: 10 },
    { name: '其他数据', value: 10 }
  ];
  
  constructor(private dialog: MatDialog) {}
  
  ngOnInit(): void {
    // 加载各类数据
    this.loadWorkflowStages();
    this.loadSOPTemplates();
    this.loadPricingRules();
    this.loadPerformanceRules();
    this.loadSystemOptions();
    
    // 初始化图表（延迟初始化，确保DOM已经加载）
    setTimeout(() => {
      this.initDataUsageChart();
      this.initBackupHistoryChart();
      this.initSystemPerformanceChart();
    }, 100);
  }
  
  // 切换标签页
  switchTab(tab: string): void {
    this.activeTab = tab;
  }
  
  // 加载工作流阶段数据
  loadWorkflowStages(): void {
    this.workflowStages = [
      {
        id: '1',
        name: '需求沟通',
        order: 1,
        description: '与客户沟通需求，了解项目背景和期望',
        isActive: true
      },
      {
        id: '2',
        name: '方案设计',
        order: 2,
        description: '根据需求设计解决方案和技术架构',
        isActive: true
      },
      {
        id: '3',
        name: '开发实现',
        order: 3,
        description: '按照方案进行开发和实现',
        isActive: true
      },
      {
        id: '4',
        name: '测试验证',
        order: 4,
        description: '对开发结果进行测试和验证',
        isActive: true
      },
      {
        id: '5',
        name: '部署上线',
        order: 5,
        description: '将项目部署到生产环境',
        isActive: true
      },
      {
        id: '6',
        name: '运维维护',
        order: 6,
        description: '项目上线后的运行维护和优化',
        isActive: true
      }
    ];
    this.onWorkflowSearch();
    // 计算核心阶段（1~4）用于时间轴
    this.coreWorkflowStages = this.workflowStages
      .filter(s => s.order >= 1 && s.order <= 4)
      .sort((a, b) => a.order - b.order);
  }
  
  // 加载SOP模板数据
  loadSOPTemplates(): void {
    this.sopTemplates = [
      {
        id: '1',
        name: '新客户接入流程',
        description: '规范新客户从接触到签约的全流程',
        steps: [
          '初步接触与需求了解',
          '提供解决方案与报价',
          '商务谈判',
          '签订合同',
          '客户信息录入系统',
          '启动项目'
        ],
        category: '客户接入',
        isActive: true
      },
      {
        id: '2',
        name: '项目开发流程',
        description: '标准项目开发的流程规范',
        steps: [
          '需求分析与文档编写',
          '系统设计',
          '编码实现',
          '单元测试',
          '集成测试',
          '系统测试',
          '用户验收测试',
          '上线部署'
        ],
        category: '项目开发',
        isActive: true
      },
      {
        id: '3',
        name: '上线运维流程',
        description: '项目上线后的运维与监控流程',
        steps: [
          '上线准备',
          '监控配置',
          '告警设置',
          '备份策略',
          '应急预案'
        ],
        category: '运维保障',
        isActive: true
      }
    ];
    this.onSOPSearch();
  }
  
  // 加载报价规则数据
  loadPricingRules(): void {
    this.pricingRules = [
      {
        id: '1',
        name: '基础设计报价',
        description: '按面积与复杂度计算设计报价',
        category: '设计',
        formula: '基础费 + 面积 * 设计单价 * 复杂度系数',
        isActive: true
      },
      {
        id: '2',
        name: '开发功能报价',
        description: '按功能点与工期评估开发报价',
        category: '开发',
        formula: '功能点数 * 功能单价 + 预估工期 * 人日单价',
        isActive: true
      },
      {
        id: '3',
        name: '维保服务报价',
        description: '按服务等级与响应时间计算报价',
        category: '服务',
        formula: '服务等级系数 * 基础费 + 响应时间系数 * 附加费',
        isActive: true
      }
    ];
    this.onPricingSearch();
  }
  
  // 加载绩效规则数据
  loadPerformanceRules(): void {
    this.performanceRules = [
      {
        id: '1',
        name: '项目按时完成率',
        description: '评估项目是否按时完成',
        metric: '按时交付率',
        threshold: 90,
        reward: '绩效加分10分',
        isActive: true
      },
      {
        id: '2',
        name: '客户满意度',
        description: '评估客户对服务的满意程度',
        metric: '客户满意度',
        threshold: 95,
        reward: '绩效加分15分',
        isActive: true
      },
      {
        id: '3',
        name: '项目完成质量',
        description: '评估项目交付质量',
        metric: '项目完成率',
        threshold: 85,
        reward: '绩效加分12分',
        isActive: true
      }
    ];
    this.onPerformanceSearch();
  }
  
  // 加载系统配置
  loadSystemOptions(): void {
    // 这里可以添加从后端加载配置的逻辑
    // 目前使用的是模拟数据
  }
  
  // 打开工作流阶段对话框
  openWorkflowDialog(stage?: WorkflowStage): void {
    const dialogRef = this.dialog.open(SettingDialogComponent, {
      width: '720px',
      data: {
        type: 'workflow',
        item: stage ? { ...stage } : {
          id: '',
          name: '',
          order: this.workflowStages.length + 1,
          description: '',
          isActive: true
        }
      }
    });

    dialogRef.afterClosed().subscribe((result: WorkflowStage | undefined) => {
      if (result) {
        this.saveSetting('workflow', result);
      }
    });
  }
  
  // 打开SOP模板对话框
  openSOPDialog(template?: SOPTemplate): void {
    const dialogRef = this.dialog.open(SettingDialogComponent, {
      width: '880px',
      data: {
        type: 'sop',
        categories: this.sopCategories,
        item: template ? { ...template } : {
          id: '',
          name: '',
          description: '',
          steps: [],
          category: this.sopCategories[0],
          isActive: true
        }
      }
    });

    dialogRef.afterClosed().subscribe((result: SOPTemplate | undefined) => {
      if (result) {
        this.saveSetting('sop', result);
      }
    });
  }
  
  // 打开报价规则对话框
  openPricingDialog(rule?: PricingRule): void {
    const dialogRef = this.dialog.open(SettingDialogComponent, {
      width: '720px',
      data: {
        type: 'pricing',
        categories: this.pricingCategories,
        item: rule ? { ...rule } : {
          id: '',
          name: '',
          description: '',
          category: this.pricingCategories[0],
          formula: '',
          isActive: true
        }
      }
    });

    dialogRef.afterClosed().subscribe((result: PricingRule | undefined) => {
      if (result) {
        this.saveSetting('pricing', result);
      }
    });
  }
  
  // 打开绩效规则对话框
  openPerformanceDialog(rule?: PerformanceRule): void {
    const dialogRef = this.dialog.open(SettingDialogComponent, {
      width: '720px',
      data: {
        type: 'performance',
        metrics: this.performanceMetrics,
        item: rule ? { ...rule } : {
          id: '',
          name: '',
          description: '',
          metric: this.performanceMetrics[0],
          threshold: 80,
          reward: '基础绩效 * 1.2',
          isActive: true
        }
      }
    });

    dialogRef.afterClosed().subscribe((result: PerformanceRule | undefined) => {
      if (result) {
        this.saveSetting('performance', result);
      }
    });
  }
  
  // 顶部批量操作菜单入口
  onBulkAction(): void {
    this.enterBulkMode();
  }
  
  // 进入/退出批量模式
  enterBulkMode(): void {
    this.isBulkMode = true;
    this.bulkSelectedIds.clear();
  }
  exitBulkMode(): void {
    this.isBulkMode = false;
    this.bulkSelectedIds.clear();
  }

  // 选择与全选
  toggleSelectWorkflow(id: string, checked: boolean): void {
    if (checked) {
      this.bulkSelectedIds.add(id);
    } else {
      this.bulkSelectedIds.delete(id);
    }
  }
  isSelectedWorkflow(id: string): boolean {
    return this.bulkSelectedIds.has(id);
  }
  selectAllVisibleWorkflow(): void {
    // 当前 UI 显示为核心阶段 1~4
    this.coreWorkflowStages.forEach(s => this.bulkSelectedIds.add(s.id));
  }
  clearSelectionWorkflow(): void {
    this.bulkSelectedIds.clear();
  }

  // 批量启用/禁用
  bulkEnableWorkflow(enable: boolean): void {
    if (this.bulkSelectedIds.size === 0) return;
    const set = this.bulkSelectedIds;
    this.workflowStages = this.workflowStages.map(s =>
      set.has(s.id) ? { ...s, isActive: enable } : s
    );
    this.onWorkflowSearch();
    this.recalcCoreWorkflowStages();
    console.log(`批量${enable ? '启用' : '禁用'}完成：${set.size} 项`);
  }

  // 批量删除
  bulkDeleteWorkflow(): void {
    if (this.bulkSelectedIds.size === 0) return;
    const names = this.workflowStages.filter(s => this.bulkSelectedIds.has(s.id)).map(s => s.name);
    const preview = names.slice(0, 5).join('、') + (names.length > 5 ? ` 等 ${names.length} 项` : '');
    if (confirm(`确认删除以下阶段？\n${preview}`)) {
      this.workflowStages = this.workflowStages.filter(s => !this.bulkSelectedIds.has(s.id));
      this.onWorkflowSearch();
      this.recalcCoreWorkflowStages();
      this.clearSelectionWorkflow();
    }
  }

  // 批量复制
  bulkCopyWorkflow(): void {
    if (this.bulkSelectedIds.size === 0) return;
    const selected = this.workflowStages.filter(s => this.bulkSelectedIds.has(s.id)).sort((a,b)=>a.order-b.order);
    const maxId = this.workflowStages.reduce((m, s) => Math.max(m, parseInt(s.id, 10) || 0), 0);
    let nextId = maxId + 1;
    const maxOrder = this.workflowStages.reduce((m, s) => Math.max(m, s.order), 0);
    let nextOrder = maxOrder + 1;
    const clones: WorkflowStage[] = selected.map(s => ({
      ...s,
      id: String(nextId++),
      name: `${s.name} (副本)`,
      order: nextOrder++,
    }));
    this.workflowStages = [...this.workflowStages, ...clones];
    this.onWorkflowSearch();
    this.recalcCoreWorkflowStages();
    console.log(`已复制 ${clones.length} 项`);
  }

  // 批量排序：输入起始序号，按当前显示顺序依次编号
  bulkSortWorkflow(): void {
    if (this.bulkSelectedIds.size === 0) return;
    const selected = this.workflowStages.filter(s => this.bulkSelectedIds.has(s.id)).sort((a,b)=>a.order-b.order);
    const minOrder = selected.reduce((m,s)=>Math.min(m,s.order), selected[0].order);
    const input = prompt(`请输入起始序号（默认 ${minOrder}）`, String(minOrder));
    const start = input ? parseInt(input, 10) : minOrder;
    if (!Number.isFinite(start)) return;
    let current = start;
    const idSet = new Set(selected.map(s=>s.id));
    this.workflowStages = this.workflowStages.map(s => {
      if (idSet.has(s.id)) {
        return { ...s, order: current++ };
      }
      return s;
    });
    // 二次排序保证整体序号稳定
    this.workflowStages.sort((a,b)=>a.order-b.order);
    this.onWorkflowSearch();
    this.recalcCoreWorkflowStages();
  }

  // 批量导出 JSON
  bulkExportWorkflow(): void {
    if (this.bulkSelectedIds.size === 0) return;
    const data = this.workflowStages.filter(s => this.bulkSelectedIds.has(s.id));
    const json = JSON.stringify(data, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'workflow-stages-export.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  // 计算核心阶段（1~4）
  recalcCoreWorkflowStages(): void {
    this.coreWorkflowStages = this.workflowStages
      .filter(s => s.order >= 1 && s.order <= 4)
      .sort((a, b) => a.order - b.order);
  }

  // 名称缩写：用于时间轴标签
  getStageAbbr(name: string): string {
    const map: Record<string, string> = {
      '需求沟通': '需求',
      '方案设计': '方设',
      '开发实现': '开实',
      '测试验证': '测验',
      '部署上线': '部署',
      '运维维护': '运维'
    };
    if (map[name]) return map[name];
    const ascii = name.match(/[A-Za-z]+/g);
    if (ascii && ascii.length) {
      return ascii.map(s => s[0]).join('').slice(0, 3).toUpperCase();
    }
    return name.slice(0, 2);
  }
  
  // 保存设置项
  saveSetting(type: string, updatedItem: any): void {
    switch (type) {
      case 'workflow':
        if (updatedItem.id) {
          // 更新现有阶段
          this.workflowStages = this.workflowStages.map(stage => 
            stage.id === updatedItem.id ? updatedItem : stage
          );
        } else {
          // 添加新阶段
          updatedItem.id = (this.workflowStages.length + 1).toString();
          this.workflowStages.push(updatedItem);
        }
        this.onWorkflowSearch();
        break;
      case 'sop':
        if (updatedItem.id) {
          // 更新现有模板
          this.sopTemplates = this.sopTemplates.map(template => 
            template.id === updatedItem.id ? updatedItem : template
          );
        } else {
          // 添加新模板
          updatedItem.id = (this.sopTemplates.length + 1).toString();
          this.sopTemplates.push(updatedItem);
        }
        this.onSOPSearch();
        break;
      case 'pricing':
        if (updatedItem.id) {
          // 更新现有规则
          this.pricingRules = this.pricingRules.map(rule => 
            rule.id === updatedItem.id ? updatedItem : rule
          );
        } else {
          // 添加新规则
          updatedItem.id = (this.pricingRules.length + 1).toString();
          this.pricingRules.push(updatedItem);
        }
        this.onPricingSearch();
        break;
      case 'performance':
        if (updatedItem.id) {
          // 更新现有规则
          this.performanceRules = this.performanceRules.map(rule => 
            rule.id === updatedItem.id ? updatedItem : rule
          );
        } else {
          // 添加新规则
          updatedItem.id = (this.performanceRules.length + 1).toString();
          this.performanceRules.push(updatedItem);
        }
        this.onPerformanceSearch();
        break;
    }
  }
  
  // 删除设置项
  deleteSetting(type: string, id: string): void {
    if (confirm('确定要删除此项设置吗？')) {
      switch (type) {
        case 'workflow':
          this.workflowStages = this.workflowStages.filter(stage => stage.id !== id);
          this.onWorkflowSearch();
          break;
        case 'sop':
          this.sopTemplates = this.sopTemplates.filter(template => template.id !== id);
          this.onSOPSearch();
          break;
        case 'pricing':
          this.pricingRules = this.pricingRules.filter(rule => rule.id !== id);
          this.onPricingSearch();
          break;
        case 'performance':
          this.performanceRules = this.performanceRules.filter(rule => rule.id !== id);
          this.onPerformanceSearch();
          break;
      }
    }
  }
  
  // 更新设置项的激活状态
  toggleActive(type: string, id: string, isActive: boolean): void {
    switch (type) {
      case 'workflow':
        this.workflowStages = this.workflowStages.map(stage => 
          stage.id === id ? { ...stage, isActive } : stage
        );
        this.onWorkflowSearch();
        break;
      case 'sop':
        this.sopTemplates = this.sopTemplates.map(template => 
          template.id === id ? { ...template, isActive } : template
        );
        this.onSOPSearch();
        break;
      case 'pricing':
        this.pricingRules = this.pricingRules.map(rule => 
          rule.id === id ? { ...rule, isActive } : rule
        );
        this.onPricingSearch();
        break;
      case 'performance':
        this.performanceRules = this.performanceRules.map(rule => 
          rule.id === id ? { ...rule, isActive } : rule
        );
        this.onPerformanceSearch();
        break;
    }
  }
  
  // 搜索工作流阶段
  onWorkflowSearch(): void {
    if (!this.workflowSearchTerm.trim()) {
      this.filteredWorkflowStages = this.workflowStages;
    } else {
      const searchTerm = this.workflowSearchTerm.toLowerCase();
      this.filteredWorkflowStages = this.workflowStages.filter(
        stage => stage.name.toLowerCase().includes(searchTerm) || 
                 stage.description.toLowerCase().includes(searchTerm)
      );
    }
  }
  
  // 搜索SOP模板
  onSOPSearch(): void {
    if (!this.sopSearchTerm.trim()) {
      this.filteredSOPTemplates = this.sopTemplates;
    } else {
      const searchTerm = this.sopSearchTerm.toLowerCase();
      this.filteredSOPTemplates = this.sopTemplates.filter(
        template => template.name.toLowerCase().includes(searchTerm) || 
                    template.description.toLowerCase().includes(searchTerm) ||
                    template.steps.some(step => step.toLowerCase().includes(searchTerm))
      );
    }
  }
  
  // 搜索报价规则
  onPricingSearch(): void {
    if (!this.pricingSearchTerm.trim()) {
      this.filteredPricingRules = this.pricingRules;
    } else {
      const searchTerm = this.pricingSearchTerm.toLowerCase();
      this.filteredPricingRules = this.pricingRules.filter(
        rule => rule.name.toLowerCase().includes(searchTerm) || 
                rule.description.toLowerCase().includes(searchTerm) ||
                rule.formula.toLowerCase().includes(searchTerm) ||
                rule.category.toLowerCase().includes(searchTerm)
      );
    }
  }
  
  // 搜索绩效规则
  onPerformanceSearch(): void {
    if (!this.performanceSearchTerm.trim()) {
      this.filteredPerformanceRules = this.performanceRules;
    } else {
      const searchTerm = this.performanceSearchTerm.toLowerCase();
      this.filteredPerformanceRules = this.performanceRules.filter(
        rule => rule.name.toLowerCase().includes(searchTerm) || 
                rule.description.toLowerCase().includes(searchTerm) ||
                rule.metric.toLowerCase().includes(searchTerm)
      );
    }
  }
  
  // 保存系统配置
  saveSystemOptions(): void {
    console.log('保存系统配置:', this.systemOptions);
    // 这里可以添加保存到后端的逻辑
    alert('系统配置保存成功！');
  }
  
  // 初始化数据使用情况图表
  initDataUsageChart(): void {
    if (echarts && this.dataUsageChart) {
      const chart = echarts.init(this.dataUsageChart.nativeElement);
      
      const option = {
        title: {
          text: '数据存储使用情况',
          left: 'center',
          textStyle: {
            fontWeight: 'normal',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}GB ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 'center'
        },
        series: [
          {
            name: '数据存储',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 18,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {
                value: this.systemStats.usedDataSize,
                name: '已使用',
                itemStyle: { color: '#165DFF' }
              },
              {
                value: this.systemStats.totalDataSize - this.systemStats.usedDataSize,
                name: '未使用',
                itemStyle: { color: '#E5E6EB' }
              }
            ]
          },
          {
            name: '数据类型分布',
            type: 'pie',
            radius: ['15%', '30%'],
            center: ['75%', '60%'],
            data: this.dataDistribution,
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: false
            }
          }
        ]
      };
      
      chart.setOption(option);
      
      // 响应式调整
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }
  }
  
  // 初始化备份历史图表
  initBackupHistoryChart(): void {
    if (echarts && this.backupHistoryChart) {
      const chart = echarts.init(this.backupHistoryChart.nativeElement);
      
      const dates = this.backupHistory.map(item => item.date);
      const sizes = this.backupHistory.map(item => item.size);
      const statusColors = this.backupHistory.map(item => {
        switch(item.status) {
          case 'success': return '#00B42A';
          case 'warning': return '#FFAA00';
          case 'error': return '#F53F3F';
          default: return '#86909C';
        }
      });
      
      const option = {
        title: {
          text: '备份历史记录',
          left: 'center',
          textStyle: {
            fontWeight: 'normal',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: (params: any) => {
            const data = params[0];
            const statusItem = this.backupHistory[data.dataIndex];
            const statusText: Record<string, string> = {
              'success': '成功',
              'warning': '警告',
              'error': '失败'
            };
            return `${data.name}<br/>备份大小: ${data.value}GB<br/>状态: ${statusText[statusItem.status]}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '备份大小 (GB)',
          min: 0
        },
        series: [
          {
            name: '备份大小',
            type: 'line',
            smooth: true,
            data: sizes,
            lineStyle: {
              width: 3,
              color: '#165DFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(22, 93, 255, 0.3)'
                },
                {
                  offset: 1,
                  color: 'rgba(22, 93, 255, 0.05)'
                }
              ])
            },
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: function(params: any) {
                return statusColors[params.dataIndex];
              }
            }
          }
        ]
      };
      
      chart.setOption(option);
      
      // 响应式调整
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }
  }
  
  // 初始化系统性能图表
  initSystemPerformanceChart(): void {
    if (echarts && this.systemPerformanceChart) {
      const chart = echarts.init(this.systemPerformanceChart.nativeElement);
      
      const times = this.systemPerformance.map(item => item.time);
      const cpuUsage = this.systemPerformance.map(item => item.cpuUsage);
      const memoryUsage = this.systemPerformance.map(item => item.memoryUsage);
      const diskIO = this.systemPerformance.map(item => item.diskIO);
      
      const option = {
        title: {
          text: '系统性能监控',
          left: 'center',
          textStyle: {
            fontWeight: 'normal',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['CPU使用率', '内存使用率', '磁盘IO'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times
        },
        yAxis: {
          type: 'value',
          name: '使用率 (%)',
          min: 0,
          max: 100
        },
        series: [
          {
            name: 'CPU使用率',
            type: 'line',
            stack: 'Total',
            data: cpuUsage,
            lineStyle: {
              color: '#165DFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(22, 93, 255, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(22, 93, 255, 0.1)'
                }
              ])
            }
          },
          {
            name: '内存使用率',
            type: 'line',
            stack: 'Total',
            data: memoryUsage,
            lineStyle: {
              color: '#722ED1'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(114, 46, 209, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(114, 46, 209, 0.1)'
                }
              ])
            }
          },
          {
            name: '磁盘IO',
            type: 'line',
            stack: 'Total',
            data: diskIO,
            lineStyle: {
              color: '#F7BA1E'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(247, 186, 30, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(247, 186, 30, 0.1)'
                }
              ])
            }
          }
        ]
      };
      
      chart.setOption(option);
      
      // 响应式调整
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }
  }
}