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

interface RecordItem {
  id: string;
  date: string; // yyyy-mm-dd
  type: 'income' | 'expense';
  project: string;
  customer: string;
  amount: number;
  status: 'pending' | 'done';
}

@Component({
  selector: 'app-admin-finance',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './finance.html',
  styleUrl: './finance.scss'
})
export class FinancePage {
  // 统计
  income = signal(511800);
  expense = signal(98000);
  profit = signal(this.income() - this.expense());

  // 数据
  list = signal<RecordItem[]>([
    { id: 'r001', date: '2025-09-01', type: 'income', project: '极越办公公装设计', customer: '岚小牛', amount: 60000, status: 'done' },
    { id: 'r002', date: '2025-09-05', type: 'income', project: '山水别墅景观', customer: '王先生', amount: 85000, status: 'done' },
    { id: 'r003', date: '2025-09-08', type: 'expense', project: '材料采购', customer: '—', amount: 12000, status: 'done' },
    { id: 'r004', date: '2025-09-09', type: 'income', project: '工业风办公室', customer: '赵女士', amount: 95000, status: 'pending' }
  ]);

  // 筛选
  keyword = signal('');
  type = signal<'all' | 'income' | 'expense'>('all');
  status = signal<'all' | 'pending' | 'done'>('all');

  get filtered() {
    const kw = this.keyword().toLowerCase();
    return this.list().filter(i => {
      const m1 = !kw || i.project.toLowerCase().includes(kw) || i.customer.toLowerCase().includes(kw);
      const m2 = this.type() === 'all' || i.type === this.type();
      const m3 = this.status() === 'all' || i.status === this.status();
      return m1 && m2 && m3;
    });
  }

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

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

  // 导出当前筛选流水为 CSV
  exportReport() {
    const header = ['日期','类型','项目','客户','金额','状态'];
    const rows = this.filtered.map(i => [
      i.date,
      i.type === 'income' ? '收入' : '支出',
      i.project,
      i.customer,
      i.amount,
      i.status === 'done' ? '已入账' : '待入账'
    ]);
    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);
  }
}