import { Component, OnInit, Input, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FmodeObject, FmodeParse } from 'fmode-ng/parse';
import { NovaUploadService } from 'fmode-ng/storage';

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

/**
 * 售后归档阶段组件
 *
 * 功能：
 * 1. 尾款管理
 * 2. 支付凭证OCR识别
 * 3. 客户评价
 * 4. 项目复盘（AI生成）
 * 5. 归档
 */
@Component({
  selector: 'app-stage-aftercare',
  standalone: true,
  imports: [CommonModule, 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 = '';

  // 尾款信息
  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;

  // 注入上传服务
  private uploadService: NovaUploadService = inject(NovaUploadService);

  constructor(
    private route: ActivatedRoute
  ) {}

  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) {
        // 动态导入WxworkSDK避免循环依赖
        const { WxworkSDK } = await import('fmode-ng/core');
        const wxwork = new WxworkSDK({ cid: this.cid, appId: 'crm' });
        this.currentUser = await wxwork.getCurrentUser();

        const role = this.currentUser?.get('roleName') || '';
        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 (!file.type.startsWith('image/')) {
      alert('请上传图片文件');
      return;
    }

    // 验证文件大小 (10MB)
    if (file.size > 10 * 1024 * 1024) {
      alert('图片大小不能超过10MB');
      return;
    }

    try {
      this.uploading = true;

      // 使用 NovaUploadService 上传文件
      const fileResult: any = await this.uploadService.upload(file);
      const url = fileResult.url;

      // 暂时不使用OCR，需要手动输入金额和支付方式
      this.finalPayment.paymentVouchers.push({
        url: url,
        amount: 0,
        paymentTime: new Date(),
        paymentMethod: '待确认',
        ocrResult: { note: '请手动核对金额和支付方式' }
      });

      await this.saveDraft();

      alert('凭证已上传，请手动核对金额和支付方式');

    } 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('projectType') || '',
        duration: this.calculateProjectDuration(),
        customerRating: this.customerFeedback.rating,
        challenges: this.extractChallenges()
      };

      // 使用mock数据生成复盘（暂时不调用AI服务）
      this.projectRetrospective = {
        generated: true,
        summary: `项目${projectData.title}整体执行顺利，历时${projectData.duration}天完成。客户满意度${projectData.customerRating}星，团队协作良好。`,
        highlights: [
          '设计方案获得客户高度认可',
          '按时完成所有交付物',
          '团队协作高效，沟通顺畅'
        ],
        challenges: projectData.challenges.length > 0
          ? projectData.challenges
          : ['部分细节调整较多', '个别环节时间紧张'],
        lessons: [
          '需要更早介入前期沟通',
          '方案确认需要更充分讨论',
          '时间管理需要更精细化'
        ],
        recommendations: [
          '建立快速响应机制',
          '增加可视化沟通工具',
          '完善项目管理流程'
        ]
      };

      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;
  }


  /**
   * 归档项目
   */
  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';
  }
}
