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

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

/**
 * 订单分配阶段组件
 *
 * 功能：
 * 1. 显示客户基础信息
 * 2. 编辑项目基本信息（项目名称、类型、交付期限）
 * 3. 编辑报价明细（按空间+工序类型）
 * 4. 分配设计师（组员）
 * 5. 提交审批
 */
@Component({
  selector: 'app-stage-order',
  standalone: true,
  imports: [CommonModule, IonicModule, FormsModule],
  templateUrl: './stage-order.component.html',
  styleUrls: ['./stage-order.component.scss']
})
export class StageOrderComponent implements OnInit {
  @Input() project: FmodeObject | null = null;
  @Input() customer: FmodeObject | null = null;
  @Input() currentUser: FmodeObject | null = null;
  @Input() canEdit: boolean = false;

  // 项目基本信息
  projectInfo = {
    title: '',
    type: '整屋设计', // 整屋设计 | 局部改造 | 软装设计
    deadline: '',
    description: ''
  };

  // 报价明细（按空间+工序）
  quotation = {
    spaces: [
      {
        name: '客厅',
        processes: {
          modeling: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          softDecor: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          rendering: { enabled: false, price: 0, unit: '张', quantity: 0 },
          postProcess: { enabled: false, price: 0, unit: '张', quantity: 0 }
        }
      },
      {
        name: '主卧',
        processes: {
          modeling: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          softDecor: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          rendering: { enabled: false, price: 0, unit: '张', quantity: 0 },
          postProcess: { enabled: false, price: 0, unit: '张', quantity: 0 }
        }
      },
      {
        name: '次卧',
        processes: {
          modeling: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          softDecor: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          rendering: { enabled: false, price: 0, unit: '张', quantity: 0 },
          postProcess: { enabled: false, price: 0, unit: '张', quantity: 0 }
        }
      },
      {
        name: '厨房',
        processes: {
          modeling: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          softDecor: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          rendering: { enabled: false, price: 0, unit: '张', quantity: 0 },
          postProcess: { enabled: false, price: 0, unit: '张', quantity: 0 }
        }
      },
      {
        name: '卫生间',
        processes: {
          modeling: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          softDecor: { enabled: false, price: 0, unit: '㎡', quantity: 0 },
          rendering: { enabled: false, price: 0, unit: '张', quantity: 0 },
          postProcess: { enabled: false, price: 0, unit: '张', quantity: 0 }
        }
      }
    ],
    total: 0
  };

  // 工序类型定义
  processTypes = [
    { key: 'modeling', name: '建模', color: 'primary' },
    { key: 'softDecor', name: '软装', color: 'secondary' },
    { key: 'rendering', name: '渲染', color: 'tertiary' },
    { key: 'postProcess', name: '后期', color: 'success' }
  ];

  // 可选设计师列表
  designers: FmodeObject[] = [];
  selectedDesigner: FmodeObject | null = null;

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

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

  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');
        this.selectedDesigner = this.project.get('assignee');
      }

      // 如果没有传入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();

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

      // 1. 加载项目基本信息
      if (this.project) {
        this.projectInfo.title = this.project.get('title') || '';
        this.projectInfo.type = this.project.get('type') || '整屋设计';
        this.projectInfo.deadline = this.project.get('deadline') || '';
        this.projectInfo.description = this.project.get('description') || '';

        // 加载报价明细
        const data = this.project.get('data') || {};
        if (data.quotation) {
          this.quotation = data.quotation;
        }

        // 加载已分配设计师
        const assignee = this.project.get('assignee');
        if (assignee) {
          this.selectedDesigner = assignee;
        }
      }

      // 2. 加载可用设计师列表
      const query = new Parse.Query('Profile');
      query.equalTo('role', '组员');
      query.equalTo('isDeleted', false);
      query.ascending('name');
      this.designers = await query.find();

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

  /**
   * 计算报价总额
   */
  calculateTotal() {
    let total = 0;
    for (const space of this.quotation.spaces) {
      for (const processKey of Object.keys(space.processes)) {
        const process = space.processes[processKey as keyof typeof space.processes];
        if (process.enabled) {
          total += process.price * process.quantity;
        }
      }
    }
    this.quotation.total = total;
  }

  /**
   * 切换工序启用状态
   */
  toggleProcess(space: any, processKey: string) {
    const process = space.processes[processKey];
    process.enabled = !process.enabled;
    if (!process.enabled) {
      process.price = 0;
      process.quantity = 0;
    }
    this.calculateTotal();
  }

  /**
   * 工序价格或数量变化
   */
  onProcessChange() {
    this.calculateTotal();
  }

  /**
   * 选择设计师
   */
  selectDesigner(designer: FmodeObject) {
    this.selectedDesigner = designer;
  }

  /**
   * 获取设计师工作量统计
   */
  getDesignerWorkload(designer: FmodeObject): string {
    // TODO: 查询该设计师当前进行中的项目数量
    return '3个项目';
  }

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

    try {
      this.saving = true;

      // 更新项目基本信息
      this.project.set('title', this.projectInfo.title);
      this.project.set('type', this.projectInfo.type);
      this.project.set('deadline', this.projectInfo.deadline);
      this.project.set('description', this.projectInfo.description);

      // 保存报价明细到 data 字段
      const data = this.project.get('data') || {};
      data.quotation = this.quotation;
      this.project.set('data', data);

      // 保存设计师分配
      if (this.selectedDesigner) {
        this.project.set('assignee', this.selectedDesigner.toPointer());
      }

      await this.project.save();

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

  /**
   * 提交审批
   */
  async submitForApproval() {
    if (!this.project || !this.canEdit) return;

    // 验证必填项
    if (!this.projectInfo.title.trim()) {
      alert('请填写项目名称');
      return;
    }

    if (!this.projectInfo.deadline) {
      alert('请选择交付期限');
      return;
    }

    if (this.quotation.total === 0) {
      alert('请配置报价明细');
      return;
    }

    if (!this.selectedDesigner) {
      alert('请选择设计师');
      return;
    }

    try {
      this.saving = true;

      // 1. 保存项目信息
      await this.saveDraft();

      // 2. 更新项目状态
      this.project.set('status', '待审核');
      this.project.set('currentStage', '订单分配');

      // 3. 添加审批记录到 data 字段
      const data = this.project.get('data') || {};
      const approvalHistory = data.approvalHistory || [];

      approvalHistory.push({
        stage: '订单分配',
        submitter: {
          id: this.currentUser!.id,
          name: this.currentUser!.get('name'),
          role: this.currentUser!.get('roleName')
        },
        submitTime: new Date(),
        status: 'pending',
        quotationTotal: this.quotation.total,
        assignee: {
          id: this.selectedDesigner.id,
          name: this.selectedDesigner.get('name')
        }
      });

      data.approvalHistory = approvalHistory;
      this.project.set('data', data);

      await this.project.save();

      // 4. TODO: 发送企微消息通知组长审批

      alert('提交成功，等待组长审批');

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

  /**
   * 检查工序是否启用
   */
  isProcessEnabled(space: any, processKey: string): boolean {
    const process = (space.processes as any)[processKey];
    return process?.enabled || false;
  }

  /**
   * 设置工序价格
   */
  setProcessPrice(space: any, processKey: string, value: any): void {
    const process = (space.processes as any)[processKey];
    if (process) {
      process.price = value;
    }
  }

  /**
   * 设置工序数量
   */
  setProcessQuantity(space: any, processKey: string, value: any): void {
    const process = (space.processes as any)[processKey];
    if (process) {
      process.quantity = value;
    }
  }

  /**
   * 获取工序价格
   */
  getProcessPrice(space: any, processKey: string): number {
    const process = (space.processes as any)[processKey];
    return process?.price || 0;
  }

  /**
   * 获取工序数量
   */
  getProcessQuantity(space: any, processKey: string): number {
    const process = (space.processes as any)[processKey];
    return process?.quantity || 0;
  }

  /**
   * 获取工序单位
   */
  getProcessUnit(space: any, processKey: string): string {
    const process = (space.processes as any)[processKey];
    return process?.unit || '';
  }

  /**
   * 计算工序小计
   */
  calculateProcessSubtotal(space: any, processKey: string): number {
    const process = (space.processes as any)[processKey];
    return (process?.price || 0) * (process?.quantity || 0);
  }

  /**
   * 获取项目类型图标
   */
  getProjectTypeIcon(type: string): string {
    const iconMap: any = {
      '整屋设计': 'home-outline',
      '局部改造': 'construct-outline',
      '软装设计': 'color-palette-outline'
    };
    return iconMap[type] || 'document-outline';
  }
}
