import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { EmployeeService } from '../services/employee.service';
import { DepartmentService } from '../services/department.service';

interface Employee {
  id: string;
  name: string;
  mobile: string;
  userid: string;
  roleName: string;
  department: string;
  departmentId?: string;
  isDisabled?: boolean;
  createdAt?: Date;
}

interface Department {
  id: string;
  name: string;
}

@Component({
  selector: 'app-employees',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './employees.html',
  styleUrls: ['./employees.scss']
})
export class Employees implements OnInit {
  // 数据
  employees = signal<Employee[]>([]);
  departments = signal<Department[]>([]);
  loading = signal(false);

  // 筛选
  keyword = signal('');
  roleFilter = signal<string>('all');

  // 侧边面板
  showPanel = false;
  panelMode: 'detail' | 'edit' = 'detail';
  currentEmployee: Employee | null = null;
  formModel: Partial<Employee> = {};

  // 统计 - 按身份统计
  stats = {
    total: signal(0),
    service: signal(0), // 客服
    designer: signal(0), // 组员(设计师)
    leader: signal(0), // 组长
    hr: signal(0), // 人事
    finance: signal(0) // 财务
  };

  // 角色列表
  roles = ['客服', '组员', '组长', '人事', '财务','管理员'];

  constructor(
    private employeeService: EmployeeService,
    private departmentService: DepartmentService
  ) {}

  ngOnInit(): void {
    this.loadEmployees();
    this.loadDepartments();
  }

  async loadEmployees(): Promise<void> {
    this.loading.set(true);
    try {
      const emps = await this.employeeService.findEmployees();

      const empList: Employee[] = emps.map(e => {
        const json = this.employeeService.toJSON(e);
        return {
          id: json.objectId,
          name: json.name || '未知',
          mobile: json.mobile || '',
          userid: json.userid || '',
          roleName: json.roleName || '未分配',
          department: e.get("department")?.get("name") || '未分配',
          departmentId: e.get("department")?.id,
          isDisabled: json.isDisabled || false,
          createdAt: json.createdAt
        };
      });

      this.employees.set(empList);

      // 更新统计
      this.stats.total.set(empList.length);
      this.stats.service.set(empList.filter(e => e.roleName === '客服').length);
      this.stats.designer.set(empList.filter(e => e.roleName === '组员').length);
      this.stats.leader.set(empList.filter(e => e.roleName === '组长').length);
      this.stats.hr.set(empList.filter(e => e.roleName === '人事').length);
      this.stats.finance.set(empList.filter(e => e.roleName === '财务').length);
    } catch (error) {
      console.error('加载员工列表失败:', error);
    } finally {
      this.loading.set(false);
    }
  }

  async loadDepartments(): Promise<void> {
    try {
      const depts = await this.departmentService.findDepartments();
      this.departments.set(
        depts.map(d => {
          const json = this.departmentService.toJSON(d);
          return {
            id: json.objectId,
            name: json.name
          };
        })
      );
    } catch (error) {
      console.error('加载部门列表失败:', error);
    }
  }

  get filtered() {
    const kw = this.keyword().trim().toLowerCase();
    const role = this.roleFilter();

    let list = this.employees();

    if (role !== 'all') {
      list = list.filter(e => e.roleName === role);
    }

    if (kw) {
      list = list.filter(
        e =>
          e.name.toLowerCase().includes(kw) ||
          e.mobile.includes(kw) ||
          e.userid.toLowerCase().includes(kw)
      );
    }

    return list;
  }

  setRoleFilter(role: string) {
    this.roleFilter.set(role);
  }

  resetFilters() {
    this.keyword.set('');
    this.roleFilter.set('all');
  }

  // 查看详情
  viewEmployee(emp: Employee) {
    this.currentEmployee = emp;
    this.panelMode = 'detail';
    this.showPanel = true;
  }

  // 编辑 (员工从企微同步，只能编辑部分字段，不能删除)
  editEmployee(emp: Employee) {
    this.currentEmployee = emp;
    this.formModel = { ...emp };
    this.panelMode = 'edit';
    this.showPanel = true;
  }

  // 关闭面板
  closePanel() {
    this.showPanel = false;
    this.panelMode = 'detail';
    this.currentEmployee = null;
    this.formModel = {};
  }

  // 提交编辑
  async updateEmployee() {
    if (!this.currentEmployee) return;

    try {
      await this.employeeService.updateEmployee(this.currentEmployee.id, {
        roleName: this.formModel.roleName,
        departmentId: this.formModel.departmentId,
        isDisabled: this.formModel.isDisabled
      });

      await this.loadEmployees();
      this.closePanel();
    } catch (error) {
      console.error('更新员工失败:', error);
      alert('更新员工失败，请重试');
    }
  }

  // 禁用/启用员工
  async toggleEmployee(emp: Employee) {
    const action = emp.isDisabled ? '启用' : '禁用';
    if (!confirm(`确定要${action}员工 "${emp.name}" 吗？`)) {
      return;
    }

    try {
      await this.employeeService.toggleEmployee(emp.id, !emp.isDisabled);
      await this.loadEmployees();
    } catch (error) {
      console.error(`${action}员工失败:`, error);
      alert(`${action}员工失败，请重试`);
    }
  }

  // 导出
  exportEmployees() {
    const header = ['姓名', '手机号', '企微ID', '身份', '部门', '状态', '创建时间'];
    const rows = this.filtered.map(e => [
      e.name,
      e.mobile,
      e.userid,
      e.roleName,
      e.department,
      e.isDisabled ? '已禁用' : '正常',
      e.createdAt instanceof Date
        ? e.createdAt.toISOString().slice(0, 10)
        : String(e.createdAt || '')
    ]);

    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);
  }
}
