import { Component, OnInit, Input, inject, ChangeDetectionStrategy, ChangeDetectorRef } 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';
import { ProjectFileService } from '../../../services/project-file.service';
import { ProductSpaceService, Project } from '../../../services/product-space.service';

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

/**
 * 售后归档阶段组件 - Product表统一空间管理
 *
 * 功能：
 * 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'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
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 = '';

  // Product-based 空间管理
  projectProducts: Project[] = [];
  isMultiProductProject: boolean = false;
  activeProductId: string = '';
  selectedProductIds: string[] = [];

  // 售后视图切换
  aftercareView: string = 'overview'; // overview | spaces | complaints | panorama

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

  // 客户评价（支持整体评价和空间评价）
  customerFeedback = {
    submitted: false,
    overallRating: 0,
    serviceRating: 0,
    qualityRating: 0,
    timelinessRating: 0,
    comments: '',
    improvements: '',
    wouldRecommend: true,
    spaceFeedbacks: [] as Array<{
      spaceId: string;
      spaceName: string;
      rating: number;
      comments: string;
      issues: string[];
    }>
  };

  // 项目复盘
  projectRetrospective: {
    generated: boolean;
    summary: string;
    highlights: string[];
    challenges: string[];
    lessons: string[];
    recommendations: string[];
    spaceRetrospectives: Array<{
      spaceId: string;
      spaceName: string;
      performance: number; // 1-5
      issues: string[];
      improvements: string[];
    }>;
  } | null = null;

  // 售后投诉管理
  complaints = [] as Array<{
    id: string;
    spaceId?: string;
    spaceName?: string;
    type: string; // quality | service | timeline | other
    description: string;
    severity: 'low' | 'medium' | 'high';
    status: 'open' | 'processing' | 'resolved';
    reportedBy: string;
    reportedTime: Date;
    assignedTo?: string;
    responses: Array<{
      content: string;
      respondedBy: string;
      responseTime: Date;
    }>;
    resolution?: string;
    resolvedTime?: Date;
  }>;

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

  // 全景照片收集
  panoramaCollection = {
    enabled: false,
    images: [] as Array<{
      id: string;
      spaceId: string;
      spaceName: string;
      url: string;
      uploadTime: Date;
      uploadedBy: string;
      type: string; // before | after | detail
      description?: string;
    }>,
    status: 'pending' // pending | collecting | completed
  };

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

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

  constructor(
    private route: ActivatedRoute,
    private projectFileService: ProjectFileService,
    private productSpaceService: ProductSpaceService,
    private cdr: ChangeDetectorRef
  ) {}

  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) {
        await this.loadProjectSpaces();
        await this.loadAftercareData();
      }

      this.cdr.markForCheck();

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

  /**
   * 加载项目空间数据
   */
  async loadProjectSpaces(): Promise<void> {
    if (!this.project) return;

    try {
      this.projectProducts = await this.productSpaceService.getProjectProductSpaces(this.project.id!);
      this.isMultiProductProject = this.projectProducts.length > 1;

      // 如果有产品，默认选中第一个
      if (this.projectProducts.length > 0 && !this.activeProductId) {
        this.activeProductId = this.projectProducts[0].id;
      }

    } catch (error) {
      console.error('加载项目空间失败:', error);
    }
  }

  /**
   * 加载售后数据
   */
  async loadAftercareData(): Promise<void> {
    if (!this.project) return;

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

      // 加载尾款信息
      if (data.finalPayment) {
        this.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 = { ...this.customerFeedback, ...data.customerFeedback };
      }

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

      // 加载投诉记录
      if (data.complaints) {
        this.complaints = data.complaints;
      }

      // 加载全景照片收集
      if (data.panoramaCollection) {
        this.panoramaCollection = { ...this.panoramaCollection, ...data.panoramaCollection };
      }

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

    } catch (error) {
      console.error('加载售后数据失败:', error);
    }
  }

  // ===== 多空间售后管理方法 =====

  /**
   * 切换售后视图
   */
  onAftercareViewChange(event: any): void {
    this.aftercareView = event.detail.value;
    this.cdr.markForCheck();
  }

  /**
   * 选择产品
   */
  selectProduct(productId: string): void {
    this.activeProductId = productId;
    this.cdr.markForCheck();
  }

  /**
   * 切换产品选择状态
   */
  toggleProductSelection(productId: string): void {
    const index = this.selectedProductIds.indexOf(productId);
    if (index > -1) {
      this.selectedProductIds.splice(index, 1);
    } else {
      this.selectedProductIds.push(productId);
    }
    this.cdr.markForCheck();
  }

  /**
   * 上传支付凭证
   */
  async uploadPaymentVoucher(event: any, spaceId?: string) {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    try {
      this.uploading = true;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 简单的文件类型验证
        if (!file.type.startsWith('image/')) {
          console.warn(`文件 ${file.name} 不是图片格式，跳过`);
          continue;
        }

        // 验证文件大小 (10MB)
        if (file.size > 10 * 1024 * 1024) {
          console.warn(`文件 ${file.name} 超过10MB限制，跳过`);
          continue;
        }

        // 使用ProjectFileService上传文件
        const uploadedFile = await this.projectFileService.uploadProjectFile(
          file,
          this.projectId,
          'payment_voucher',
          spaceId,
          'aftercare',
          {
            paymentType: 'final_payment',
            uploadSource: 'aftercare'
          }
        );

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

      this.cdr.markForCheck();
      // await this.saveDraft();
      // alert('凭证已上传，请手动核对金额和支付方式');

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

  /**
   * 添加空间评价
   */
  addSpaceFeedback(spaceId: string): void {
    const space = this.projectProducts.find(s => s.id === spaceId);
    if (!space) return;

    const existingFeedback = this.customerFeedback.spaceFeedbacks.find(f => f.spaceId === spaceId);
    if (!existingFeedback) {
      this.customerFeedback.spaceFeedbacks.push({
        spaceId,
        spaceName: space.name || this.productSpaceService.getProductTypeName(space.type),
        rating: 0,
        comments: '',
        issues: []
      });
      this.cdr.markForCheck();
    }
  }

  /**
   * 更新空间评价
   */
  updateSpaceFeedback(spaceId: string, field: string, value: any): void {
    const feedback = this.customerFeedback.spaceFeedbacks.find(f => f.spaceId === spaceId);
    if (feedback) {
      (feedback as any)[field] = value;
      this.cdr.markForCheck();
    }
  }

  /**
   * 创建投诉记录
   */
  async createComplaint(complaint: {
    spaceId?: string;
    type: string;
    description: string;
    severity: 'low' | 'medium' | 'high';
  }): Promise<void> {
    const space = complaint.spaceId ? this.projectProducts.find(s => s.id === complaint.spaceId) : undefined;

    const newComplaint = {
      id: `complaint_${Date.now()}`,
      spaceId: complaint.spaceId,
      spaceName: space?.name || this.productSpaceService.getProductTypeName(space?.type || ''),
      type: complaint.type,
      description: complaint.description,
      severity: complaint.severity,
      status: 'open' as const,
      reportedBy: this.customer?.get('name') || '客户',
      reportedTime: new Date(),
      responses: []
    };

    this.complaints.push(newComplaint);
    this.cdr.markForCheck();

    // await this.saveDraft();
  }

  /**
   * 上传全景照片
   */
  async uploadPanoramaImage(event: any, spaceId: string, type: string) {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    const space = this.projectProducts.find(s => s.id === spaceId);
    if (!space) return;

    try {
      this.uploading = true;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        if (!file.type.startsWith('image/')) {
          console.warn(`文件 ${file.name} 不是图片格式，跳过`);
          continue;
        }

        const uploadedFile = await this.projectFileService.uploadProjectFile(
          file,
          this.projectId,
          'panorama',
          spaceId,
          'aftercare',
          {
            imageType: type,
            uploadSource: 'panorama_collection'
          }
        );

        this.panoramaCollection.images.push({
          id: uploadedFile.md5 || '',
          spaceId,
          spaceName: space.name || this.productSpaceService.getProductTypeName(space.type),
          url: uploadedFile.url || '',
          uploadTime: new Date(),
          uploadedBy: this.currentUser?.get('name') || '',
          type,
          description: ''
        });
      }

      this.panoramaCollection.enabled = true;
      this.cdr.markForCheck();

    } catch (error) {
      console.error('上传全景照片失败:', error);
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 提交客户评价
   */
  async submitFeedback() {
    if (this.customerFeedback.overallRating === 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.overallRating,
        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: [
          '建立快速响应机制',
          '增加可视化沟通工具',
          '完善项目管理流程'
        ],
        spaceRetrospectives: this.isMultiProductProject
          ? this.projectProducts.map(space => ({
              spaceId: space.id,
              spaceName: space.name || this.productSpaceService.getProductTypeName(space.type),
              performance: this.customerFeedback.spaceFeedbacks.find(f => f.spaceId === space.id)?.rating || 0,
              issues: [],
              improvements: []
            }))
          : []
      };

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

  // ===== 工具方法 =====

  /**
   * 获取空间图标
   */
  getSpaceIcon(spaceType: string): string {
    return this.productSpaceService.getProductIcon(spaceType);
  }

  /**
   * 获取空间类型名称
   */
  getSpaceTypeName(spaceType: string): string {
    return this.productSpaceService.getProductTypeName(spaceType);
  }

  /**
   * 获取空间显示名称
   */
  getSpaceDisplayName(space: Project): string {
    return space.name || this.getSpaceTypeName(space.type);
  }

  /**
   * 获取当前空间的评价
   */
  getCurrentSpaceFeedback(): any {
    if (!this.activeProductId) return null;
    return this.customerFeedback.spaceFeedbacks.find(f => f.spaceId === this.activeProductId);
  }

  /**
   * 获取空间的投诉
   */
  getSpaceComplaints(spaceId?: string): any[] {
    if (!spaceId) return this.complaints;
    return this.complaints.filter(c => c.spaceId === spaceId);
  }

  /**
   * 获取空间的全景照片
   */
  getSpacePanoramaImages(spaceId?: string): any[] {
    if (!spaceId) return this.panoramaCollection.images;
    return this.panoramaCollection.images.filter(img => img.spaceId === spaceId);
  }

  /**
   * 获取投诉类型名称
   */
  getComplaintTypeName(type: string): string {
    const typeMap: Record<string, string> = {
      'quality': '质量问题',
      'service': '服务问题',
      'timeline': '进度问题',
      'other': '其他问题'
    };
    return typeMap[type] || type;
  }

  /**
   * 获取投诉严重程度名称
   */
  getComplaintSeverityName(severity: string): string {
    const severityMap: Record<string, string> = {
      'low': '轻微',
      'medium': '一般',
      'high': '严重'
    };
    return severityMap[severity] || severity;
  }

  /**
   * 获取投诉状态名称
   */
  getComplaintStatusName(status: string): string {
    const statusMap: Record<string, string> = {
      'open': '待处理',
      'processing': '处理中',
      'resolved': '已解决'
    };
    return statusMap[status] || status;
  }

  /**
   * 计算空间完成度
   */
  calculateSpaceCompletion(spaceId: string): number {
    const spaceFeedback = this.customerFeedback.spaceFeedbacks.find(f => f.spaceId === spaceId);
    if (!spaceFeedback || spaceFeedback.rating === 0) return 0;

    const spaceComplaints = this.getSpaceComplaints(spaceId);
    const unresolvedComplaints = spaceComplaints.filter(c => c.status !== 'resolved').length;

    // 基于评分和投诉情况计算完成度
    let completion = spaceFeedback.rating * 20; // 评分占100%
    if (unresolvedComplaints > 0) {
      completion -= unresolvedComplaints * 10; // 每个未解决投诉扣10分
    }

    return Math.max(0, Math.min(100, completion));
  }

  /**
   * 计算整体项目完成度
   */
  calculateOverallCompletion(): number {
    if (this.projectProducts.length === 0) return 0;

    const totalCompletion = this.projectProducts.reduce((total, space) => {
      return total + this.calculateSpaceCompletion(space.id);
    }, 0);

    return Math.round(totalCompletion / this.projectProducts.length);
  }

  /**
   * 获取待处理投诉数量
   */
  getOpenComplaintsCount(): number {
    return this.complaints.filter(c => c.status === 'open').length;
  }

  /**
   * 获取空间的支付凭证
   */
  getSpacePaymentVouchers(spaceId?: string): any[] {
    if (!spaceId) return this.finalPayment.paymentVouchers;
    return this.finalPayment.paymentVouchers.filter(v => v.spaceId === spaceId);
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes: number): string {
    return this.projectFileService.formatFileSize(bytes);
  }

  /**
   * 生成项目报告摘要
   */
  generateProjectSummary(): string {
    if (!this.projectRetrospective) return '';

    const summary = [];
    summary.push(`项目整体满意度：${this.customerFeedback.overallRating}/5星`);

    if (this.isMultiProductProject) {
      summary.push(`涉及${this.projectProducts.length}个空间`);

      const spaceRatings = this.customerFeedback.spaceFeedbacks.map(f =>
        `${f.spaceName}：${f.rating}/5星`
      );
      if (spaceRatings.length > 0) {
        summary.push(`各空间评分：${spaceRatings.join('，')}`);
      }
    }

    summary.push(`尾款状态：${this.getPaymentStatusText()}`);
    summary.push(`投诉记录：${this.complaints.length}条`);

    return summary.join(' | ');
  }
}
