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

interface Customer {
  id: string;
  name: string;
  contact: string;
  phone: string;
  level: 'normal' | 'vip' | 'svip';
  status: 'active' | 'inactive';
  projects: number;
  totalAmount: number;
  joinDate: string; // yyyy-mm-dd
}

@Component({
  selector: 'app-admin-customers',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './customers.html',
  styleUrl: './customers.scss'
})
export class Customers {
  // 统计
  total = signal(356);
  active = signal(298);
  vip = signal(42);
  amount = signal(1118000);

  // 数据
  customers = signal<Customer[]>([
    { id: 'c001', name: '杭州 | 岚光科技', contact: '刘先生', phone: '138****2011', level: 'vip', status: 'active', projects: 6, totalAmount: 120000, joinDate: '2025-03-18' },
    { id: 'c002', name: '苏州 | 宏图建设', contact: '王女士', phone: '137****8890', level: 'normal', status: 'active', projects: 3, totalAmount: 60000, joinDate: '2024-12-05' },
    { id: 'c003', name: '宁波 | 海纳传媒', contact: '周先生', phone: '139****7621', level: 'svip', status: 'active', projects: 12, totalAmount: 380000, joinDate: '2023-10-01' },
    { id: 'c004', name: '嘉兴 | 岛屿设计', contact: '陈女士', phone: '136****5532', level: 'normal', status: 'inactive', projects: 1, totalAmount: 8000, joinDate: '2024-02-20' }
  ]);

  // 筛选
  keyword = signal('');
  status = signal<'all' | 'active' | 'inactive'>('all');
  level = signal<'all' | 'normal' | 'vip' | 'svip'>('all');

  // 面板状态
  showPanel = false;
  panelMode: 'add' | 'detail' | 'edit' = 'add';
  currentCustomer: Customer | null = null;
  formModel: Partial<Customer> = {};

  get filtered() {
    const kw = this.keyword().trim().toLowerCase();
    const st = this.status();
    const lv = this.level();
    return this.customers().filter(c => {
      const m1 = !kw || c.name.toLowerCase().includes(kw) || c.contact.toLowerCase().includes(kw) || c.phone.includes(kw);
      const m2 = st === 'all' || c.status === st;
      const m3 = lv === 'all' || c.level === lv;
      return m1 && m2 && m3;
    });
  }

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

  formatAmount(n: number) {
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 0 }).format(n);
  }

  // 新建客户 -> 打开侧边面板填写
  addCustomer() {
    this.formModel = {
      name: '',
      contact: '',
      phone: '',
      level: 'normal',
      status: 'active',
      projects: 0,
      totalAmount: 0,
      joinDate: new Date().toISOString().slice(0, 10)
    } as Partial<Customer>;
    this.currentCustomer = null;
    this.panelMode = 'add';
    this.showPanel = true;
  }

  // 导出当前筛选客户为 CSV
  exportCustomers() {
    const header = ['客户名称','联系人','电话','等级','状态','项目数','累计成交','加入日期'];
    const rows = this.filtered.map(c => [
      c.name,
      c.contact,
      c.phone,
      c.level.toUpperCase(),
      c.status === 'active' ? '活跃' : '沉默',
      String(c.projects),
      String(c.totalAmount),
      c.joinDate
    ]);
    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);
  }

  // 查看详情
  viewCustomer(c: Customer) {
    this.currentCustomer = c;
    this.panelMode = 'detail';
    this.showPanel = true;
  }

  // 编辑
  editCustomer(c: Customer) {
    this.currentCustomer = c;
    this.formModel = { ...c };
    this.panelMode = 'edit';
    this.showPanel = true;
  }

  // 关闭
  closePanel() {
    this.showPanel = false;
    this.panelMode = 'add';
    this.currentCustomer = null;
    this.formModel = {};
  }

  // 保存
  saveCustomer() {
    const name = (this.formModel.name || '').trim();
    if (!name) { alert('请输入客户名称'); return; }
    const item: Customer = {
      id: Date.now().toString(),
      name,
      contact: this.formModel.contact || '',
      phone: this.formModel.phone || '',
      level: (this.formModel.level as Customer['level']) || 'normal',
      status: (this.formModel.status as Customer['status']) || 'active',
      projects: Number(this.formModel.projects || 0),
      totalAmount: Number(this.formModel.totalAmount || 0),
      joinDate: this.formModel.joinDate || new Date().toISOString().slice(0,10)
    };
    this.customers.set([item, ...this.customers()]);
    this.total.set(this.total() + 1);
    if (item.status === 'active') this.active.set(this.active() + 1);
    if (item.level === 'vip') this.vip.set(this.vip() + 1);
    this.amount.set(this.amount() + item.totalAmount);
    this.closePanel();
  }

  // 更新
  updateCustomer() {
    if (!this.currentCustomer) return;
    const updated: Customer = {
      ...this.currentCustomer,
      name: this.formModel.name ?? this.currentCustomer.name,
      contact: this.formModel.contact ?? this.currentCustomer.contact,
      phone: this.formModel.phone ?? this.currentCustomer.phone,
      level: (this.formModel.level as Customer['level']) ?? this.currentCustomer.level,
      status: (this.formModel.status as Customer['status']) ?? this.currentCustomer.status,
      projects: Number(this.formModel.projects ?? this.currentCustomer.projects),
      totalAmount: Number(this.formModel.totalAmount ?? this.currentCustomer.totalAmount),
      joinDate: this.formModel.joinDate ?? this.currentCustomer.joinDate
    };
    // 简化：不做复杂统计差异，直接替换
    this.customers.set(this.customers().map(c => c.id === updated.id ? updated : c));
    this.closePanel();
  }
}