import React, { useState, useRef } from 'react';
import { Card, Steps, Button, message, Space, Row, Col, Form } from 'antd';
import { history } from 'umi';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { addTask } from '@/servers/api/supplierEvaluate';
import BasicInfoStep from './components/BasicInfoStep';
import SupplierSelectStep from './components/SupplierSelectStep';
import EvaluatorSelectStep from './components/EvaluatorSelectStep';
import styles from './supplierTaskManageAdd.less';

const { Step } = Steps;

const SupplierTaskManageAdd: React.FC = () => {
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [formData, setFormData] = useState<Partial<SupplierEvaluate.TaskAddRequest>>({});

  // 创建表单引用
  const basicFormRef = useRef<any>(null);
  const supplierFormRef = useRef<any>(null);
  const evaluatorFormRef = useRef<any>(null);

  // 步骤配置
  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: <div>设置评价分工步骤（待实现）</div>,
    },
    {
      title: '创建成功',
      description: '评价任务创建成功',
      content: <div>创建成功步骤（待实现）</div>,
    },
  ];

  // 处理表单数据变更
  function handleFormDataChange(data: any) {
    setFormData({ ...formData, ...data });
  }

  // 处理返回
  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();
      }

      // 验证通过，进入下一步
      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 handleSubmit = async () => {
    setLoading(true);
    try {
      // 构建提交数据
      const submitData: SupplierEvaluate.TaskAddRequest = {
        evaluateTheme: formData.evaluateTheme || '',
        startTime: formData.startTime || '',
        endTime: formData.endTime || '',
        templateId: formData.templateId || '',
        categoryLimitation: formData.categoryLimitation || '0',
        evaluateYear: formData.evaluateYear || '',
        supplierIds: formData.supplierIds || [],
        indicatorList: formData.indicatorList || [],
        taskDeptWeightList: formData.taskDeptWeightList || [],
        weightStatus: formData.weightStatus || 0
      };

      // 调用API提交数据
      const response = await addTask(submitData);

      if (response.success) {
        message.success('任务创建成功');
        // 显示最后一步（创建成功）
        setCurrentStep(steps.length - 1);
      } else {
        message.error(response.message || '提交失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="common-container">
      <Card bordered={false}>
        <div className="page-header">
          <h2>新增评价任务</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 && currentStep < steps.length - 1 && (
                  <Button onClick={handlePrev}>上一步</Button>
                )}
                {currentStep < steps.length - 2 && (
                  <Button type="primary" onClick={handleNext}>
                    下一步
                  </Button>
                )}
                {currentStep === steps.length - 2 && (
                  <Button
                    type="primary"
                    loading={loading}
                    icon={<SaveOutlined />}
                    onClick={handleSubmit}
                  >
                    提交
                  </Button>
                )}
                {currentStep === steps.length - 1 && (
                  <Button type="primary" onClick={handleBack}>
                    完成
                  </Button>
                )}
              </Space>
            </div>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default SupplierTaskManageAdd;
