import { Component, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CustomerService } from '../services/customer.service';
import { FmodeObject } from 'fmode-ng/core';
import { CustomerProfileComponent } from '../../../../modules/project/pages/contact/contact.component';

interface Customer {
  id: string;
  name: string;
  mobile: string;
  external_userid?: string;
  source?: string;
  createdAt?: Date;
}

@Component({
  selector: 'app-admin-customers',
  standalone: true,
  imports: [CommonModule, FormsModule, CustomerProfileComponent],
  templateUrl: './customers.html',
  styleUrl: './customers.scss'
})
export class Customers implements OnInit {
  // 统计
  total = signal(0);
  loading = signal(false);

  // 数据
  customers = signal<Customer[]>([]);
  customerObjects: Map<string, FmodeObject> = new Map(); // 存储Parse对象

  // 客户详情面板
  showCustomerPanel = false;
  selectedCustomer: FmodeObject | null = null;

  constructor(private customerService: CustomerService) {}

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

  async loadCustomers(): Promise<void> {
    this.loading.set(true);
    try {
      const custs = await this.customerService.findCustomers();

      // 清空之前的对象映射
      this.customerObjects.clear();

      const custList: Customer[] = custs.map(c => {
        const json = this.customerService.toJSON(c);
        const customerId = json.objectId;

        // 保存Parse对象以便后续使用
        this.customerObjects.set(customerId, c);

        return {
          id: customerId,
          name: json.name || '未知客户',
          mobile: json.mobile || '',
          external_userid: json.external_userid,
          source: json.source,
          createdAt: json.createdAt?.iso || json.createdAt
        };
      });

      this.customers.set(custList);
      this.total.set(custList.length);
    } catch (error) {
      console.error('加载客户列表失败:', error);
    } finally {
      this.loading.set(false);
    }
  }

  // 打开客户详情面板
  openCustomerDetail(customer: Customer) {
    const customerObj = this.customerObjects.get(customer.id);
    if (customerObj) {
      this.selectedCustomer = customerObj;
      this.showCustomerPanel = true;
    }
  }

  // 关闭客户详情面板
  closeCustomerPanel() {
    this.showCustomerPanel = false;
    this.selectedCustomer = null;
  }

  // 筛选
  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();
    return this.customers().filter(c => {
      const m1 = !kw || c.name.toLowerCase().includes(kw) || c.mobile.includes(kw);
      return m1;
    });
  }

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

  // 导出当前筛选客户为 CSV
  exportCustomers() {
    const header = ['客户名称','手机号','企微ID','来源','创建时间'];
    const rows = this.filtered.map(c => [
      c.name,
      c.mobile,
      c.external_userid || '',
      c.source || '',
      c.createdAt instanceof Date ? c.createdAt.toISOString().slice(0, 10) : String(c.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);
  }

}