import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { QuotationApprovalService } from '../../../services/quotation-approval.service';
import { QuotationApproval, QuotationApprovalStatus, CommunicationRecord, ScriptUsageStats } from '../../../services/quotation-approval.service';

@Component({
  selector: 'app-quotation-approval',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './quotation-approval.component.html',
  styleUrls: ['./quotation-approval.component.scss']
})
export class QuotationApprovalComponent implements OnInit {
  quotationApprovals: QuotationApproval[] = [];
  filteredApprovals: QuotationApproval[] = [];
  scriptUsageStats: ScriptUsageStats[] = [];
  
  // 筛选条件
  statusFilter: QuotationApprovalStatus | 'all' = 'all';
  searchKeyword = '';
  dateRange = {
    start: '',
    end: ''
  };
  
  // 统计数据
  approvalStats = {
    total: 0,
    pending: 0,
    approved: 0,
    rejected: 0,
    revisionRequired: 0,
    averageApprovalTime: 0
  };
  
  // 选中的审核项
  selectedApproval: QuotationApproval | null = null;
  
  // 沟通记录
  communicationRecords: CommunicationRecord[] = [];
  newComment = '';
  
  // 模态框状态
  showApprovalModal = false;
  showStatsModal = false;

  constructor(
    private quotationApprovalService: QuotationApprovalService,
    private router: Router
  ) {}

  ngOnInit() {
    this.loadQuotationApprovals();
    this.loadScriptUsageStats();
    this.loadApprovalStats();
  }

  // 加载报价审核列表
  loadQuotationApprovals() {
    this.quotationApprovalService.getQuotationApprovals().subscribe({
      next: (approvals: QuotationApproval[]) => {
        this.quotationApprovals = approvals;
        this.applyFilters();
      },
      error: (error: any) => {
        console.error('加载报价审核列表失败:', error);
      }
    });
  }

  // 加载话术使用统计
  loadScriptUsageStats() {
    this.quotationApprovalService.getScriptUsageStats().subscribe({
      next: (stats: ScriptUsageStats[]) => {
        this.scriptUsageStats = stats;
      },
      error: (error: any) => {
        console.error('加载话术使用统计失败:', error);
      }
    });
  }

  // 加载审核统计
  loadApprovalStats() {
    this.quotationApprovalService.getApprovalStats().subscribe({
      next: (stats: any) => {
        this.approvalStats = stats;
      },
      error: (error: any) => {
        console.error('加载审核统计失败:', error);
      }
    });
  }

  // 应用筛选条件
  applyFilters() {
    this.filteredApprovals = this.quotationApprovals.filter(approval => {
      // 状态筛选
      if (this.statusFilter !== 'all' && approval.status !== this.statusFilter) {
        return false;
      }
      
      // 关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        if (!approval.projectName.toLowerCase().includes(keyword) &&
            !approval.customerName.toLowerCase().includes(keyword) &&
            !approval.submittedBy.toLowerCase().includes(keyword)) {
          return false;
        }
      }
      
      // 日期范围筛选
      if (this.dateRange.start) {
        const startDate = new Date(this.dateRange.start);
        if (new Date(approval.submittedAt) < startDate) {
          return false;
        }
      }
      
      if (this.dateRange.end) {
        const endDate = new Date(this.dateRange.end);
        endDate.setHours(23, 59, 59, 999);
        if (new Date(approval.submittedAt) > endDate) {
          return false;
        }
      }
      
      return true;
    });
  }

  // 重置筛选条件
  resetFilters() {
    this.statusFilter = 'all';
    this.searchKeyword = '';
    this.dateRange = { start: '', end: '' };
    this.applyFilters();
  }

  // 查看审核详情
  viewApprovalDetails(approval: QuotationApproval) {
    this.selectedApproval = approval;
    this.loadCommunicationRecords(approval.quotationId);
    this.showApprovalModal = true;
  }

  // 加载沟通记录
  loadCommunicationRecords(quotationId: string) {
    // 这里应该调用服务获取沟通记录
    // 暂时使用模拟数据
    this.communicationRecords = [];
  }

  // 审批报价
  approveQuotation() {
    if (!this.selectedApproval) return;
    
    this.quotationApprovalService.approveQuotation(
      this.selectedApproval.quotationId,
      'current_user',
      this.newComment
    ).subscribe({
      next: (updatedApproval) => {
        this.updateApprovalInList(updatedApproval);
        this.closeApprovalModal();
        this.loadApprovalStats();
      },
      error: (error) => {
        console.error('审批失败:', error);
      }
    });
  }

  // 拒绝报价
  rejectQuotation() {
    if (!this.selectedApproval) return;
    
    this.quotationApprovalService.rejectQuotation(
      this.selectedApproval.quotationId,
      'current_user',
      this.newComment
    ).subscribe({
      next: (updatedApproval) => {
        this.updateApprovalInList(updatedApproval);
        this.closeApprovalModal();
        this.loadApprovalStats();
      },
      error: (error) => {
        console.error('拒绝失败:', error);
      }
    });
  }

  // 要求修改
  requestRevision() {
    if (!this.selectedApproval) return;
    
    this.quotationApprovalService.requestRevision(
      this.selectedApproval.quotationId,
      'current_user',
      this.newComment
    ).subscribe({
      next: (updatedApproval) => {
        this.updateApprovalInList(updatedApproval);
        this.closeApprovalModal();
        this.loadApprovalStats();
      },
      error: (error) => {
        console.error('要求修改失败:', error);
      }
    });
  }

  // 更新列表中的审核项
  updateApprovalInList(updatedApproval: QuotationApproval) {
    const index = this.quotationApprovals.findIndex(a => a.quotationId === updatedApproval.quotationId);
    if (index !== -1) {
      this.quotationApprovals[index] = updatedApproval;
      this.applyFilters();
    }
  }

  // 关闭审核模态框
  closeApprovalModal() {
    this.showApprovalModal = false;
    this.selectedApproval = null;
    this.newComment = '';
    this.communicationRecords = [];
  }

  // 显示统计模态框
  showStatistics() {
    this.showStatsModal = true;
  }

  // 关闭统计模态框
  closeStatsModal() {
    this.showStatsModal = false;
  }

  // 格式化金额
  formatAmount(amount: number): string {
    return amount.toLocaleString('zh-CN', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    });
  }

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

  // 获取状态标签
  getStatusLabel(status: QuotationApprovalStatus): string {
    const statusMap = {
      'pending': '待审核',
      'approved': '已通过',
      'rejected': '已拒绝',
      'revision_required': '需修改'
    };
    return statusMap[status] || status;
  }

  // 获取状态样式类
  getStatusClass(status: QuotationApprovalStatus): string {
    const classMap = {
      'pending': 'status-pending',
      'approved': 'status-approved',
      'rejected': 'status-rejected',
      'revision_required': 'status-revision'
    };
    return classMap[status] || '';
  }

  // 返回财务工作台
  backToDashboard(): void {
    this.router.navigate(['/finance/dashboard']);
  }
}