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. 按空间+工序上传交付物（从order阶段quotation动态加载）
 * 2. 质量自查清单
 * 3. 组长审核与问题反馈
 * 4. 发起交付流程
 */
@Component({
  selector: 'app-stage-delivery',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './stage-delivery.component.html',
  styleUrls: ['./stage-delivery.component.scss']
})
export class StageDeliveryComponent 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 = '';

  // 用户角色
  role: string = '';
  isDesigner: boolean = false;
  isTeamLeader: boolean = false;

  // 交付物列表（按空间+工序组织）
  deliverables: Array<{
    spaceId: string;
    spaceName: string;
    processType: string; // modeling | softDecor | rendering | postProcess
    processName: string;
    files: Array<{
      url: string;
      name: string;
      type: string; // image | video | document
      uploadTime: Date;
      uploadBy: {
        id: string;
        name: string;
      };
    }>;
    status: string; // draft | submitted | approved | rejected
    qualityCheck?: {
      checked: boolean;
      items: Array<{
        label: string;
        passed: boolean;
      }>;
    };
    review?: {
      reviewedBy: {
        id: string;
        name: string;
      };
      reviewTime: Date;
      result: string; // approved | rejected
      comments: string;
      issues: Array<{
        description: string;
        priority: string; // high | medium | low
        status: string; // open | resolved
      }>;
    };
  }> = [];

  // 当前选中的空间和工序
  selectedSpace: string = '';
  selectedProcess: string = '';

  // 质量自查清单模板
  qualityCheckTemplates = {
    modeling: [
      { label: '模型尺寸准确', passed: false },
      { label: '材质贴图完整', passed: false },
      { label: '灯光设置合理', passed: false },
      { label: '相机视角正确', passed: false }
    ],
    softDecor: [
      { label: '软装搭配协调', passed: false },
      { label: '色彩方案一致', passed: false },
      { label: '家具摆放合理', passed: false },
      { label: '细节装饰完整', passed: false }
    ],
    rendering: [
      { label: '渲染质量达标', passed: false },
      { label: '光影效果自然', passed: false },
      { label: '材质质感真实', passed: false },
      { label: '画面构图优美', passed: false }
    ],
    postProcess: [
      { label: '后期处理精细', passed: false },
      { label: '色调统一协调', passed: false },
      { label: '瑕疵修复完整', passed: false },
      { label: '输出格式正确', passed: false }
    ]
  };

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

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

  constructor(
    private route: ActivatedRoute
  ) {}

  async ngOnInit() {
    // 尝试从父组件获取数据（如果通过@Input传入）
    // 否则从路由参数加载
    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;

      // 如果没有传入project，从路由参数加载
      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');
      }

      // 如果没有传入currentUser，加载当前用户
      if (!this.currentUser && this.cid) {
        const { WxworkSDK } = await import('fmode-ng/core');
        const wxwork = new WxworkSDK({ cid: this.cid, appId: 'crm' });
        this.currentUser = await wxwork.getCurrentUser();
      }

      // 设置用户角色和权限
      this.role = this.currentUser?.get('roleName') || '';
      this.isDesigner = this.role === '组员';
      this.isTeamLeader = this.role === '组长';
      this.canEdit = ['组员', '组长', '管理员'].includes(this.role);

      // 加载交付物数据
      if (this.project) {
        const data = this.project.get('data') || {};

        if (data.deliverables) {
          this.deliverables = data.deliverables;
        } else {
          // 初始化交付物结构（基于报价明细）
          this.initializeDeliverables();
        }
      }

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

  /**
   * 初始化交付物结构
   */
  initializeDeliverables() {
    const data = this.project?.get('data') || {};
    const quotation = data.quotation;

    if (!quotation) return;

    const processTypeMap: any = {
      'modeling': '建模',
      'softDecor': '软装',
      'rendering': '渲染',
      'postProcess': '后期'
    };

    for (const space of quotation.spaces) {
      for (const [processKey, processData] of Object.entries(space.processes)) {
        if ((processData as any).enabled) {
          this.deliverables.push({
            spaceId: space.name,
            spaceName: space.name,
            processType: processKey,
            processName: processTypeMap[processKey],
            files: [],
            status: 'draft'
          });
        }
      }
    }
  }

  /**
   * 获取指定空间和工序的交付物
   */
  getDeliverable(spaceName: string, processType: string): any {
    return this.deliverables.find(
      d => d.spaceName === spaceName && d.processType === processType
    );
  }

  /**
   * 上传交付物文件
   */
  async uploadFile(event: any, spaceName: string, processType: string) {
    const file = event.target.files[0];
    if (!file) return;

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

    try {
      this.uploading = true;

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

      const deliverable = this.getDeliverable(spaceName, processType);
      if (deliverable) {
        deliverable.files.push({
          url: url,
          name: file.name,
          type: file.type.startsWith('image/') ? 'image' : file.type.startsWith('video/') ? 'video' : 'document',
          uploadTime: new Date(),
          uploadBy: {
            id: this.currentUser!.id,
            name: this.currentUser!.get('name')
          }
        });

        await this.saveDraft();
        alert('上传成功');
      }

    } catch (err) {
      console.error('上传失败:', err);
      alert('上传失败');
    } finally {
      this.uploading = false;
    }
  }

  /**
   * 删除文件
   */
  async deleteFile(spaceName: string, processType: string, fileIndex: number) {
    const deliverable = this.getDeliverable(spaceName, processType);
    if (deliverable) {
      deliverable.files.splice(fileIndex, 1);
      await this.saveDraft();
    }
  }

  /**
   * 进行质量自查
   */
  performQualityCheck(spaceName: string, processType: string) {
    const deliverable = this.getDeliverable(spaceName, processType);
    if (!deliverable) return;

    // 初始化质量检查清单
    const template = this.qualityCheckTemplates[processType as keyof typeof this.qualityCheckTemplates];
    if (!deliverable.qualityCheck) {
      deliverable.qualityCheck = {
        checked: false,
        items: template.map(item => ({ ...item }))
      };
    }
  }

  /**
   * 提交交付物给组长审核
   */
  async submitForReview(spaceName: string, processType: string) {
    const deliverable = this.getDeliverable(spaceName, processType);
    if (!deliverable) return;

    // 验证
    if (deliverable.files.length === 0) {
      alert('请先上传交付物文件');
      return;
    }

    if (!deliverable.qualityCheck?.checked) {
      alert('请先完成质量自查');
      return;
    }

    try {
      this.saving = true;

      deliverable.status = 'submitted';
      await this.saveDraft();

      // TODO: 发送企微通知给组长
      alert('已提交审核');

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

  /**
   * 组长审核（通过/驳回）
   */
  async reviewDeliverable(spaceName: string, processType: string, result: 'approved' | 'rejected', comments: string) {
    if (!this.isTeamLeader && !this.canEdit) {
      alert('您没有审核权限');
      return;
    }

    const deliverable = this.getDeliverable(spaceName, processType);
    if (!deliverable) return;

    try {
      this.saving = true;

      deliverable.status = result;
      deliverable.review = {
        reviewedBy: {
          id: this.currentUser!.id,
          name: this.currentUser!.get('name')
        },
        reviewTime: new Date(),
        result,
        comments,
        issues: []
      };

      await this.saveDraft();

      alert(result === 'approved' ? '审核通过' : '已驳回，请修改后重新提交');

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

  /**
   * 创建问题反馈
   */
  async createIssue(spaceName: string, processType: string, issue: any) {
    const deliverable = this.getDeliverable(spaceName, processType);
    if (!deliverable || !deliverable.review) return;

    deliverable.review.issues.push(issue);
    await this.saveDraft();
  }

  /**
   * 发起交付流程
   */
  async initiateDelivery() {
    if (!this.project || !this.canEdit) return;

    // 验证所有交付物都已通过审核
    const allApproved = this.deliverables.every(d => d.status === 'approved');
    if (!allApproved) {
      alert('请确保所有交付物都已通过审核');
      return;
    }

    try {
      this.saving = true;

      // 更新项目状态
      this.project.set('currentStage', '尾款结算');
      this.project.set('status', '待结算');

      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.deliverables = this.deliverables;

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

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

  /**
   * 获取已批准的交付物数量
   */
  getApprovedCount(): number {
    return this.deliverables.filter(d => d.status === 'approved').length;
  }

  /**
   * 检查质检是否全部通过
   */
  isQualityCheckAllPassed(deliverable: any): boolean {
    return deliverable.qualityCheck?.items?.every((i: any) => i.passed) || false;
  }

  /**
   * 获取工序颜色
   */
  getProcessColor(processType: string): string {
    const colorMap: any = {
      'modeling': 'primary',
      'softDecor': 'secondary',
      'rendering': 'tertiary',
      'postProcess': 'success'
    };
    return colorMap[processType] || 'medium';
  }

  /**
   * 获取状态颜色
   */
  getStatusColor(status: string): string {
    const colorMap: any = {
      'draft': 'medium',
      'submitted': 'warning',
      'approved': 'success',
      'rejected': 'danger'
    };
    return colorMap[status] || 'medium';
  }

  /**
   * 获取状态文本
   */
  getStatusText(status: string): string {
    const textMap: any = {
      'draft': '草稿',
      'submitted': '待审核',
      'approved': '已通过',
      'rejected': '已驳回'
    };
    return textMap[status] || status;
  }

  /**
   * 按空间分组交付物
   */
  get deliverablesBySpace(): Array<{ spaceName: string; items: any[] }> {
    const grouped = new Map<string, any[]>();

    for (const deliverable of this.deliverables) {
      if (!grouped.has(deliverable.spaceName)) {
        grouped.set(deliverable.spaceName, []);
      }
      grouped.get(deliverable.spaceName)!.push(deliverable);
    }

    return Array.from(grouped.entries()).map(([spaceName, items]) => ({
      spaceName,
      items
    }));
  }

  /**
   * 计算完成进度
   */
  get completionProgress(): number {
    if (this.deliverables.length === 0) return 0;
    const approvedCount = this.deliverables.filter(d => d.status === 'approved').length;
    return Math.round((approvedCount / this.deliverables.length) * 100);
  }
}
