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 { FmodeParse } from 'fmode-ng/parse';
import { CustomerProfileComponent } from '../../../../modules/project/pages/contact/contact.component';

@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<FmodeObject[]>([]);

  showCustomerPanel = false;
  selectedCustomer: FmodeObject | null = null;
  currentUserForContact: FmodeObject | null = null;
  panelProjectId: string | null = null;

  constructor(private customerService: CustomerService) {}

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

  async loadCustomers(): Promise<void> {
    this.loading.set(true);
    try {
      const custs = await this.customerService.findCustomers();
      this.customers.set(custs);
      this.total.set(custs.length);
    } catch (error) {
      console.error('加载客户列表失败:', error);
    } finally {
      this.loading.set(false);
    }
  }

  setupCurrentUserForContact() {
    const companyId = localStorage.getItem('company');
    if (companyId) {
      const Company = (FmodeParse.with('nova') as any).Object.extend('Company');
      const company = new Company();
      company.id = companyId;
      const companyPtr = company.toPointer();
      this.currentUserForContact = { get: (key: string) => key === 'company' ? companyPtr : (key === 'roleName' ? '管理员' : null) } as any;
    }
  }

  openCustomerDetail(customer: FmodeObject) {
    this.selectedCustomer = customer;
    this.showCustomerPanel = true;
  }

  async closeCustomerPanel(refresh: boolean = false) {
    this.showCustomerPanel = false;
    this.selectedCustomer = null;
    if (refresh) await this.loadCustomers();
  }

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

  get filtered() {
    const kw = this.keyword().trim().toLowerCase();
    return this.customers().filter(c => {
      if (!kw) return true;
      const name = (c.get('name') || c.get('data')?.name || '').toLowerCase();
      const mobile = c.get('mobile') || '';
      return name.includes(kw) || mobile.includes(kw);
    });
  }

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

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