import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';

// 设计师接口定义
interface Designer {
  id: string;
  name: string;
  avatar: string;
  email: string;
  phone: string;
  department: string;
  level: 'junior' | 'intermediate' | 'senior' | 'expert';
  skills: string[];
  status: 'active' | 'inactive' | 'busy';
  projectCount: number;
  completionRate: number;
  satisfactionScore: number;
  joinDate: Date;
  lastActiveDate: Date;
}

@Component({
  selector: 'app-designers',
  standalone: true,
  imports: [CommonModule, RouterModule, FormsModule],
  templateUrl: './designers.html',
  styleUrl: './designers.scss'
})
export class Designers implements OnInit {
  // 设计师数据
  designers = signal<Designer[]>([
    {
      id: '1',
      name: '张小美',
      avatar: 'data:image/svg+xml,%3Csvg width="40" height="40" xmlns="http://www.w3.org/2000/svg"%3E%3Crect width="100%25" height="100%25" fill="%23FFE6CC"/%3E%3Ctext x="50%25" y="50%25" font-family="Arial" font-size="14" font-weight="bold" text-anchor="middle" fill="%23FF7D00" dy="0.3em"%3E张%3C/text%3E%3C/svg%3E',
      email: 'zhang.xiaomei@company.com',
      phone: '138****1234',
      department: '室内设计部',
      level: 'senior',
      skills: ['室内设计', '3D建模', 'AutoCAD', 'SketchUp'],
      status: 'active',
      projectCount: 15,
      completionRate: 95,
      satisfactionScore: 4.8,
      joinDate: new Date('2022-03-15'),
      lastActiveDate: new Date()
    },
    {
      id: '2',
      name: '李设计',
      avatar: 'data:image/svg+xml,%3Csvg width="40" height="40" xmlns="http://www.w3.org/2000/svg"%3E%3Crect width="100%25" height="100%25" fill="%23E6F7FF"/%3E%3Ctext x="50%25" y="50%25" font-family="Arial" font-size="14" font-weight="bold" text-anchor="middle" fill="%23165DFF" dy="0.3em"%3E李%3C/text%3E%3C/svg%3E',
      email: 'li.sheji@company.com',
      phone: '139****5678',
      department: '建筑设计部',
      level: 'expert',
      skills: ['建筑设计', 'Revit', 'Rhino', '参数化设计'],
      status: 'busy',
      projectCount: 22,
      completionRate: 98,
      satisfactionScore: 4.9,
      joinDate: new Date('2021-08-20'),
      lastActiveDate: new Date()
    },
    {
      id: '3',
      name: '王创意',
      avatar: 'data:image/svg+xml,%3Csvg width="40" height="40" xmlns="http://www.w3.org/2000/svg"%3E%3Crect width="100%25" height="100%25" fill="%23F0F9FF"/%3E%3Ctext x="50%25" y="50%25" font-family="Arial" font-size="14" font-weight="bold" text-anchor="middle" fill="%234E5BA6" dy="0.3em"%3E王%3C/text%3E%3C/svg%3E',
      email: 'wang.chuangyi@company.com',
      phone: '137****9012',
      department: '景观设计部',
      level: 'intermediate',
      skills: ['景观设计', 'Lumion', 'Photoshop', '手绘'],
      status: 'active',
      projectCount: 8,
      completionRate: 92,
      satisfactionScore: 4.6,
      joinDate: new Date('2023-01-10'),
      lastActiveDate: new Date()
    }
  ]);

  // 筛选和搜索
  searchTerm = signal('');
  selectedDepartment = signal('all');
  selectedLevel = signal('all');
  selectedStatus = signal('all');

  // 统计数据
  totalDesigners = signal(24);
  activeDesigners = signal(18);
  busyDesigners = signal(4);
  inactiveDesigners = signal(2);

  // 部门列表
  departments = ['室内设计部', '建筑设计部', '景观设计部', '平面设计部'];

  // 侧边面板状态
  showPanel: boolean = false;
  panelMode: 'add' | 'detail' | 'edit' = 'add';
  currentDesigner: Designer | null = null;
  formModel: (Partial<Designer> & { skillsInput?: string }) = {};

  ngOnInit(): void {
    this.loadDesigners();
  }

  loadDesigners(): void {
    // 在实际应用中，这里会从服务加载数据
    console.log('加载设计师数据');
  }

  // 筛选设计师
  get filteredDesigners() {
    return this.designers().filter(designer => {
      const matchesSearch = designer.name.toLowerCase().includes(this.searchTerm().toLowerCase()) ||
                           designer.email.toLowerCase().includes(this.searchTerm().toLowerCase());
      const matchesDepartment = this.selectedDepartment() === 'all' || designer.department === this.selectedDepartment();
      const matchesLevel = this.selectedLevel() === 'all' || designer.level === this.selectedLevel();
      const matchesStatus = this.selectedStatus() === 'all' || designer.status === this.selectedStatus();
      
      return matchesSearch && matchesDepartment && matchesLevel && matchesStatus;
    });
  }

  // 获取等级显示文本
  getLevelText(level: string): string {
    const levelMap: { [key: string]: string } = {
      'junior': '初级',
      'intermediate': '中级',
      'senior': '高级',
      'expert': '专家'
    };
    return levelMap[level] || level;
  }

  // 获取状态显示文本
  getStatusText(status: string): string {
    const statusMap: { [key: string]: string } = {
      'active': '在线',
      'inactive': '离线',
      'busy': '忙碌'
    };
    return statusMap[status] || status;
  }

  // 获取状态样式类
  getStatusClass(status: string): string {
    return `status-${status}`;
  }

  // 查看设计师详情
  viewDesigner(designer: Designer): void {
    this.currentDesigner = designer;
    this.panelMode = 'detail';
    this.showPanel = true;
  }

  // 编辑设计师
  editDesigner(designer: Designer): void {
    this.currentDesigner = designer;
    this.formModel = { ...designer };
    this.panelMode = 'edit';
    this.showPanel = true;
  }

  // 关闭面板
  closePanel(): void {
    this.showPanel = false;
    this.panelMode = 'add';
    this.currentDesigner = null;
    this.formModel = {};
  }

  // 保存新增
  saveDesigner(): void {
    const name = (this.formModel.name || '').trim();
    if (!name) {
      alert('请输入姓名');
      return;
    }
    const newDesigner: Designer = {
      id: Date.now().toString(),
      name,
      avatar:
        `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="100%" height="100%" fill="%23F0F9FF"/><text x="50%" y="50%" font-family="Arial" font-size="14" font-weight="bold" text-anchor="middle" fill="%234E5BA6" dy="0.35em">${name.charAt(0)}</text></svg>`,
      email: this.formModel.email || '',
      phone: this.formModel.phone || '',
      department: (this.formModel.department as Designer['department']) || '室内设计部',
      level: (this.formModel.level as Designer['level']) || 'junior',
      skills: Array.isArray(this.formModel.skills) ? (this.formModel.skills as string[]) : ((this.formModel as any).skillsInput ? String((this.formModel as any).skillsInput).split(',').map(s=>s.trim()).filter(Boolean) : []),
      status: (this.formModel.status as Designer['status']) || 'active',
      projectCount: Number(this.formModel.projectCount || 0),
      completionRate: Number(this.formModel.completionRate || 0),
      satisfactionScore: Number(this.formModel.satisfactionScore || 5),
      joinDate: this.formModel.joinDate instanceof Date ? this.formModel.joinDate : new Date(),
      lastActiveDate: new Date()
    };
    this.designers.set([newDesigner, ...this.designers()]);
    this.totalDesigners.set(this.totalDesigners() + 1);
    if (newDesigner.status === 'active') this.activeDesigners.set(this.activeDesigners() + 1);
    if (newDesigner.status === 'busy') this.busyDesigners.set(this.busyDesigners() + 1);
    if (newDesigner.status === 'inactive') this.inactiveDesigners.set(this.inactiveDesigners() + 1);
    this.closePanel();
  }

  // 提交编辑
  updateDesigner(): void {
    if (!this.currentDesigner) return;
    const updated: Designer = {
      ...this.currentDesigner,
      name: (this.formModel.name ?? this.currentDesigner.name) as string,
      email: (this.formModel.email ?? this.currentDesigner.email) as string,
      phone: (this.formModel.phone ?? this.currentDesigner.phone) as string,
      department: (this.formModel.department ?? this.currentDesigner.department) as Designer['department'],
      level: (this.formModel.level ?? this.currentDesigner.level) as Designer['level'],
      status: (this.formModel.status ?? this.currentDesigner.status) as Designer['status'],
      skills: Array.isArray(this.formModel.skills)
        ? (this.formModel.skills as string[])
        : ((this.formModel as any).skillsInput
            ? String((this.formModel as any).skillsInput).split(',').map(s=>s.trim()).filter(Boolean)
            : this.currentDesigner.skills),
      projectCount: Number(this.formModel.projectCount ?? this.currentDesigner.projectCount),
      completionRate: Number(this.formModel.completionRate ?? this.currentDesigner.completionRate),
      satisfactionScore: Number(this.formModel.satisfactionScore ?? this.currentDesigner.satisfactionScore),
      joinDate: this.formModel.joinDate instanceof Date ? this.formModel.joinDate : this.currentDesigner.joinDate,
      lastActiveDate: this.currentDesigner.lastActiveDate
    };

    // 若状态变更，更新统计
    if (updated.status !== this.currentDesigner.status) {
      const dec = (s: 'active'|'busy'|'inactive') => {
        if (s==='active') this.activeDesigners.set(this.activeDesigners()-1);
        if (s==='busy') this.busyDesigners.set(this.busyDesigners()-1);
        if (s==='inactive') this.inactiveDesigners.set(this.inactiveDesigners()-1);
      };
      const inc = (s: 'active'|'busy'|'inactive') => {
        if (s==='active') this.activeDesigners.set(this.activeDesigners()+1);
        if (s==='busy') this.busyDesigners.set(this.busyDesigners()+1);
        if (s==='inactive') this.inactiveDesigners.set(this.inactiveDesigners()+1);
      };
      dec(this.currentDesigner.status);
      inc(updated.status);
    }

    this.designers.set(this.designers().map(d => d.id === updated.id ? updated : d));
    this.closePanel();
  }

  // 添加新设计师 -> 打开面板
  addDesigner(): void {
    this.formModel = {
      name: '',
      email: '',
      phone: '',
      department: '室内设计部',
      level: 'junior',
      status: 'active',
      projectCount: 0,
      completionRate: 0,
      satisfactionScore: 5,
      joinDate: new Date(),
      skillsInput: ''
    };
    this.currentDesigner = null;
    this.panelMode = 'add';
    this.showPanel = true;
  }

  // 删除设计师
  deleteDesigner(designer: Designer): void {
    if (confirm(`确定要删除设计师 ${designer.name} 吗？`)) {
      const updatedDesigners = this.designers().filter(d => d.id !== designer.id);
      this.designers.set(updatedDesigners);
      console.log('删除设计师:', designer);
    }
  }

  // （已移除重复的新增方法，保留通过侧边面板新增的流程）

  // 导出设计师数据
  exportDesigners(): void {
    const header = [
      '姓名',
      '邮箱',
      '电话',
      '部门',
      '级别',
      '状态',
      '项目数',
      '完工率(%)',
      '满意度',
      '入职日期',
      '最近活跃'
    ];

    const rows = this.filteredDesigners.map(d => [
      d.name,
      d.email,
      d.phone,
      d.department,
      this.getLevelText(d.level),
      this.getStatusText(d.status),
      String(d.projectCount),
      String(d.completionRate),
      String(d.satisfactionScore),
      d.joinDate instanceof Date ? d.joinDate.toISOString().slice(0, 10) : String(d.joinDate),
      d.lastActiveDate instanceof Date ? d.lastActiveDate.toISOString().slice(0, 10) : String(d.lastActiveDate)
    ]);

    this.downloadCSV('设计师列表.csv', [header, ...rows]);
  }

  private downloadCSV(filename: string, rows: (string | number)[][]) {
    const escape = (val: string | number) => {
      const s = String(val ?? '');
      if (/[",\n]/.test(s)) {
        return '"' + s.replace(/"/g, '""') + '"';
      }
      return s;
    };
    const csv = rows.map(r => r.map(escape).join(',')).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;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  }

  // 重置筛选条件
  resetFilters(): void {
    this.searchTerm.set('');
    this.selectedDepartment.set('all');
    this.selectedLevel.set('all');
    this.selectedStatus.set('all');
  }
}