import { Component, OnInit, Input } 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 {
  QUOTATION_PRICE_TABLE,
  STYLE_LEVELS,
  SPACE_TYPES,
  BUSINESS_TYPES,
  HOME_DEFAULT_ROOMS,
  ADJUSTMENT_RULES,
  getBasePrice,
  calculateFinalPrice,
  getDefaultProcesses
} from '../../../config/quotation-rules';
import { QuotationEditorComponent } from '../../../components/quotation-editor.component';

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

/**
 * 订单分配阶段组件
 *
 * 功能：
 * 1. 家装/工装项目类型选择
 * 2. 快速场景选择，自动生成报价表（基于quotation.md规则）
 * 3. 项目组（Department）→ 组员（Profile）两级设计师分配
 * 4. 提交审批
 */
@Component({
  selector: 'app-stage-order',
  standalone: true,
  imports: [CommonModule, FormsModule, QuotationEditorComponent],
  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: '',
    projectType: '', // 家装 | 工装
    renderType: '', // 静态单张 | 360全景
    deadline: '',
    description: '',
    priceLevel: '一级' // 一级(老客户) | 二级(中端组) | 三级(高端组)
  };

  hasSpacesDisabled(){
    return !this.canEdit || !this.commercialScenes?.spaces?.some(s => s?.selected)
  }
  hasRoomsDisabled(){
    return !this.canEdit || !this.homeScenes?.rooms?.some((r:any) => r?.selected)
  }
  getLevels(levels:any){
    if(!levels) return []
    return Object.keys(levels)
  }
  // 场景选择（家装）
  homeScenes = {
    spaceType: '', // 平层 | 跃层 | 挑空
    styleLevel: '', // 基础风格组 | 中级风格组 | 高级风格组 | 顶级风格组
    rooms: [] as Array<{
      name: string; // 客厅、主卧、次卧等
      selected: boolean;
      basePrice: number;
      adjustments: {
        extraFunction: number; // 功能区加价
        complexity: number; // 造型复杂度加价
        design: boolean; // 是否需要设计服务（×2）
      };
    }>
  };

  // 场景选择（工装）
  commercialScenes = {
    businessType: '', // 办公空间 | 商业空间 | 娱乐空间 | 酒店餐厅 | 公共空间
    spaces: [] as Array<{
      name: string;
      type: string; // 门厅空间 | 封闭空间
      selected: boolean;
      basePrice: number;
      adjustments: {
        extraFunction: number;
        complexity: number;
        design: boolean;
        panoramic: boolean; // 是否全景渲染（×2）
      };
    }>
  };

  // 报价明细（最终生成）
  quotation = {
    spaces: [] as Array<{
      name: string;
      processes: {
        modeling: { enabled: boolean; price: number; unit: string; quantity: number };
        softDecor: { enabled: boolean; price: number; unit: string; quantity: number };
        rendering: { enabled: boolean; price: number; unit: string; quantity: number };
        postProcess: { enabled: boolean; price: number; unit: string; quantity: number };
      };
      subtotal: number;
    }>,
    total: 0
  };

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

  // 项目组（Department）列表
  departments: FmodeObject[] = [];
  selectedDepartment: FmodeObject | null = null;

  // 项目组成员（Profile）列表
  departmentMembers: FmodeObject[] = [];
  selectedDesigner: FmodeObject | null = null;

  // 已分配的项目团队成员
  projectTeams: FmodeObject[] = [];

  // 设计师分配对话框
  showAssignDialog: boolean = false;
  assigningDesigner: FmodeObject | null = null;
  selectedSpaces: string[] = [];
  editingTeam: FmodeObject | null = null; // 当前正在编辑的团队对象

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

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

  // 从配置导入报价表和规则
  priceTable = QUOTATION_PRICE_TABLE;
  styleLevels = STYLE_LEVELS;
  spaceTypes = SPACE_TYPES;
  businessTypes = BUSINESS_TYPES;
  homeDefaultRooms = HOME_DEFAULT_ROOMS;
  adjustmentRules = ADJUSTMENT_RULES;

  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;

      // 使用FmodeParse加载项目、客户、当前用户
      if (!this.project && this.projectId) {
        const query = new Parse.Query('Project');
        query.include('customer', 'assignee', 'department');
        this.project = await query.get(this.projectId);
        this.customer = this.project.get('customer');
        this.selectedDesigner = this.project.get('assignee');
      }

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

      // 加载项目信息
      if (this.project) {
        this.projectInfo.title = this.project.get('title') || '';
        this.projectInfo.projectType = this.project.get('projectType') || '';
        this.projectInfo.renderType = this.project.get('renderType') || '';
        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;
        }

        if (data.priceLevel) {
          this.projectInfo.priceLevel = data.priceLevel;
        }

        // 加载场景选择数据
        if (data.homeScenes) {
          this.homeScenes = data.homeScenes;
        }
        if (data.commercialScenes) {
          this.commercialScenes = data.commercialScenes;
        }

        // 加载已分配的项目组和设计师
        const department = this.project.get('department');
        if (department) {
          this.selectedDepartment = department;
          await this.loadDepartmentMembers(department.id);
        }

        const assignee = this.project.get('assignee');
        if (assignee) {
          this.selectedDesigner = assignee;
        }
      }

      // 使用FmodeParse加载项目组列表（Department表）
      const deptQuery = new Parse.Query('Department');
      deptQuery.include("leader");
      deptQuery.equalTo('type', 'project');
      deptQuery.equalTo('company', localStorage.getItem('company'));
      deptQuery.notEqualTo('isDeleted', true);
      deptQuery.ascending('name');
      this.departments = await deptQuery.find();

      // 加载已分配的项目团队
      await this.loadProjectTeams();

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

  /**
   * 项目类型改变，初始化场景数据
   */
  onProjectTypeChange() {
    this.quotation.spaces = [];
    this.quotation.total = 0;

    if (this.projectInfo.projectType === '家装') {
      this.homeScenes = {
        spaceType: '',
        styleLevel: '',
        rooms: []
      };
      this.commercialScenes = { businessType: '', spaces: [] };
    } else if (this.projectInfo.projectType === '工装') {
      this.commercialScenes = {
        businessType: '',
        spaces: []
      };
      this.homeScenes = { spaceType: '', styleLevel: '', rooms: [] };
    }
  }

  /**
   * 家装场景：空间类型和风格等级改变，生成预设房间列表
   */
  onHomeSceneChange() {
    if (!this.homeScenes.spaceType || !this.homeScenes.styleLevel) {
      this.homeScenes.rooms = [];
      return;
    }

    const renderType = this.projectInfo.renderType || '静态单张';

    // 使用配置文件中的工具函数获取价格
    this.homeScenes.rooms = this.homeDefaultRooms.map(name => {
      const spaceType = name.includes('卧') ? '卧室' : this.homeScenes.spaceType;
      const basePrice = getBasePrice(
        this.projectInfo.priceLevel,
        '家装',
        renderType,
        spaceType,
        this.homeScenes.styleLevel
      );

      return {
        name,
        selected: false,
        basePrice,
        adjustments: {
          extraFunction: 0,
          complexity: 0,
          design: false
        }
      };
    });
  }

  /**
   * 工装场景：业态类型改变，生成预设空间列表
   */
  onCommercialTypeChange() {
    if (!this.commercialScenes.businessType) {
      this.commercialScenes.spaces = [];
      return;
    }

    const renderType = '静态单张';

    this.commercialScenes.spaces = [
      {
        name: '门厅',
        type: '门厅空间',
        selected: false,
        basePrice: getBasePrice(
          this.projectInfo.priceLevel,
          '工装',
          renderType,
          '门厅空间',
          undefined,
          this.commercialScenes.businessType
        ),
        adjustments: {
          extraFunction: 0,
          complexity: 0,
          design: false,
          panoramic: false
        }
      },
      {
        name: '封闭空间1',
        type: '封闭空间',
        selected: false,
        basePrice: getBasePrice(
          this.projectInfo.priceLevel,
          '工装',
          renderType,
          '封闭空间',
          undefined,
          this.commercialScenes.businessType
        ),
        adjustments: {
          extraFunction: 0,
          complexity: 0,
          design: false,
          panoramic: false
        }
      }
    ];
  }

  /**
   * 生成最终报价明细
   */
  generateQuotation() {
    this.quotation.spaces = [];

    if (this.projectInfo.projectType === '家装') {
      // 遍历选中的房间
      for (const room of this.homeScenes.rooms.filter(r => r.selected)) {
        // 使用配置文件中的价格计算函数
        const finalPrice = calculateFinalPrice(
          room.basePrice,
          '家装',
          {
            extraFunction: room.adjustments.extraFunction,
            complexity: room.adjustments.complexity,
            design: room.adjustments.design
          }
        );

        // 使用配置文件生成默认工序
        const processes = getDefaultProcesses('家装', finalPrice);

        this.quotation.spaces.push({
          name: room.name,
          processes: processes as any,
          subtotal: finalPrice + processes.postProcess.price
        });
      }
    } else if (this.projectInfo.projectType === '工装') {
      // 遍历选中的空间
      for (const space of this.commercialScenes.spaces.filter(s => s.selected)) {
        const finalPrice = calculateFinalPrice(
          space.basePrice,
          '工装',
          {
            extraFunction: space.adjustments.extraFunction,
            complexity: space.adjustments.complexity,
            design: space.adjustments.design,
            panoramic: space.adjustments.panoramic
          }
        );

        const processes = getDefaultProcesses('工装', finalPrice);

        this.quotation.spaces.push({
          name: space.name,
          processes: processes as any,
          subtotal: finalPrice + processes.postProcess.price
        });
      }
    }

    this.calculateTotal();
  }

  /**
   * 计算报价总额
   */
  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;
  }

  /**
   * 选择项目组（Department）
   */
  async selectDepartment(department: FmodeObject) {
    if (this.canEdit || this.project?.get('assignee')?.id){
      
      this.selectedDepartment = department;
      this.selectedDesigner = null;
      this.departmentMembers = [];
      
      await this.loadDepartmentMembers(department);
    }
  }

  /**
   * 加载项目组成员
   */
  async loadDepartmentMembers(department: FmodeObject) {
    let departmentId = department.id
    if(!departmentId) return []
    try {
      this.loadingMembers = true;

      // 使用FmodeParse查询项目组的组员（Profile表，roleName为"组员"）
      const query = new Parse.Query('Profile');
      query.equalTo('department', departmentId);
      query.equalTo('roleName', '组员');
      query.notEqualTo('isDeleted', true);
      query.ascending('name');

      this.departmentMembers = await query.find();
      this.departmentMembers.unshift(department?.get("leader"))
      return this.departmentMembers
    } catch (err) {
      console.error('加载项目组成员失败:', err);
    } finally {
      this.loadingMembers = false;
    }
    return []
  }

  /**
   * 加载已分配的ProjectTeam
   */
  async loadProjectTeams() {
    if (!this.project) return;

    try {
      this.loadingTeams = true;

      const query = new Parse.Query('ProjectTeam');
      query.equalTo('project', this.project.toPointer());
      query.include('profile');
      query.notEqualTo('isDeleted', true);

      this.projectTeams = await query.find();
    } catch (err) {
      console.error('加载项目团队失败:', err);
    } finally {
      this.loadingTeams = false;
    }
  }

  /**
   * 选择设计师 - 弹出分配对话框
   */
  selectDesigner(designer: FmodeObject) {
    // 检查是否已分配
    const isAssigned = this.projectTeams.some(team => team.get('profile')?.id === designer.id);
    if (isAssigned) {
      alert('该设计师已分配到此项目');
      return;
    }

    this.assigningDesigner = designer;
    this.selectedSpaces = [];

    // 如果只有一个空间，默认选中
    if (this.quotation.spaces.length === 1) {
      this.selectedSpaces = [this.quotation.spaces[0].name];
    }

    this.showAssignDialog = true;
  }

  /**
   * 编辑已分配的设计师 - 重用分配对话框
   */
  editAssignedDesigner(team: FmodeObject) {
    if (!this.canEdit) return;

    const designer = team.get('profile');
    if (!designer) return;

    // 设置当前编辑的设计师和团队对象
    this.assigningDesigner = designer;
    this.editingTeam = team;

    // 预选当前已分配的空间
    const currentSpaces = team.get('data')?.spaces || [];
    this.selectedSpaces = [...currentSpaces];

    this.showAssignDialog = true;
  }

  /**
   * 切换空间选择
   */
  toggleSpaceSelection(spaceName: string) {
    const index = this.selectedSpaces.indexOf(spaceName);
    if (index > -1) {
      this.selectedSpaces.splice(index, 1);
    } else {
      this.selectedSpaces.push(spaceName);
    }
  }

  /**
   * 确认分配设计师（支持创建和更新）
   */
  async confirmAssignDesigner() {
    if (!this.assigningDesigner || !this.project) return;

    if (this.selectedSpaces.length === 0) {
      alert('请至少选择一个空间场景');
      return;
    }

    try {
      this.saving = true;

      if (this.editingTeam) {
        // 更新现有团队成员的空间分配
        const data = this.editingTeam.get('data') || {};
        data.spaces = this.selectedSpaces;
        data.updatedAt = new Date();
        data.updatedBy = this.currentUser?.id;
        this.editingTeam.set('data', data);

        await this.editingTeam.save();

        alert('更新成功');
      } else {
        // 创建新的 ProjectTeam
        const ProjectTeam = Parse.Object.extend('ProjectTeam');
        const team = new ProjectTeam();
        team.set('project', this.project.toPointer());
        team.set('profile', this.assigningDesigner.toPointer());
        team.set('role', '组员');
        team.set('data', {
          spaces: this.selectedSpaces,
          assignedAt: new Date(),
          assignedBy: this.currentUser?.id
        });

        await team.save();

        // 加入群聊（静默执行）
        await this.addMemberToGroupChat(this.assigningDesigner.get('userId'));

        alert('分配成功');
      }

      // 重新加载团队列表
      await this.loadProjectTeams();

      this.showAssignDialog = false;
      this.assigningDesigner = null;
      this.selectedSpaces = [];
      this.editingTeam = null;

    } catch (err) {
      console.error(this.editingTeam ? '更新失败:' : '分配设计师失败:', err);
      alert(this.editingTeam ? '更新失败' : '分配失败');
    } finally {
      this.saving = false;
    }
  }

  /**
   * 取消分配对话框
   */
  cancelAssignDialog() {
    this.showAssignDialog = false;
    this.assigningDesigner = null;
    this.selectedSpaces = [];
    this.editingTeam = null;
  }

  /**
   * 添加成员到群聊（静默执行）
   */
  async addMemberToGroupChat(userId: string) {
    if (!userId) return;

    try {
      // 从父组件获取groupChat和chatId
      const groupChat = (this as any).groupChat;
      if (!groupChat) return;

      const chatId = groupChat.get('chat_id');
      if (!chatId) return;

      // 调用企微SDK添加成员（需要在前端通过ww对象调用）
      // 这部分需要在浏览器环境中通过企微JSSDK执行
      if (typeof (window as any).ww !== 'undefined') {
        await (window as any).ww.updateEnterpriseChat({
          chatId: chatId,
          userIdsToAdd: [userId]
        });
      }
    } catch (err) {
      // 静默失败，不影响主流程
      console.warn('添加群成员失败:', err);
    }
  }

  /**
   * 获取团队成员负责的空间
   */
  getMemberSpaces(team: FmodeObject): string {
    const spaces = team.get('data')?.spaces || [];
    return spaces.join('、') || '未分配';
  }

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

  /**
   * 报价数据变化回调
   */
  onQuotationChange(updatedQuotation: any) {
    this.quotation = updatedQuotation;
  }

  /**
   * 报价总额变化回调
   */
  onTotalChange(total: number) {
    this.quotation.total = total;
  }

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

    try {
      this.saving = true;

      this.project.set('title', this.projectInfo.title);
      this.project.set('projectType', this.projectInfo.projectType);
      this.project.set('renderType', this.projectInfo.renderType);
      this.project.set('deadline', this.projectInfo.deadline);
      this.project.set('description', this.projectInfo.description);

      const data = this.project.get('data') || {};
      data.quotation = this.quotation;
      data.priceLevel = this.projectInfo.priceLevel;
      data.homeScenes = this.homeScenes;
      data.commercialScenes = this.commercialScenes;
      this.project.set('data', data);

      if (this.selectedDepartment) {
        this.project.set('department', this.selectedDepartment.toPointer());
      }

      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 submitForOrder() {
    if (!this.project || !this.canEdit) return;

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

    if (!this.projectInfo.projectType) {
      alert('请选择项目类型');
      return;
    }

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

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

    if (!this.selectedDepartment) {
      alert('请选择项目组');
      return;
    }

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

    try {
      this.saving = true;

      await this.saveDraft();

      this.project.set('currentStage', '确认需求');

      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: 'confirm',
        quotationTotal: this.quotation.total,
        department: {
          id: this.selectedDepartment.id,
          name: this.selectedDepartment.get('name')
        },
        assignee: {
          id: this.selectedDesigner.id,
          name: this.selectedDesigner.get('name')
        }
      });

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

      await this.project.save();

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

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

}
