import { Component, Input, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Settlement } from '../../../models/project.model';

export interface SettlementStats {
  totalAmount: number;
  pendingAmount: number;
  overdueAmount: number;
  completedAmount: number;
  totalCount: number;
  pendingCount: number;
  overdueCount: number;
  completedCount: number;
}

@Component({
  selector: 'app-settlement-card',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './settlement-card.html',
  styleUrls: ['./settlement-card.scss']
})
export class SettlementCardComponent {
  @Input() settlements: Settlement[] = [];
  
  // 筛选条件
  statusFilter = signal<string>('all');
  searchKeyword = signal<string>('');
  
  // 计算统计数据
  stats = computed<SettlementStats>(() => {
    const settlements = this.settlements || [];
    
    return {
      totalAmount: settlements.reduce((sum, s) => sum + (s.amount || 0), 0),
      pendingAmount: settlements.filter(s => s.status === '待结算').reduce((sum, s) => sum + (s.amount || 0), 0),
      overdueAmount: settlements.filter(s => this.isOverdue(s)).reduce((sum, s) => sum + (s.amount || 0), 0),
      completedAmount: settlements.filter(s => s.status === '已结算').reduce((sum, s) => sum + (s.amount || 0), 0),
      totalCount: settlements.length,
      pendingCount: settlements.filter(s => s.status === '待结算').length,
      overdueCount: settlements.filter(s => this.isOverdue(s)).length,
      completedCount: settlements.filter(s => s.status === '已结算').length
    };
  });
  
  // 筛选后的结算列表
  filteredSettlements = computed(() => {
    let filtered = this.settlements || [];
    
    // 状态筛选
    const status = this.statusFilter();
    if (status !== 'all') {
      if (status === 'overdue') {
        filtered = filtered.filter(s => this.isOverdue(s));
      } else {
        filtered = filtered.filter(s => s.status === status);
      }
    }
    
    // 关键词搜索
    const keyword = this.searchKeyword().toLowerCase();
    if (keyword) {
      filtered = filtered.filter(s => 
        (s.projectName || '').toLowerCase().includes(keyword) ||
        (s.stage || '').toLowerCase().includes(keyword)
      );
    }
    
    return filtered;
  });
  
  // 判断是否逾期
  isOverdue(settlement: Settlement): boolean {
    if (settlement.status === '已结算') return false;
    // 简化逾期判断：如果是待结算状态且创建时间超过30天，则认为逾期
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    return settlement.createdAt < thirtyDaysAgo;
  }
  
  // 获取状态样式类
  getStatusClass(settlement: Settlement): string {
    if (this.isOverdue(settlement)) return 'overdue';
    return settlement.status === '已结算' ? 'completed' : 'pending';
  }
  
  // 格式化金额
  formatAmount(amount: number): string {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 2
    }).format(amount);
  }
  
  // 更新筛选条件
  updateStatusFilter(status: string): void {
    this.statusFilter.set(status);
  }
  
  updateSearchKeyword(keyword: string): void {
    this.searchKeyword.set(keyword);
  }
  
  // 计算逾期天数
  getDaysOverdue(settlement: Settlement): number {
    if (settlement.status === '已结算') return 0;
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    if (settlement.createdAt >= thirtyDaysAgo) return 0;
    
    const today = new Date();
    const diffTime = today.getTime() - thirtyDaysAgo.getTime();
    return Math.max(0, Math.ceil(diffTime / (1000 * 60 * 60 * 24)));
  }
}