import { Component, OnInit, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule, Router } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';

export interface AfterSalesProject {
  id: string;
  projectCode: string;
  projectName: string;
  customerName: string;
  completedDate: Date;
  finalPaymentStatus: 'pending' | 'partial' | 'completed' | 'overdue';
  finalPaymentAmount: number;
  paidAmount: number;
  reviewStatus: 'pending' | 'positive' | 'negative' | 'no-review';
  reviewScore?: number;
  reviewContent?: string;
  suggestionCount: number;
  lastContactDate: Date;
  priority: 'high' | 'medium' | 'low';
  // 详情页面相关数据
  paymentRecords?: PaymentRecord[];
  reviewRecords?: ReviewRecord[];
  suggestions?: CustomerSuggestion[];
}

export interface PaymentRecord {
  id: string;
  amount: number;
  paymentDate: Date;
  paymentMethod: string;
  voucher?: FileUpload;
  status: 'pending' | 'verified' | 'rejected';
  operator: string;
  remark?: string;
  statusHistory: PaymentStatusHistory[];
}

export interface PaymentStatusHistory {
  id: string;
  status: string;
  operator: string;
  changeDate: Date;
  reason: string;
}

export interface FileUpload {
  id: string;
  fileName: string;
  fileType: string;
  fileSize: number;
  uploadDate: Date;
  fileUrl: string;
  previewUrl?: string;
}

export interface ReviewRecord {
  id: string;
  reviewType: 'system' | 'manual';
  reviewChannel: string;
  reviewDate: Date;
  score?: number;
  content: string;
  status: 'pending' | 'processed';
  followUpReminder?: Date;
  operator?: string;
  remark?: string;
}

export interface CustomerSuggestion {
  id: string;
  category: string;
  content: string;
  submitDate: Date;
  status: 'pending' | 'processing' | 'completed' | 'rejected';
  priority: 'high' | 'medium' | 'low';
  assignee?: string;
  response?: string;
  responseDate?: Date;
  statusHistory: SuggestionStatusHistory[];
}

export interface SuggestionStatusHistory {
  id: string;
  status: string;
  operator: string;
  changeDate: Date;
  remark: string;
}

@Component({
  selector: 'app-after-sales',
  standalone: true,
  imports: [
    CommonModule, 
    FormsModule, 
    RouterModule,
    MatIconModule,
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatDatepickerModule,
    MatNativeDateModule
  ],
  templateUrl: './after-sales.component.html',
  styleUrls: ['./after-sales.component.scss']
})
export class AfterSalesComponent implements OnInit {
  // 搜索和筛选条件
  searchTerm = signal('');
  selectedPaymentStatus = signal('all');
  selectedReviewStatus = signal('all');
  selectedPriority = signal('all');
  dateRange = signal<{ start: Date | null; end: Date | null }>({ start: null, end: null });

  // 售后项目数据
  afterSalesProjects = signal<AfterSalesProject[]>([]);
  
  // 当前选中的项目
  selectedProject = signal<AfterSalesProject | null>(null);
  
  // 视图状态
  currentView = signal<'overview' | 'detail'>('overview');
  
  // 详情页面状态
  activeDetailTab = signal<'payment' | 'review' | 'suggestion'>('payment');
  
  // 表单状态
  isUploadingFile = signal(false);
  isSubmittingForm = signal(false);
  showAddReviewForm = false;
  showUpdateForm: { [key: string]: boolean } = {};
  
  // 建议类别选项
  suggestionCategories = signal([
    { value: 'service-process', label: '服务流程' },
    { value: 'product-function', label: '产品功能' },
    { value: 'delivery-time', label: '交付周期' },
    { value: 'communication', label: '沟通协调' },
    { value: 'quality', label: '质量问题' },
    { value: 'other', label: '其他建议' }
  ]);
  
  // 筛选后的项目列表
  filteredProjects = computed(() => {
    let projects = this.afterSalesProjects();
    
    // 搜索筛选
    if (this.searchTerm()) {
      const term = this.searchTerm().toLowerCase();
      projects = projects.filter(p => 
        p.projectCode.toLowerCase().includes(term) ||
        p.projectName.toLowerCase().includes(term) ||
        p.customerName.toLowerCase().includes(term)
      );
    }
    
    // 尾款状态筛选
    if (this.selectedPaymentStatus() !== 'all') {
      projects = projects.filter(p => p.finalPaymentStatus === this.selectedPaymentStatus());
    }
    
    // 评价状态筛选
    if (this.selectedReviewStatus() !== 'all') {
      projects = projects.filter(p => p.reviewStatus === this.selectedReviewStatus());
    }
    
    // 优先级筛选
    if (this.selectedPriority() !== 'all') {
      projects = projects.filter(p => p.priority === this.selectedPriority());
    }
    
    return projects;
  });

  // 统计数据
  stats = computed(() => {
    const projects = this.afterSalesProjects();
    return {
      total: projects.length,
      pendingPayment: projects.filter(p => p.finalPaymentStatus === 'pending').length,
      overduePayment: projects.filter(p => p.finalPaymentStatus === 'overdue').length,
      pendingReview: projects.filter(p => p.reviewStatus === 'pending').length,
      highPriority: projects.filter(p => p.priority === 'high').length
    };
  });

  constructor(private router: Router) {}

  ngOnInit(): void {
    this.loadAfterSalesData();
  }

  private loadAfterSalesData(): void {
    // 模拟数据
    const mockData: AfterSalesProject[] = [
      {
        id: '1',
        projectCode: 'PRJ-2024-001',
        projectName: '企业官网设计开发',
        customerName: '张三科技有限公司',
        completedDate: new Date('2024-01-15'),
        finalPaymentStatus: 'pending',
        finalPaymentAmount: 50000,
        paidAmount: 40000,
        reviewStatus: 'positive',
        reviewScore: 5,
        reviewContent: '非常满意，设计很棒！',
        suggestionCount: 2,
        lastContactDate: new Date('2024-01-20'),
        priority: 'high'
      },
      {
        id: '2',
        projectCode: 'PRJ-2024-002',
        projectName: '移动端APP开发',
        customerName: '李四网络科技',
        completedDate: new Date('2024-01-10'),
        finalPaymentStatus: 'overdue',
        finalPaymentAmount: 80000,
        paidAmount: 60000,
        reviewStatus: 'pending',
        suggestionCount: 1,
        lastContactDate: new Date('2024-01-18'),
        priority: 'high'
      },
      {
        id: '3',
        projectCode: 'PRJ-2024-003',
        projectName: '电商平台升级',
        customerName: '王五电商',
        completedDate: new Date('2024-01-08'),
        finalPaymentStatus: 'completed',
        finalPaymentAmount: 120000,
        paidAmount: 120000,
        reviewStatus: 'positive',
        reviewScore: 4,
        reviewContent: '整体不错，有些细节需要优化',
        suggestionCount: 3,
        lastContactDate: new Date('2024-01-22'),
        priority: 'medium'
      }
    ];
    
    this.afterSalesProjects.set(mockData);
  }

  // 选择项目进入详情页
  selectProject(project: AfterSalesProject): void {
    this.selectedProject.set(project);
    this.currentView.set('detail');
    this.loadProjectDetails(project.id);
  }

  // 返回概览页
  backToOverview(): void {
    this.currentView.set('overview');
    this.selectedProject.set(null);
    this.activeDetailTab.set('payment');
  }

  // 切换详情页面标签
  switchDetailTab(tab: 'payment' | 'review' | 'suggestion'): void {
    this.activeDetailTab.set(tab);
  }

  // 加载项目详情数据
  async loadProjectDetails(projectId: string): Promise<void> {
    try {
      // 模拟API调用
      const projectDetails = await this.mockLoadProjectDetails(projectId);
      const currentProject = this.selectedProject();
      if (currentProject) {
        this.selectedProject.set({
          ...currentProject,
          ...projectDetails
        });
      }
    } catch (error) {
      console.error('加载项目详情失败:', error);
    }
  }

  // 模拟加载项目详情数据
  private async mockLoadProjectDetails(projectId: string) {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      paymentRecords: [
        {
          id: '1',
          amount: 5000,
          paymentDate: new Date('2024-01-15'),
          paymentMethod: '银行转账',
          status: 'verified' as const,
          operator: '张三',
          remark: '首期尾款',
          statusHistory: [
            {
              id: '1',
              status: '待验证',
              operator: '系统',
              changeDate: new Date('2024-01-15'),
              reason: '客户上传支付凭证'
            },
            {
              id: '2',
              status: '已验证',
              operator: '张三',
              changeDate: new Date('2024-01-16'),
              reason: '核实支付信息无误'
            }
          ]
        }
      ],
      reviewRecords: [
        {
          id: '1',
          reviewType: 'manual' as const,
          reviewChannel: '电话回访',
          reviewDate: new Date('2024-01-20'),
          score: 5,
          content: '服务很满意，交付及时',
          status: 'processed' as const,
          operator: '李四',
          remark: '客户反馈良好'
        }
      ],
      suggestions: [
        {
          id: '1',
          category: 'service-process',
          content: '希望能提供更详细的项目进度报告',
          submitDate: new Date('2024-01-18'),
          status: 'processing' as const,
          priority: 'medium' as const,
          assignee: '王五',
          statusHistory: [
            {
              id: '1',
              status: '待处理',
              operator: '系统',
              changeDate: new Date('2024-01-18'),
              remark: '客户提交建议'
            },
            {
              id: '2',
              status: '处理中',
              operator: '王五',
              changeDate: new Date('2024-01-19'),
              remark: '已分配处理人员'
            }
          ]
        }
      ]
    };
  }

  // 文件上传处理
  async handleFileUpload(event: Event, recordId?: string): Promise<void> {
    const input = event.target as HTMLInputElement;
    const files = input.files;
    
    if (!files || files.length === 0) return;
    
    this.isUploadingFile.set(true);
    
    try {
      for (const file of Array.from(files)) {
        await this.uploadFile(file, recordId);
      }
      // 显示成功提示
      this.showSuccessMessage('文件上传成功');
    } catch (error) {
      console.error('文件上传失败:', error);
      this.showErrorMessage('文件上传失败，请检查文件格式和大小');
    } finally {
      this.isUploadingFile.set(false);
    }
  }

  // 上传文件
  private async uploadFile(file: File, recordId?: string): Promise<FileUpload> {
    // 验证文件类型和大小
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
    const maxSize = 10 * 1024 * 1024; // 10MB
    
    if (!allowedTypes.includes(file.type)) {
      throw new Error('文件格式不支持，请上传 JPG/PNG/PDF 格式');
    }
    
    if (file.size > maxSize) {
      throw new Error('文件大小超过限制，请上传小于10MB的文件');
    }
    
    // 模拟上传过程
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    return {
      id: Date.now().toString(),
      fileName: file.name,
      fileType: file.type,
      fileSize: file.size,
      uploadDate: new Date(),
      fileUrl: URL.createObjectURL(file),
      previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined
    };
  }

  // 添加评价记录
  async addReviewRecord(reviewData: Partial<ReviewRecord>): Promise<void> {
    this.isSubmittingForm.set(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const newRecord: ReviewRecord = {
        id: Date.now().toString(),
        reviewType: 'manual',
        reviewChannel: reviewData.reviewChannel || '',
        reviewDate: new Date(),
        score: reviewData.score,
        content: reviewData.content || '',
        status: 'processed',
        operator: '当前用户',
        remark: reviewData.remark
      };
      
      const currentProject = this.selectedProject();
      if (currentProject && currentProject.reviewRecords) {
        currentProject.reviewRecords.push(newRecord);
        this.selectedProject.set({ ...currentProject });
      }
      
      this.showSuccessMessage('评价记录添加成功');
    } catch (error) {
      console.error('添加评价记录失败:', error);
      this.showErrorMessage('添加评价记录失败，请重试');
    } finally {
      this.isSubmittingForm.set(false);
    }
  }

  // 更新建议状态
  async updateSuggestionStatus(suggestionId: string, status: string, response?: string): Promise<void> {
    this.isSubmittingForm.set(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const currentProject = this.selectedProject();
      if (currentProject && currentProject.suggestions) {
        const suggestion = currentProject.suggestions.find(s => s.id === suggestionId);
        if (suggestion) {
          suggestion.status = status as any;
          suggestion.response = response;
          suggestion.responseDate = new Date();
          
          // 添加状态历史
          suggestion.statusHistory.push({
            id: Date.now().toString(),
            status,
            operator: '当前用户',
            changeDate: new Date(),
            remark: response || '状态更新'
          });
          
          this.selectedProject.set({ ...currentProject });
        }
      }
      
      this.showSuccessMessage('建议状态更新成功');
    } catch (error) {
      console.error('更新建议状态失败:', error);
      this.showErrorMessage('更新建议状态失败，请重试');
    } finally {
      this.isSubmittingForm.set(false);
    }
  }

  // 显示成功消息
  private showSuccessMessage(message: string): void {
    // 这里可以集成实际的消息提示组件
    alert(message);
  }

  // 显示错误消息
  private showErrorMessage(message: string): void {
    // 这里可以集成实际的消息提示组件
    alert(message);
  }
  
  // 获取支付记录状态文本
  getPaymentRecordStatusText(status: string): string {
    const statusMap: { [key: string]: string } = {
      'pending': '待验证',
      'verified': '已验证',
      'rejected': '已拒绝'
    };
    return statusMap[status] || status;
  }
  
  // 获取建议状态文本
  getSuggestionStatusText(status: string): string {
    const statusMap: { [key: string]: string } = {
      'pending': '待处理',
      'processing': '处理中',
      'completed': '已完成',
      'rejected': '已拒绝'
    };
    return statusMap[status] || status;
  }
  
  // 获取建议类别标签
  getSuggestionCategoryLabel(category: string): string {
    const categoryMap: { [key: string]: string } = {
      'service-process': '服务流程',
      'product-function': '产品功能',
      'delivery-time': '交付周期',
      'communication': '沟通协调',
      'quality': '质量问题',
      'other': '其他建议'
    };
    return categoryMap[category] || category;
  }

  // 获取尾款状态显示文本
  getPaymentStatusText(status: string): string {
    const statusMap: Record<string, string> = {
      'pending': '待收款',
      'partial': '部分收款',
      'completed': '已完成',
      'overdue': '逾期'
    };
    return statusMap[status] || status;
  }

  // 获取尾款状态样式类
  getPaymentStatusClass(status: string): string {
    const classMap: Record<string, string> = {
      'pending': 'status-pending',
      'partial': 'status-partial',
      'completed': 'status-completed',
      'overdue': 'status-overdue'
    };
    return classMap[status] || '';
  }

  // 获取评价状态显示文本
  getReviewStatusText(status: string): string {
    const statusMap: Record<string, string> = {
      'pending': '待评价',
      'positive': '好评',
      'negative': '差评',
      'no-review': '无评价'
    };
    return statusMap[status] || status;
  }

  // 获取评价状态样式类
  getReviewStatusClass(status: string): string {
    const classMap: Record<string, string> = {
      'pending': 'review-pending',
      'positive': 'review-positive',
      'negative': 'review-negative',
      'no-review': 'review-none'
    };
    return classMap[status] || '';
  }

  // 获取优先级显示文本
  getPriorityText(priority: string): string {
    const priorityMap: Record<string, string> = {
      'high': '高',
      'medium': '中',
      'low': '低'
    };
    return priorityMap[priority] || priority;
  }

  // 获取优先级样式类
  getPriorityClass(priority: string): string {
    const classMap: Record<string, string> = {
      'high': 'priority-high',
      'medium': 'priority-medium',
      'low': 'priority-low'
    };
    return classMap[priority] || '';
  }

  // 格式化金额
  formatAmount(amount: number): string {
    return `¥${amount.toLocaleString()}`;
  }

  // 格式化货币
  formatCurrency(amount: number): string {
    return `¥${amount.toLocaleString()}`;
  }

  // 格式化日期
  formatDate(date: Date): string {
    return date.toLocaleDateString('zh-CN');
  }

  // 计算尾款进度百分比
  getPaymentProgress(project: AfterSalesProject): number {
    return Math.round((project.paidAmount / project.finalPaymentAmount) * 100);
  }
}