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

export interface ComplaintItem {
  id: string;
  type: string;
  description: string;
  submitTime: any;
  submittedAt?: Date;
  resolvedAt?: Date;
  status: string;
  response?: string;
  handlerComment?: string;
  handlerName?: string;
  solution?: string;
  customerName?: string;
  priority?: string;
  images?: string[];
}

interface ComplaintStats {
  totalCount: number;
  pendingCount: number;
  processingCount: number;
  resolvedCount: number;
  highPriorityCount: number;
  averageResolutionTime: number;
  priorityStats: { [key: string]: number };
  typeStats: { [key: string]: number };
}

@Component({
  selector: 'app-complaint-card',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './complaint-card.html',
  styleUrls: ['./complaint-card.scss']
})
export class ComplaintCardComponent {
  @Input() complaints: ComplaintItem[] = [];

  // 筛选条件
  statusFilter = signal<string>('all');
  priorityFilter = signal<string>('all');
  typeFilter = signal<string>('all');
  searchKeyword = signal<string>('');

  // 投诉类型
  complaintTypes = [
    { value: 'quality', label: '质量问题' },
    { value: 'service', label: '服务态度' },
    { value: 'delivery', label: '交付延期' },
    { value: 'communication', label: '沟通问题' },
    { value: 'design', label: '设计不满意' },
    { value: 'other', label: '其他问题' }
  ];

  // 优先级选项
  priorities = [
    { value: 'low', label: '低', color: '#52c41a' },
    { value: 'medium', label: '中', color: '#faad14' },
    { value: 'high', label: '高', color: '#f5222d' },
    { value: 'urgent', label: '紧急', color: '#722ed1' }
  ];

  // 计算统计数据
  stats = computed<ComplaintStats>(() => {
    const complaints = this.complaints || [];
    const totalCount = complaints.length;
    
    const pendingCount = complaints.filter(c => c.status === '待处理').length;
    const processingCount = complaints.filter(c => c.status === '处理中').length;
    const resolvedCount = complaints.filter(c => c.status === '已解决').length;
    const highPriorityCount = complaints.filter(c => (c as any).priority === 'high' || (c as any).priority === 'urgent').length;

    // 计算平均解决时间（天）
    const resolvedComplaints = complaints.filter(c => c.status === '已解决' && (c as any).resolvedAt && (c as any).createdAt);
    const averageResolutionTime = resolvedComplaints.length > 0 
      ? resolvedComplaints.reduce((sum, c) => {
          const days = Math.ceil((new Date((c as any).resolvedAt).getTime() - new Date((c as any).createdAt).getTime()) / (1000 * 60 * 60 * 24));
          return sum + days;
        }, 0) / resolvedComplaints.length
      : 0;

    // 优先级统计
    const priorityStats: { [key: string]: number } = {};
    this.priorities.forEach(p => {
      priorityStats[p.value] = complaints.filter(c => (c as any).priority === p.value).length;
    });

    // 类型统计
    const typeStats: { [key: string]: number } = {};
    this.complaintTypes.forEach(t => {
      typeStats[t.value] = complaints.filter(c => this.getComplaintType(c) === t.value).length;
    });

    return {
      totalCount,
      pendingCount,
      processingCount,
      resolvedCount,
      highPriorityCount,
      averageResolutionTime: Math.round(averageResolutionTime * 10) / 10,
      priorityStats,
      typeStats
    };
  });

  // 筛选后的投诉列表
  filteredComplaints = computed(() => {
    let filtered = this.complaints || [];

    // 状态筛选
    if (this.statusFilter() !== 'all') {
      filtered = filtered.filter(complaint => complaint.status === this.statusFilter());
    }

    // 优先级筛选
    if (this.priorityFilter() !== 'all') {
      filtered = filtered.filter(complaint => (complaint as any).priority === this.priorityFilter());
    }

    // 类型筛选
    if (this.typeFilter() !== 'all') {
      filtered = filtered.filter(complaint => this.getComplaintType(complaint) === this.typeFilter());
    }

    // 关键词搜索
    if (this.searchKeyword()) {
      const keyword = this.searchKeyword().toLowerCase();
      filtered = filtered.filter(complaint => 
        complaint.description?.toLowerCase().includes(keyword) ||
        (complaint as any).customerName?.toLowerCase().includes(keyword) ||
        complaint.type?.toLowerCase().includes(keyword)
      );
    }

    return filtered;
  });

  // 获取投诉类型
  getComplaintType(complaint: any): string {
    if (complaint.type) return complaint.type;
    
    // 根据描述内容推断类型
    const description = complaint.description?.toLowerCase() || '';
    if (description.includes('质量') || description.includes('缺陷')) return 'quality';
    if (description.includes('服务') || description.includes('态度')) return 'service';
    if (description.includes('延期') || description.includes('时间')) return 'delivery';
    if (description.includes('沟通') || description.includes('联系')) return 'communication';
    if (description.includes('设计') || description.includes('效果')) return 'design';
    
    return 'other';
  }

  // 获取类型标签
  getTypeLabel(type: string): string {
    const typeObj = this.complaintTypes.find(t => t.value === type);
    return typeObj ? typeObj.label : '其他';
  }

  // 获取优先级信息
  getPriorityInfo(priority: string) {
    return this.priorities.find(p => p.value === priority) || this.priorities[0];
  }

  // 获取状态样式类
  getStatusClass(complaint: any): string {
    switch (complaint.status) {
      case '待处理': return 'pending';
      case '处理中': return 'processing';
      case '已解决': return 'resolved';
      default: return 'pending';
    }
  }

  // 获取优先级样式类
  getPriorityClass(priority: string): string {
    switch (priority) {
      case 'low': return 'priority-low';
      case 'medium': return 'priority-medium';
      case 'high': return 'priority-high';
      case 'urgent': return 'priority-urgent';
      default: return 'priority-low';
    }
  }

  // 计算处理天数
  getDaysInProgress(complaint: any): number {
    const startDate = new Date(complaint.createdAt);
    const endDate = complaint.resolvedAt ? new Date(complaint.resolvedAt) : new Date();
    return Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
  }

  // 判断是否超时
  isOverdue(complaint: any): boolean {
    if (complaint.status === '已解决') return false;
    
    const daysInProgress = this.getDaysInProgress(complaint);
    const maxDays = complaint.priority === 'urgent' ? 1 : 
                   complaint.priority === 'high' ? 3 : 
                   complaint.priority === 'medium' ? 7 : 14;
    
    return daysInProgress > maxDays;
  }

  // 更新筛选条件
  updateStatusFilter(event: any) {
    this.statusFilter.set(event.target.value);
  }

  updatePriorityFilter(event: any) {
    this.priorityFilter.set(event.target.value);
  }

  updateTypeFilter(event: any) {
    this.typeFilter.set(event.target.value);
  }

  updateSearchKeyword(keyword: string) {
    this.searchKeyword.set(keyword);
  }
}