import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Card, Button, Space, Form } from 'antd';
import styles from '../supplierTaskManageAdd.less';
import {
  SupplierTable,
  BatchEvaluatorModal,
  SupplierEvaluatorModal,
  WeightSettingModal,
} from './EvaluatorComponents';
import { ModalMode } from '@/servers/types/evaluator';
import type { PersonnelItem, SupplierItem } from '@/servers/types/evaluator';
import type { DeptWeightItem,TaskAddRequest } from '@/servers/types/supplierEvaluateTask';

interface EvaluatorSelectStepProps {
  formData: Partial<TaskAddRequest>; // 从上层组件传递过来的表单数据
  onFormDataChange: (data: Partial<TaskAddRequest>) => void; // 表单数据变更回调函数
}

const EvaluatorSelectStep = forwardRef<any, EvaluatorSelectStepProps>(
  ({ formData, onFormDataChange }, ref) => {
    // 选中的供应商行的key列表，用于批量操作
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

    // 供应商列表数据，包含评价人员信息
    const [suppliers, setSuppliers] = useState<SupplierItem[]>([]);

    // 批量选择模态框的可见性控制
    const [batchSelectModalVisible, setBatchSelectModalVisible] = useState(false);

    // 权重设置模态框的可见性控制
    const [weightSettingModalVisible, setWeightSettingModalVisible] = useState(false);

    // 评价人员选择/查看模态框的可见性控制
    const [evaluatorModalVisible, setEvaluatorModalVisible] = useState(false);

    // 当前操作的供应商对象，用于评价人员的选择和查看
    const [currentSupplier, setCurrentSupplier] = useState<SupplierItem | null>(null);

    // 模态框模式：SELECT(选择模式) 或 VIEW(查看模式)
    const [modalMode, setModalMode] = useState<ModalMode>(ModalMode.SELECT);

    // 权重单位列表，根据评价人员部门动态生成
    const [taskDeptWeightList, setTaskDeptWeightList] = useState<DeptWeightItem[]>([]);

    // 表单实例，用于权重设置
    const [form] = Form.useForm();

    // 暴露表单方法给父组件
    useImperativeHandle(ref, () => ({
      validateFields: () => {
        // 自定义验证逻辑
        if (suppliers.length === 0) {
          return Promise.reject('请至少添加一个供应商');
        }

        // 检查是否每个供应商都有评价人员
        const hasNoEvaluator = suppliers.some(
          (supplier) => !supplier.evaluators || supplier.evaluators.length === 0,
        );

        if (hasNoEvaluator) {
          return Promise.reject('存在未分配评价人员的供应商');
        }

        return Promise.resolve();
      },
      getFieldsValue: () => {
        // 构建评价人员列表
        const indicatorList = suppliers.flatMap(
          (supplier) =>
            supplier.evaluators?.map((evaluator: PersonnelItem) => ({
              userId: evaluator.id,
              type: 0, //  type  评价类型(默认0 按评价单 ,当用户关联了指标则为 :1 按指标)
              indicatorIds: [],
            })) || [],
        );

        // 构建供应商ID列表
        const supplierIds = suppliers.map((supplier) => ({
          id: supplier.id,
          userIds: supplier.evaluators?.map((e: PersonnelItem) => e.id) || [],
        }));

        return {
          indicatorList,
          supplierIds,
          suppliersWithEvaluators: suppliers,
          taskDeptWeightList,
        };
      },
      setFieldsValue: (values: any) => {
        if (values.suppliersWithEvaluators) {
          setSuppliers(values.suppliersWithEvaluators);
        }
        if (values.taskDeptWeightList) {
          setTaskDeptWeightList(values.taskDeptWeightList);
        }
      },
    }));

    // 从上一步获取供应商数据
    useEffect(() => {
      console.log(formData.selectedSuppliers)
      if (formData.selectedSuppliers && formData.selectedSuppliers.length > 0) {
        // 转换上一步的供应商数据，添加评价人员数量字段
        const suppliersWithEvaluators = formData.selectedSuppliers.map((supplier: SupplierItem) => {
          // 确保evaluators字段存在且为数组
          const evaluators = supplier.evaluators || [];
          return {
            ...supplier,
            userDept: supplier.userDept || '采购部', // 假设部门数据，实际应该从上一步获取
            evaluatorCount: evaluators.length,
            evaluators: evaluators,
          };
        });
        setSuppliers(suppliersWithEvaluators);
      } else {
        // 没有选择供应商，清空供应商列表
        setSuppliers([]);
      }

      // 初始化权重数据（如果有）
      if (formData.taskDeptWeightList && formData.taskDeptWeightList.length > 0) {
        setTaskDeptWeightList(formData.taskDeptWeightList);
      } else {
        // 没有权重数据，将在下面的useEffect中根据人员部门计算
        setTaskDeptWeightList([]);
      }
    }, [formData]);

    // 当选择的人员变化时，更新权重单位列表
    useEffect(() => {
      // 抽取所有评价人员的部门
      const allDepartments: PersonnelItem[] = [];

      suppliers.forEach((supplier) => {
        if (supplier.evaluators && supplier.evaluators.length > 0) {
          supplier.evaluators.forEach((evaluator) => {
            if (evaluator.userDept) {
              allDepartments.push(evaluator);
            }
          });
        }
      });

      // 去重部门列表 - 根据部门ID去重
      const departmentMap = new Map<string, PersonnelItem>();
      allDepartments.forEach(dept => {
        if (dept.userDeptId && !departmentMap.has(dept.userDeptId)) {
          departmentMap.set(dept.userDeptId, dept);
        }
      });
      const uniqueDepartments = Array.from(departmentMap.values());

      // 如果有部门数据，生成权重单位列表
      if (uniqueDepartments.length > 0) {
        const newTaskDeptWeightList: DeptWeightItem[] = uniqueDepartments.map((dept) => ({
          weightDept: dept.userDeptId || '',
          weightValue: '0', // 默认权重为0
          weightDeptName: dept.userDept || '',
        }));

        // 更新权重单位列表，保留原有权重值
        setTaskDeptWeightList((prevList) => {
          const prevValuesMap = new Map(prevList.map((item) => [item.weightDept, item.weightValue]));

          return newTaskDeptWeightList.map((item) => ({
            ...item,
            weightValue: prevValuesMap.get(item.weightDept) || '0', // 如果有原来的权重值则保留
          }));
        });
      }
    }, [suppliers]);

    // 更新表单数据
    const updateFormData = (updatedData: any) => {
      // // 构建评价人员列表
      const indicatorList = suppliers.flatMap(
        (supplier) =>
          supplier.evaluators?.map((evaluator: PersonnelItem) => ({
            userId: evaluator.id,
            type: 0, // 默认按评价单评价 (没有指派分工),如果指派了 (就 1 按指标)
            indicatorIds: [], // 指标id集合
          })) || [],
      );

      // 构建供应商ID列表
      const supplierIds = suppliers.map((supplier) => ({
        id: supplier.id,
        userIds: supplier.evaluators?.map((e: PersonnelItem) => e.id) || [],
      }));

      // 如果有taskDeptWeightList数据，直接使用
      if (updatedData.taskDeptWeightList) {
        onFormDataChange({
          ...updatedData,
          indicatorList,
          supplierIds,
        });
      } else {
        // 否则包含当前的taskDeptWeightList
        onFormDataChange({
          ...updatedData,
          indicatorList,
          supplierIds,
          taskDeptWeightList,
        });
      }
    };

    // 处理批量选择
    const handleBatchSelect = () => {
      if (selectedRowKeys.length === 0) return;
      setBatchSelectModalVisible(true);
    };

    // 处理设置评分单位权重
    const handleWeightSetting = () => {
      // 设置初始表单值
      form.setFieldsValue({
        taskDeptWeightList: taskDeptWeightList.reduce((acc, item) => {
          acc[item.weightDept] = parseInt(item.weightValue, 10) || 0;
          return acc;
        }, {} as Record<string, number>),
      });

      setWeightSettingModalVisible(true);
    };

    // 保存权重设置
    const handleSaveWeights = () => {
      form.validateFields().then((values) => {
        const updatedTaskDeptWeightList = taskDeptWeightList.map((item) => ({
          ...item,
          weightValue: values.taskDeptWeightList[item.weightDept].toString(),
        }));

        setTaskDeptWeightList(updatedTaskDeptWeightList);

        updateFormData({
          suppliersWithEvaluators: suppliers,
          taskDeptWeightList: updatedTaskDeptWeightList,
        });

        setWeightSettingModalVisible(false);
      });
    };

    // 处理选择评价人员
    const handleSelectEvaluators = (supplier: SupplierItem) => {
      setCurrentSupplier(supplier);
      setModalMode(ModalMode.SELECT);
      setEvaluatorModalVisible(true);
    };

    // 处理查看评价人员
    const handleViewEvaluators = (supplier: SupplierItem) => {
      // 查找完整的供应商数据（包括evaluators）
      const fullSupplier = suppliers.find((s) => s.id === supplier.id);
      if (fullSupplier) {
        setCurrentSupplier(fullSupplier);
      } else {
        setCurrentSupplier(supplier);
      }

      setModalMode(ModalMode.VIEW);
      setEvaluatorModalVisible(true);
    };

    // 处理评价人员选择确认
    const handleEvaluatorSelect = (selectedEvaluators: PersonnelItem[]) => {
      if (!currentSupplier) return;

      const updatedSuppliers = suppliers.map((supplier) => {
        if (supplier.id === currentSupplier.id) {
          const updated = {
            ...supplier,
            evaluators: selectedEvaluators,
            evaluatorCount: selectedEvaluators.length,
          };
          return updated;
        }
        return supplier;
      });

      setSuppliers(updatedSuppliers);
      updateFormData({ suppliersWithEvaluators: updatedSuppliers });
      setEvaluatorModalVisible(false);
    };

    // 处理批量选择评价人员确认
    const handleBatchEvaluatorSelect = (selectedEvaluators: PersonnelItem[]) => {
      if (selectedRowKeys.length === 0) return;
      const updatedSuppliers = suppliers.map((supplier) => {
        if (selectedRowKeys.includes(supplier.id)) {
          return {
            ...supplier,
            evaluators: selectedEvaluators,
            evaluatorCount: selectedEvaluators.length,
          };
        }
        return supplier;
      });
      setSuppliers(updatedSuppliers);
      updateFormData({ suppliersWithEvaluators: updatedSuppliers });
      setBatchSelectModalVisible(false);
    };

    // 处理删除供应商
    const handleDeleteSupplier = (key: string) => {
      const updatedSuppliers = suppliers.filter((item) => item.id !== key);
      setSuppliers(updatedSuppliers);
      updateFormData({ suppliersWithEvaluators: updatedSuppliers });
      // 更新选中行，移除已删除的供应商
      setSelectedRowKeys((prevKeys) => prevKeys.filter((k) => k !== key));
    };

    return (
      <div className={styles.evaluatorSelectStep}>
        <Card title="选择评价人员" bordered={false} className="inner-card">
          <div className={styles.toolbar}>
            <Space>
              <Button
                type="primary"
                onClick={handleBatchSelect}
                disabled={selectedRowKeys.length === 0}
              >
                批量选择评价人员
              </Button>
              <Button onClick={handleWeightSetting} disabled={taskDeptWeightList.length === 0}>
                设置评分单位权重
              </Button>
            </Space>
          </div>

          {suppliers.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '30px 0', color: '#999' }}>
              请先在上一步选择供应商
            </div>
          ) : (
            <SupplierTable
              suppliers={suppliers}
              selectedRowKeys={selectedRowKeys}
              onSelectChange={setSelectedRowKeys}
              onViewEvaluators={handleViewEvaluators}
              onSelectEvaluators={handleSelectEvaluators}
              onDeleteSupplier={handleDeleteSupplier}
            />
          )}

          {/* 批量选择评价人员弹窗 */}
          <BatchEvaluatorModal
            visible={batchSelectModalVisible}
            onCancel={() => setBatchSelectModalVisible(false)}
            onSelect={handleBatchEvaluatorSelect}
          />

          {/* 单个供应商评价人员弹窗 */}
          <SupplierEvaluatorModal
            visible={evaluatorModalVisible}
            onCancel={() => setEvaluatorModalVisible(false)}
            onSelect={handleEvaluatorSelect}
            currentSupplier={currentSupplier}
            mode={modalMode}
          />

          {/* 权重设置弹窗 */}
          <WeightSettingModal
            visible={weightSettingModalVisible}
            onCancel={() => setWeightSettingModalVisible(false)}
            onOk={handleSaveWeights}
            taskDeptWeightList={taskDeptWeightList}
            form={form}
          />
        </Card>
      </div>
    );
  },
);

export default EvaluatorSelectStep;
