import { Component, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { FmodeObject, FmodeParse } from 'fmode-ng/parse';
import { ProjectUploadService } from '../../../services/upload.service';
import { ProjectAIService } from '../../../services/ai.service';
import { WxworkSDKService } from '../../../services/wxwork-sdk.service';

const Parse = FmodeParse.with('nova');

/**
 * 售后归档阶段组件
 *
 * 功能：
 * 1. 尾款管理
 * 2. 支付凭证OCR识别
 * 3. 客户评价
 * 4. 项目复盘（AI生成）
 * 5. 归档
 */
@Component({
  selector: 'app-stage-aftercare',
  standalone: true,
  imports: [CommonModule, IonicModule, FormsModule],
  templateUrl: './stage-aftercare.component.html',
  styleUrls: ['./stage-aftercare.component.scss']
})
export class StageAftercareComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() customer: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() canEdit: boolean = false;

  // 路由参数
  cid: string = '';
  projectId: string = '';

  // 服务注入
  wxwork: WxworkSDKService | null = null;

  // 尾款信息
  finalPayment = {
    totalAmount: 0,
    paidAmount: 0,
    remainingAmount: 0,
    paymentVouchers: [] as Array<{
      url: string;
      amount: number;
      paymentTime: Date;
      paymentMethod: string;
      ocrResult?: any;
    }>,
    status: 'pending' // pending | partial | completed
  };

  // 客户评价
  customerFeedback = {
    submitted: false,
    rating: 0,
    serviceRating: 0,
    qualityRating: 0,
    timelinessRating: 0,
    comments: '',
    improvements: '',
    wouldRecommend: true
  };

  // 项目复盘
  projectRetrospective: {
    generated: boolean;
    summary: string;
    highlights: string[];
    challenges: string[];
    lessons: string[];
    recommendations: string[];
  } | null = null;

  // 归档状态
  archiveStatus = {
    archived: false,
    archiveTime: null as Date | null,
    archivedBy: null as { id: string; name: string } | null
  };

  // 加载状态
  loading: boolean = true;
  uploading: boolean = false;
  generating: boolean = false;
  saving: boolean = false;

  constructor(
    private route: ActivatedRoute,
    private uploadService: ProjectUploadService,
    private aiService: ProjectAIService,
    private wxworkService: WxworkSDKService
  ) {}

  async ngOnInit() {
    if (!this.project || !this.customer || !this.currentUser) {
      this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
      this.projectId = this.route.parent?.snapshot.paramMap.get('projectId') || '';
    }

    await this.loadData();
  }

  /**
   * 加载数据
   */
  async loadData() {
    try {
      this.loading = true;

      if (!this.project && this.projectId) {
        const query = new Parse.Query('Project');
        query.include('customer', 'assignee');
        this.project = await query.get(this.projectId);
        this.customer = this.project.get('customer');
      }

      if (!this.currentUser && this.cid) {
        await this.wxworkService.initialize(this.cid, 'crm');
        this.currentUser = await this.wxworkService.getCurrentUser();

        const role = this.currentUser?.get('role') || '';
        this.canEdit = ['客服', '组长', '管理员'].includes(role);
      }

      if (this.project) {
        const data = this.project.get('data') || {};

        // 加载尾款信息
        if (data.finalPayment) {
          this.finalPayment = data.finalPayment;
        } else {
          // 从报价总额初始化
          const quotation = data.quotation;
          if (quotation) {
            this.finalPayment.totalAmount = quotation.total;
            this.finalPayment.remainingAmount = quotation.total;
          }
        }

        // 加载客户评价
        if (data.customerFeedback) {
          this.customerFeedback = data.customerFeedback;
        }

        // 加载项目复盘
        if (data.projectRetrospective) {
          this.projectRetrospective = data.projectRetrospective;
        }

        // 加载归档状态
        if (data.archiveStatus) {
          this.archiveStatus = data.archiveStatus;
        }
      }

    } catch (err) {
      console.error('加载失败:', err);
    } finally {
      this.loading = false;
    }
  }

  /**
   * 上传支付凭证
   */
  async uploadPaymentVoucher(event: any) {
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    if (!this.uploadService.validateFileType(file, ['image/*'])) {
      alert('请上传图片文件');
      return;
    }

    // 验证文件大小 (10MB)
    if (!this.uploadService.validateFileSize(file, 10)) {
      alert('图片大小不能超过10MB');
      return;
    }

    try {
      this.uploading = true;

      // 上传文件到Parse Server
      const url = await this.uploadService.uploadFile(file, {
        compress: true,
        onProgress: (progress: number) => {
          console.log('上传进度:', progress);
        }
      });

      // 使用AI进行OCR识别
      try {
        const ocrResult = await this.aiService.recognizePaymentVoucher(url);

        this.finalPayment.paymentVouchers.push({
          url: url,
          amount: ocrResult.amount || 0,
          paymentTime: ocrResult.paymentTime ? new Date(ocrResult.paymentTime) : new Date(),
          paymentMethod: ocrResult.paymentMethod || '未识别',
          ocrResult: ocrResult
        });

        // 更新已支付金额
        this.finalPayment.paidAmount += ocrResult.amount || 0;
        this.finalPayment.remainingAmount = this.finalPayment.totalAmount - this.finalPayment.paidAmount;

        // 更新状态
        if (this.finalPayment.remainingAmount <= 0) {
          this.finalPayment.status = 'completed';
        } else if (this.finalPayment.paidAmount > 0) {
          this.finalPayment.status = 'partial';
        }

        await this.saveDraft();

        alert(`OCR识别成功!\n金额: ¥${ocrResult.amount}\n方式: ${ocrResult.paymentMethod}`);

      } catch (ocrError) {
        // OCR失败，仍然保存图片，但需要手动输入
        console.error('OCR识别失败:', ocrError);

        this.finalPayment.paymentVouchers.push({
          url: url,
          amount: 0,
          paymentTime: new Date(),
          paymentMethod: '待确认',
          ocrResult: { error: 'OCR识别失败，请手动确认' }
        });

        await this.saveDraft();

        alert('凭证已上传，但OCR识别失败，请手动核对金额和支付方式');
      }

    } catch (error: any) {
      console.error('上传失败:', error);
      alert('上传失败: ' + (error?.message || '未知错误'));
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 提交客户评价
   */
  async submitFeedback() {
    if (this.customerFeedback.rating === 0) {
      alert('请选择综合评分');
      return;
    }

    try {
      this.saving = true;

      this.customerFeedback.submitted = true;
      await this.saveDraft();

      alert('评价提交成功');

    } catch (err) {
      console.error('提交失败:', err);
      alert('提交失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 生成项目复盘
   */
  async generateRetrospective() {
    if (!this.project || !this.canEdit) return;

    try {
      this.generating = true;

      // 准备项目数据
      const projectData = {
        title: this.project.get('title') || '',
        type: this.project.get('type') || '',
        duration: this.calculateProjectDuration(),
        customerRating: this.customerFeedback.rating,
        challenges: this.extractChallenges()
      };

      // 调用AI服务生成复盘
      const result = await this.aiService.generateProjectRetrospective(
        projectData,
        {
          onProgress: (content) => {
            console.log('生成进度:', content.length);
          }
        }
      );

      this.projectRetrospective = result;

      await this.saveDraft();

      alert('项目复盘生成成功');

    } catch (error: any) {
      console.error('生成失败:', error);
      alert('生成失败: ' + (error?.message || '未知错误'));
    } finally {
      this.generating = false;
    }
  }

  /**
   * 计算项目周期
   */
  private calculateProjectDuration(): number {
    const createdAt = this.project?.get('createdAt');
    if (!createdAt) return 0;

    const now = new Date();
    const diffTime = Math.abs(now.getTime() - createdAt.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  }

  /**
   * 提取项目挑战
   */
  private extractChallenges(): string[] {
    const challenges: string[] = [];
    const data = this.project?.get('data') || {};

    // 从交付物审核记录中提取问题
    if (data.deliverables) {
      for (const deliverable of data.deliverables) {
        if (deliverable.status === 'rejected' && deliverable.review?.comments) {
          challenges.push(deliverable.review.comments);
        }
      }
    }

    return challenges;
  }

  /**
   * 构建复盘提示词
   */
  buildRetrospectivePrompt(): string {
    let prompt = `作为项目经理，请对以下项目进行复盘总结：\n\n`;

    prompt += `项目名称: ${this.project?.get('title')}\n`;
    prompt += `项目类型: ${this.project?.get('type')}\n`;
    prompt += `客户评价: ${this.customerFeedback.rating}星\n\n`;

    prompt += `请从以下几个方面进行总结：\n`;
    prompt += `1. 项目亮点和成功经验\n`;
    prompt += `2. 遇到的挑战和问题\n`;
    prompt += `3. 经验教训和改进建议\n`;
    prompt += `4. 未来项目的建议\n`;

    return prompt;
  }

  /**
   * 调用AI服务
   */
  async callAIService(prompt: string): Promise<string> {
    // TODO: 实现实际的AI服务调用
    await new Promise(resolve => setTimeout(resolve, 2000));

    return JSON.stringify({
      summary: '项目整体执行顺利，客户满意度高，团队协作良好。',
      highlights: ['设计方案获得客户高度认可', '按时完成所有交付物', '团队协作高效'],
      challenges: ['CAD图纸延期', '部分软装调整较多'],
      lessons: ['需要更早介入CAD图纸环节', '软装方案需要更充分沟通'],
      recommendations: ['建立CAD图纸快速审核机制', '增加软装方案可视化工具']
    });
  }

  /**
   * 解析复盘响应
   */
  parseRetrospectiveResponse(response: string): any {
    try {
      const parsed = JSON.parse(response);
      return {
        generated: true,
        ...parsed
      };
    } catch (err) {
      console.error('解析失败:', err);
      return null;
    }
  }

  /**
   * 归档项目
   */
  async archiveProject() {
    if (!this.project || !this.canEdit) return;

    // 验证
    if (this.finalPayment.status !== 'completed') {
      alert('请确保尾款已结清');
      return;
    }

    if (!this.customerFeedback.submitted) {
      alert('请先提交客户评价');
      return;
    }

    if (!this.projectRetrospective) {
      alert('请先生成项目复盘');
      return;
    }

    try {
      this.saving = true;

      // 更新归档状态
      this.archiveStatus = {
        archived: true,
        archiveTime: new Date(),
        archivedBy: {
          id: this.currentUser!.id || '',
          name: this.currentUser!.get('name') || ''
        }
      };

      await this.saveDraft();

      // 更新项目状态
      this.project.set('status', '已完成');
      this.project.set('currentStage', '已归档');
      await this.project.save();

      alert('项目已归档');

    } catch (err) {
      console.error('归档失败:', err);
      alert('归档失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 保存草稿
   */
  async saveDraft() {
    if (!this.project || !this.canEdit) return;

    try {
      this.saving = true;

      const data = this.project.get('data') || {};
      data.finalPayment = this.finalPayment;
      data.customerFeedback = this.customerFeedback;

      if (this.projectRetrospective) {
        data.projectRetrospective = this.projectRetrospective;
      }

      data.archiveStatus = this.archiveStatus;

      this.project.set('data', data);
      await this.project.save();

    } catch (err) {
      console.error('保存失败:', err);
    } finally {
      this.saving = false;
    }
  }

  /**
   * 设置评分
   */
  setRating(field: string, value: number) {
    (this.customerFeedback as any)[field] = value;
  }

  /**
   * 获取支付状态文本
   */
  getPaymentStatusText(): string {
    const map: any = {
      'pending': '待支付',
      'partial': '部分支付',
      'completed': '已完成'
    };
    return map[this.finalPayment.status] || '未知';
  }

  /**
   * 获取支付状态颜色
   */
  getPaymentStatusColor(): string {
    const map: any = {
      'pending': 'warning',
      'partial': 'primary',
      'completed': 'success'
    };
    return map[this.finalPayment.status] || 'medium';
  }
}
