import React, { useState, useRef, useEffect } from 'react';
import { Card, Steps, Button, message, Space, Row, Col, Form, Modal } from 'antd';
import { history } from 'umi';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { addTask, getTaskDetail, updateTask } from '@/servers/api/supplierEvaluate';
import BasicInfoStep from './components/BasicInfoStep';
import SupplierSelectStep from './components/SupplierSelectStep';
import EvaluatorSelectStep from './components/EvaluatorSelectStep';
import DivisionStep from './components/DivisionStep';
import styles from './supplierTaskManageAdd.less';
import type {
  DeptWeightItem,
  TaskAddRequest,
  TaskDetailData,
} from '@/servers/types/supplierEvaluateTask';
import { TaskNotifyLowerUnits } from '@/dicts/supplierTaskDict';

const { Step } = Steps;

// 获取URL参数
const getUrlParams = () => {
  const location = window.location.href;
  const url = new URL(location);
  return {
    id: url.searchParams.get('id'),
    mode: url.searchParams.get('mode'),
  };
};

const SupplierTaskManageAdd: React.FC = () => {
  // 当前步骤索引，从0开始
  const [currentStep, setCurrentStep] = useState<number>(0);

  // 提交加载状态
  const [loading, setLoading] = useState<boolean>(false);

  // 判断是否为编辑模式
  const urlParams = getUrlParams();
  const isEditMode = urlParams.mode === 'edit' && urlParams.id;
  const taskId = urlParams.id || '';

  // 整个表单的数据，包含所有步骤的数据
  const [formData, setFormData] = useState<Partial<TaskAddRequest>>({});

  // 加载状态
  const [detailLoading, setDetailLoading] = useState<boolean>(false);

  // 创建表单引用，用于访问子组件的表单方法（仅用于验证）
  const basicFormRef = useRef<any>(null); // 基本信息表单引用
  const supplierFormRef = useRef<any>(null); // 供应商选择表单引用
  const evaluatorFormRef = useRef<any>(null); // 评价人员表单引用
  const divisionFormRef = useRef<any>(null); // 评价分工表单引用

  // 确认对话框可见性状态
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);

  // 获取任务详情
  const fetchTaskDetail = async (id: string) => {
    setDetailLoading(true);
    try {
      const response = await getTaskDetail(id);
      if (response.success) {
        const detail: TaskDetailData = response.data;

        // 转换任务详情数据为表单数据结构
        const taskFormData: Partial<TaskAddRequest> = {
          id: detail.id || '',
          evaluateTheme: detail.evaluateTheme || '',
          startTime: detail.startTime || '',
          endTime: detail.endTime || '',
          templateId: detail.templateId || '',
          categoryLimitation: detail.categoryLimitation || '0',
          evaluateYear: detail.evaluateYear || '',
          categoryId: detail.categoryId || undefined,

          // 供应商数据回显转换
          selectedSuppliers: detail.blackSupplierVos.map((item) => ({
            ...item,
            id: item.supplierId,
            name: item.supplierName,
            evaluators: item.userList,
          })),

          // 接口返回的人员分配的指标,以人员userId 为维度 indicatorIds[string] 指标id
          indicatorList: detail.indicatorList || [],
          //  后台用供应商集合,包含供应商id 并且关联 userIds
          supplierIds: detail.supplierIds || [],

          // 部门权重设置
          taskDeptWeightList: detail.taskDeptWeightList || [],
          // 分配指标分工回显
          suppliersWithEvaluators: detail.blackSupplierVos.map((item) => ({
            ...item,
            id: item.supplierId,
            name: item.supplierName,
            evaluators: item.userList,
          })),
        };

        // 更新表单数据 - 子组件通过props获取
        setFormData(taskFormData);
      } else {
        message.error(response.message || '获取任务详情失败');
      }
    } catch (error) {
      console.error('获取任务详情失败:', error);
      message.error('获取任务详情失败');
    } finally {
      setDetailLoading(false);
    }
  };

  // 编辑模式下获取任务详情
  useEffect(() => {
    if (isEditMode) {
      fetchTaskDetail(taskId);
    }
  }, [isEditMode, taskId]);

  // 处理表单数据变更
  const handleFormDataChange = (data: Partial<TaskAddRequest>) => {
    // 第一步：基本信息
    if (data) {
      setFormData((prev) => ({ ...prev, ...data }));
    }

    // 第二步：供应商选择
    if (data.selectedSuppliers) {
      // 确保供应商数据包含evaluators字段
      const suppliersWithEvaluators = data.selectedSuppliers.map((supplier: any) => ({
        ...supplier,
        evaluators: supplier.evaluators || [], // 确保evaluators字段存在
      }));

      setFormData((prev) => ({ ...prev, selectedSuppliers: suppliersWithEvaluators }));
    }

    // 第三步：评价人员
    if (data.suppliersWithEvaluators) {
      // 确保suppliersWithEvaluators和selectedSuppliers保持一致
      const evaluatedSuppliers = data.suppliersWithEvaluators;
      setFormData((prev) => ({
        ...prev,
        suppliersWithEvaluators: evaluatedSuppliers,
        selectedSuppliers: evaluatedSuppliers, // 同步更新selectedSuppliers
      }));
    }

    // 处理部门权重列表 taskDeptWeightList
    if (data.taskDeptWeightList) {
      setFormData((prev) => ({
        ...prev,
        taskDeptWeightList: data.taskDeptWeightList,
      }));
    }
  };

  // 步骤配置
  const steps = [
    {
      title: '基本信息', // 步骤标题
      description: '请填写基本信息', // 步骤描述
      content: (
        <BasicInfoStep
          formData={formData}
          onFormDataChange={handleFormDataChange}
          ref={basicFormRef}
        />
      ), // 步骤内容组件
    },
    {
      title: '选择供应商',
      description: '请选择参加评价的供应商',
      content: (
        <SupplierSelectStep
          formData={formData}
          onFormDataChange={handleFormDataChange}
          ref={supplierFormRef}
        />
      ),
    },
    {
      title: '选择评价人员',
      description: '请选择供应商评价人员',
      content: (
        <EvaluatorSelectStep
          formData={formData}
          onFormDataChange={handleFormDataChange}
          ref={evaluatorFormRef}
        />
      ),
    },
    {
      title: '设置评价分工',
      description: '不设置按默认全部指标评价',
      content: (
        <DivisionStep
          formData={formData}
          onFormDataChange={handleFormDataChange}
          ref={divisionFormRef}
        />
      ),
    },
  ];

  // 处理返回
  const handleBack = () => {
    history.goBack();
  };

  // 下一步
  const handleNext = async () => {
    try {
      // 验证当前步骤表单
      if (currentStep === 0 && basicFormRef.current) {
        // 验证基本信息
        await basicFormRef.current.validateFields();
      } else if (currentStep === 1 && supplierFormRef.current) {
        // 验证供应商选择
        await supplierFormRef.current.validateFields();
      } else if (currentStep === 2 && evaluatorFormRef.current) {
        // 验证评价人员选择
        await evaluatorFormRef.current.validateFields();
      } else if (currentStep === 3 && divisionFormRef.current) {
        // 验证评价分工
        const result = divisionFormRef.current.validate();
        if (!result.valid) {
          message.error(result.message);
          return;
        }
      }

      // 验证通过，进入下一步
      setCurrentStep(currentStep + 1);
    } catch (errorInfo: any) {
      // 表单验证失败
      console.log('表单验证失败:', errorInfo);
      if (typeof errorInfo === 'string') {
        message.error(errorInfo);
      } else if (errorInfo && errorInfo.errorFields) {
        message.error('请完成必填项');
      }
    }
  };

  // 上一步
  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  // 实际提交数据的函数
  const submitTaskData = async (taskStatus: TaskNotifyLowerUnits) => {
    setLoading(true);
    try {
      // 构建提交数据，确保必填字段有值
      const submitData = {
        evaluateTheme: formData.evaluateTheme || '', // 评价主题
        startTime: formData.startTime || '', // 开始时间
        endTime: formData.endTime || '', // 结束时间
        templateId: formData.templateId || '', // 模板ID
        categoryLimitation: formData.categoryLimitation || '0', // 品类限制
        evaluateYear: formData.evaluateYear || '', // 评价年份
        categoryId: formData.categoryId || '', // 品类ID
        taskStatus: taskStatus, // 任务状态，根据用户的选择决定

        // 供应商ID列表，包含评价人员ID
        supplierIds:
          formData.selectedSuppliers?.map((supplier: any) => {
            // 从供应商的evaluators中提取用户ID
            const userIds = supplier.evaluators?.map((evaluator: any) => evaluator.id) || [];
            return {
              id: supplier.id,
              userIds,
            };
          }) || [],

        // 评价指标列表
        indicatorList:
          formData.indicatorList?.map((item: any) => ({
            userId: item.userId,
            // 评价类型：如果用户关联了指标则为1(按指标)，否则为0(按评价单)
            type: item.indicatorIds && item.indicatorIds.length > 0 ? 1 : 0,
            indicatorIds: item.indicatorIds || [],
          })) || [],

        // 部门权重列表，过滤掉权重为0的
        taskDeptWeightList:
          formData.taskDeptWeightList?.filter((item: any) => {
            return item.weightValue && item.weightValue !== '0';
          }) || [],
      };

      let response;

      if (isEditMode) {
        // 编辑模式，添加ID字段
        const updateData = {
          ...submitData,
          id: taskId,
        };
        response = await updateTask(updateData);
      } else {
        // 新增模式
        response = await addTask(submitData);
      }

      if (response.success) {
        message.success(isEditMode ? '任务更新成功' : '任务创建成功');
        // 成功后直接返回列表页面
        history.push('/supplier/supplierTaskManage');
      } else {
        message.error(response.message || '提交失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    // 验证评价分工
    if (divisionFormRef.current) {
      const result = divisionFormRef.current.validate();
      if (!result.valid) {
        message.error(result.message);
        return;
      }
    }

    // 显示确认对话框
    setConfirmModalVisible(true);
  };

  // 处理确认对话框的取消
  const handleConfirmCancel = () => {
    setConfirmModalVisible(false);
  };

  // 处理确认对话框的"是"选项
  const handleConfirmYes = () => {
    submitTaskData(TaskNotifyLowerUnits.YES); // 未开始状态，需要下级单位完善
    setConfirmModalVisible(false);
  };

  // 处理确认对话框的"否"选项
  const handleConfirmNo = () => {
    submitTaskData(TaskNotifyLowerUnits.NO); // 进行中状态，不需要下级单位完善
    setConfirmModalVisible(false);
  };

  return (
    <div className="common-container">
      <Card bordered={false} loading={detailLoading}>
        <div className="page-header">
          <h2>{isEditMode ? '修改评价任务' : '新增评价任务'}</h2>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>

        <Row gutter={24} className={styles.stepsLayout}>
          <Col span={6} className={styles.stepsLeft}>
            <Steps direction="vertical" current={currentStep} className={styles.verticalSteps}>
              {steps.map((item) => (
                <Step key={item.title} title={item.title} description={item.description} />
              ))}
            </Steps>
          </Col>
          <Col span={18} className={styles.stepsRight}>
            <div className={styles.stepsContent}>{steps[currentStep].content}</div>

            <div className={styles.stepsAction}>
              <Space>
                {currentStep > 0 && <Button onClick={handlePrev}>上一步</Button>}
                {currentStep < steps.length - 1 && (
                  <Button type="primary" onClick={handleNext}>
                    下一步
                  </Button>
                )}
                {currentStep === steps.length - 1 && (
                  <Button
                    type="primary"
                    loading={loading}
                    icon={<SaveOutlined />}
                    onClick={handleSubmit}
                  >
                    {isEditMode ? '保存' : '提交'}
                  </Button>
                )}
              </Space>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 确认对话框 */}
      <Modal
        title="提交确认"
        visible={confirmModalVisible}
        onCancel={handleConfirmCancel}
        footer={null}
      >
        <p>是否提示给下级单位继续完善评价人及评价分工？</p>
        <div style={{ textAlign: 'right', marginTop: 24 }}>
          <Space>
            <Button type="primary" onClick={handleConfirmYes}>
              是
            </Button>
            <Button onClick={handleConfirmNo}>否</Button>
            <Button onClick={handleConfirmCancel}>取消</Button>
          </Space>
        </div>
      </Modal>
    </div>
  );
};

export default SupplierTaskManageAdd;
