import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { signal } from '@angular/core';
import { AuthService } from '../../../services/auth.service';

// 对账状态类型定义
export type ReconciliationStatus = 
  | 'pending'       // 待对账
  | 'partial'       // 部分对账
  | 'completed'     // 已完成
  | 'discrepancy';  // 有差异

// 交易类型定义
export type TransactionType = 
  | 'payment'       // 收款
  | 'expense'       // 支出
  | 'refund';       // 退款

// 交易记录类型定义
export interface Transaction {
  id: string;
  date: Date;
  type: TransactionType;
  amount: number;
  description: string;
  projectId: string;
  projectName: string;
  clientName: string;
  invoiceNumber?: string;
  paymentMethod?: string;
  reconciled: boolean;
  reconciliationId?: string;
}

// 对账记录类型定义
export interface ReconciliationRecord {
  id: string;
  date: Date;
  status: ReconciliationStatus;
  totalAmount: number;
  reconciledAmount: number;
  discrepancyAmount: number;
  periodStart: Date;
  periodEnd: Date;
  transactions: Transaction[];
  notes?: string;
  reconciledBy?: string;
}

@Component({
  selector: 'app-reconciliation',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormsModule, RouterModule],
  templateUrl: './reconciliation.html',
  styleUrls: ['./reconciliation.scss']
})
export class Reconciliation implements OnInit {
  // 使用signal管理对账记录数据
  reconciliationRecords = signal<ReconciliationRecord[]>([]);
  
  // 使用signal管理未对账交易
  unreconciledTransactions = signal<Transaction[]>([]);
  
  // 当前选中的对账记录
  selectedRecord = signal<ReconciliationRecord | null>(null);
  
  // 对账表单
  reconciliationForm: FormGroup;
  
  // 模态框状态
  showDetailModal = signal(false);
  showReconcileModal = signal(false);
  
  // 过滤条件
  dateRangeFilter = signal<{ start: Date | null; end: Date | null }>({ start: null, end: null });
  statusFilter = signal<ReconciliationStatus | 'all'>('all');
  
  // 用户角色信号
  userRole = signal<string>('teamLead');

  constructor(private fb: FormBuilder, private authService: AuthService) {
    // 初始化对账表单
    this.reconciliationForm = this.fb.group({
      periodStart: [''],
      periodEnd: [''],
      notes: ['']
    });
  }

  ngOnInit(): void {
    // 初始化用户角色
    this.initializeUserRole();
    
    // 初始化对账记录数据
    this.loadReconciliationData();
    // 初始化未对账交易数据
    this.loadUnreconciledTransactions();
  }
  
  // 初始化用户角色
  initializeUserRole(): void {
    // 从AuthService获取用户角色
    const roles = this.authService.getUserRoles();
    // 默认使用teamLead角色
    let userRole = 'teamLead';
    
    // 如果用户有admin角色，也视为teamLead
    if (roles.includes('admin')) {
      userRole = 'teamLead';
    } else if (roles.length > 0) {
      // 否则使用第一个角色
      userRole = roles[0];
    }
    
    this.userRole.set(userRole);
  }
  
  // 检查用户角色
  checkUserRole(requiredRole: string): boolean {
    return this.authService.hasRole(requiredRole);
  }

  // 加载对账记录数据
  loadReconciliationData(): void {
    // 模拟从API获取对账记录数据
    const mockRecords: ReconciliationRecord[] = [
      {
        id: 'REC-2023-08',
        date: new Date('2023-08-31'),
        status: 'completed',
        totalAmount: 150000,
        reconciledAmount: 150000,
        discrepancyAmount: 0,
        periodStart: new Date('2023-08-01'),
        periodEnd: new Date('2023-08-31'),
        transactions: [],
        notes: '8月份财务对账已完成',
        reconciledBy: '张三'
      },
      {
        id: 'REC-2023-07',
        date: new Date('2023-07-31'),
        status: 'completed',
        totalAmount: 120000,
        reconciledAmount: 120000,
        discrepancyAmount: 0,
        periodStart: new Date('2023-07-01'),
        periodEnd: new Date('2023-07-31'),
        transactions: [],
        notes: '7月份财务对账已完成',
        reconciledBy: '李四'
      },
      {
        id: 'REC-2023-09-P',
        date: new Date('2023-09-15'),
        status: 'partial',
        totalAmount: 85000,
        reconciledAmount: 60000,
        discrepancyAmount: 25000,
        periodStart: new Date('2023-09-01'),
        periodEnd: new Date('2023-09-30'),
        transactions: [],
        notes: '9月份财务对账进行中',
        reconciledBy: '王五'
      }
    ];

    this.reconciliationRecords.set(mockRecords);
  }

  // 加载未对账交易数据
  loadUnreconciledTransactions(): void {
    // 模拟从API获取未对账交易数据
    const mockTransactions: Transaction[] = [
      {
        id: 'TRX-2023-09-001',
        date: new Date('2023-09-10'),
        type: 'payment',
        amount: 45000,
        description: '现代风格住宅室内设计项目首付款',
        projectId: 'PRJ-2023-001',
        projectName: '现代风格住宅室内设计',
        clientName: '星光地产',
        invoiceNumber: 'INV-2023-09-001',
        paymentMethod: '银行转账',
        reconciled: false
      },
      {
        id: 'TRX-2023-09-002',
        date: new Date('2023-09-12'),
        type: 'expense',
        amount: 12000,
        description: '3D建模软件许可证续费',
        projectId: 'PRJ-2023-002',
        projectName: '商业办公空间设计',
        clientName: '未来科技有限公司',
        paymentMethod: '信用卡',
        reconciled: false
      },
      {
        id: 'TRX-2023-09-003',
        date: new Date('2023-09-15'),
        type: 'payment',
        amount: 30000,
        description: '品牌展厅设计项目尾款',
        projectId: 'PRJ-2023-005',
        projectName: '品牌展厅设计',
        clientName: '时尚家居品牌',
        invoiceNumber: 'INV-2023-09-002',
        paymentMethod: '银行转账',
        reconciled: false
      },
      {
        id: 'TRX-2023-09-004',
        date: new Date('2023-09-18'),
        type: 'expense',
        amount: 8000,
        description: '渲染服务器租赁费用',
        projectId: 'PRJ-2023-003',
        projectName: '餐饮空间改造设计',
        clientName: '悦享餐饮集团',
        paymentMethod: '银行转账',
        reconciled: false
      }
    ];

    this.unreconciledTransactions.set(mockTransactions);
  }

  // 开始新的对账
  startReconciliation(): void {
    if (!this.checkUserRole('teamLead')) {
      console.warn('权限不足：只有组长可以开始新的对账');
      return;
    }
    
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    
    this.reconciliationForm.patchValue({
      periodStart: firstDayOfMonth,
      periodEnd: today
    });
    
    this.showReconcileModal.set(true);
  }

  // 执行对账操作
  performReconciliation(): void {
    if (!this.checkUserRole('teamLead')) {
      console.warn('权限不足：只有组长可以执行对账操作');
      return;
    }
    
    if (this.reconciliationForm.invalid) return;
    
    const formValue = this.reconciliationForm.value;
    const periodStart = formValue.periodStart;
    const periodEnd = formValue.periodEnd;
    
    // 过滤出期间内的交易
    const periodTransactions = this.unreconciledTransactions()
      .filter(trx => trx.date >= periodStart && trx.date <= periodEnd);
    
    // 计算交易总额
    const totalAmount = periodTransactions.reduce((sum, trx) => {
      return trx.type === 'payment' ? sum + trx.amount : sum - trx.amount;
    }, 0);
    
    // 创建新的对账记录
    const newRecord: ReconciliationRecord = {
      id: `REC-${new Date().getFullYear()}-${(new Date().getMonth() + 1).toString().padStart(2, '0')}-${Date.now().toString().slice(-4)}`,
      date: new Date(),
      status: 'partial', // 默认为部分对账
      totalAmount: totalAmount,
      reconciledAmount: totalAmount, // 假设所有选中的交易都已对账
      discrepancyAmount: 0, // 假设没有差异
      periodStart: periodStart,
      periodEnd: periodEnd,
      transactions: periodTransactions,
      notes: formValue.notes,
      reconciledBy: '当前用户'
    };
    
    // 更新对账记录列表
    const updatedRecords = [newRecord, ...this.reconciliationRecords()];
    this.reconciliationRecords.set(updatedRecords);
    
    // 更新未对账交易列表
    const remainingTransactions = this.unreconciledTransactions()
      .filter(trx => !periodTransactions.some(t => t.id === trx.id));
    this.unreconciledTransactions.set(remainingTransactions);
    
    this.showReconcileModal.set(false);
  }

  // 查看对账详情
  viewReconciliationDetail(record: ReconciliationRecord): void {
    this.selectedRecord.set(record);
    this.showDetailModal.set(true);
  }

  // 标记交易为已对账
  markTransactionAsReconciled(transaction: Transaction): void {
    if (!this.checkUserRole('teamLead')) {
      console.warn('权限不足：只有组长可以标记交易为已对账');
      return;
    }
    
    const updatedTransactions = this.unreconciledTransactions()
      .map(trx => {
        if (trx.id === transaction.id) {
          return { ...trx, reconciled: true };
        }
        return trx;
      });
    
    this.unreconciledTransactions.set(updatedTransactions);
  }

  // 获取对账状态文本
  getStatusText(status: ReconciliationStatus): string {
    const statusMap: Record<ReconciliationStatus, string> = {
      'pending': '待对账',
      'partial': '部分对账',
      'completed': '已完成',
      'discrepancy': '有差异'
    };
    return statusMap[status] || status;
  }

  // 获取对账状态样式类
  getStatusClass(status: ReconciliationStatus): string {
    const statusClassMap: Record<ReconciliationStatus, string> = {
      'pending': 'status-pending',
      'partial': 'status-partial',
      'completed': 'status-completed',
      'discrepancy': 'status-discrepancy'
    };
    return statusClassMap[status] || '';
  }

  // 获取交易类型文本
  getTransactionTypeText(type: TransactionType): string {
    const typeMap: Record<TransactionType, string> = {
      'payment': '收款',
      'expense': '支出',
      'refund': '退款'
    };
    return typeMap[type] || type;
  }

  // 获取交易类型样式类
  getTransactionTypeClass(type: TransactionType): string {
    const typeClassMap: Record<TransactionType, string> = {
      'payment': 'transaction-payment',
      'expense': 'transaction-expense',
      'refund': 'transaction-refund'
    };
    return typeClassMap[type] || '';
  }

  // 格式化日期
  formatDate(date: Date | undefined | null): string {
    if (!date) return '';
    return new Date(date).toLocaleDateString('zh-CN');
  }

  // 格式化金额
  formatAmount(amount: number): string {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(amount);
  }

  // 应用日期范围过滤
  applyDateRangeFilter(start: Date | null, end: Date | null): void {
    this.dateRangeFilter.set({ start, end });
  }

  // 应用状态过滤
  applyStatusFilter(status: ReconciliationStatus | 'all'):
    void {
    this.statusFilter.set(status);
    // 这里应该实现过滤逻辑，但为了简化，我们假设它会在模板中使用
  }
  
  // 更新日期范围过滤的开始日期
  updateDateRangeStart(start: Date | string | null): void {
    const currentFilter = this.dateRangeFilter();
    this.dateRangeFilter.set({ 
      ...currentFilter, 
      start: start ? new Date(start) : null 
    });
  }

  // 更新日期范围过滤的结束日期
  updateDateRangeEnd(end: Date | string | null): void {
    const currentFilter = this.dateRangeFilter();
    this.dateRangeFilter.set({ 
      ...currentFilter, 
      end: end ? new Date(end) : null 
    });
  }
  // 过滤符合条件的未对账交易
  getFilteredUnreconciledTransactions(): Transaction[] {
    const formValue = this.reconciliationForm.value;
    const periodStart = formValue.periodStart ? new Date(formValue.periodStart) : null;
    const periodEnd = formValue.periodEnd ? new Date(formValue.periodEnd) : null;
    
    return this.unreconciledTransactions().filter(transaction => {
      const transactionDate = new Date(transaction.date);
      const matchesStart = !periodStart || transactionDate >= periodStart;
      const matchesEnd = !periodEnd || transactionDate <= periodEnd;
      return matchesStart && matchesEnd;
    });
  }

  // 检查是否有符合条件的未对账交易
  hasFilteredUnreconciledTransactions(): boolean {
    return this.getFilteredUnreconciledTransactions().length > 0;
  }
}
