import React, { useState, useEffect, useCallback, forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select, DatePicker, Row, Col, Card, Radio } from 'antd';
import moment from 'moment';
import { getAllTemplates } from '@/servers/api/supplierEvaluate';
import CategorySelector from '@/components/CategorySelector';
import styles from '../supplierTaskManageAdd.less';
import { CategoryLimitationType } from '@/dicts/supplierTemplateDict';
import type { Dispatch } from 'umi';
import { connect } from 'umi';
import type { SupplierTaskModelState } from '@/models/supplierTaskManage';

const { Option } = Select;

interface TemplateItem {
  id: string;
  templateName: string;
  categoryLimitation?: string;
}

interface BasicInfoStepProps {
  supplierTaskManage: SupplierTaskModelState;
  dispatch: Dispatch;
  innerRef?: any; // 使用 innerRef 作为属性名
}

// 定义组件，使用 innerRef 代替直接的 ref
const BasicInfoStepComponent = (props: BasicInfoStepProps) => {
  const { supplierTaskManage, dispatch, innerRef } = props;
  const [form] = Form.useForm();
  const [templates, setTemplates] = useState<TemplateItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  // 从props中获取状态
  const { taskFormData } = supplierTaskManage;

  // 暴露表单方法给父组件，使用 innerRef
  useImperativeHandle(innerRef, () => ({
    validateFields: () => form.validateFields(),
    // 删除不必要的方法，因为现在使用Dva管理数据
  }));

  // 获取模板列表
  const fetchTemplates = async () => {
    setLoading(true);
    try {
      const response = await getAllTemplates();
      if (response.success && response.data) {
        setTemplates(response.data);
      }
    } catch (error) {
      console.error('获取模板列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取评价模板和初始化表单数据
  useEffect(() => {
    fetchTemplates();

    // 初始化表单数据
    if (taskFormData) {
      form.setFieldsValue(taskFormData);
    }
  }, []);

  // 当taskFormData变化时更新表单值
  useEffect(() => {
    if (taskFormData) {
      // 处理日期字段，确保正确设置
      const formValues = {
        ...taskFormData,
        startTime: taskFormData.startTime ? moment(taskFormData.startTime) : undefined,
        endTime: taskFormData.endTime ? moment(taskFormData.endTime) : undefined,
      };
      form.setFieldsValue(formValues);
    }
  }, [taskFormData, form]);

  // 表单值变化时触发
  const handleValuesChange = (changedValues: any, allValues: any) => {
    // 使用dispatch更新model中的数据
    dispatch({
      type: 'supplierTaskManage/updateFormData',
      payload: allValues,
    });
  };

  // 年度选项生成
  const yearOptions = useCallback(() => {
    const currentYear = new Date().getFullYear();
    return Array.from({ length: 11 }, (_, i) => currentYear - 5 + i).map((year) => (
      <Option key={year} value={year.toString()}>
        {year}
      </Option>
    ));
  }, []);

  // 判断是否显示品类选择器
  const shouldShowCategorySelector = useCallback(() => {
    const categoryLimitation = taskFormData.categoryLimitation;
    return categoryLimitation === CategoryLimitationType.LIMITED;
  }, [taskFormData]);


  return (
    <div className={styles.basicInfoStep}>
      <Card title="基本信息" bordered={false} className="inner-card">
        <Form
          form={form}
          layout="vertical"
          onValuesChange={handleValuesChange}
          initialValues={{
            ...taskFormData,
            categoryLimitation: taskFormData.categoryLimitation || '0',
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="评价主题"
                name="evaluateTheme"
                rules={[{ required: true, message: '请输入评价主题' }]}
              >
                <Input placeholder="请输入" maxLength={50} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="评价年度"
                name="evaluateYear"
                rules={[{ required: true, message: '请选择评价年度' }]}
              >
                <Select placeholder="请选择年度" style={{ width: '100%' }}>
                  {yearOptions()}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="评价开始时间"
                name="startTime"
                rules={[{ required: true, message: '请选择评价开始时间' }]}
                getValueProps={(value) => ({
                  value: value ? moment(value) : undefined,
                })}
                normalize={(value) => value && value.format('YYYY-MM-DD')}
              >
                <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" placeholder="年/月/日" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="评价结束时间"
                name="endTime"
                rules={[{ required: true, message: '请选择评价结束时间' }]}
                getValueProps={(value) => ({
                  value: value ? moment(value) : undefined,
                })}
                normalize={(value) => value && value.format('YYYY-MM-DD')}
              >
                <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" placeholder="年/月/日" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="品类限制类型"
                name="categoryLimitation"
                rules={[{ required: true, message: '请选择品类限制类型' }]}
              >
                <Radio.Group>
                  <Radio value={CategoryLimitationType.UNIVERSAL}>通用不限品类</Radio>
                  <Radio value={CategoryLimitationType.LIMITED}>限制品类</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            {shouldShowCategorySelector() && (
              <Col span={12}>
                <Form.Item
                  label="选择品类"
                  name="categoryId"
                  rules={[{ required: true, message: '请选择品类' }]}
                >
                  <CategorySelector multiple={false} />
                </Form.Item>
              </Col>
            )}
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="选择模板"
                name="templateId"
                rules={[{ required: true, message: '请选择适用评价模板' }]}
              >
                <Select placeholder="请选择" style={{ width: '100%' }} allowClear loading={loading}>
                  {templates.map((template) => (
                    <Option key={template.id} value={template.id}>
                      {template.templateName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
    </div>
  );
};

// 连接 Dva model
const ConnectedComponent = connect(
  ({ supplierTaskManage }: { supplierTaskManage: SupplierTaskModelState }) => ({
    supplierTaskManage,
  })
)(BasicInfoStepComponent);

// 外层转发 ref 到 innerRef
const BasicInfoStep = forwardRef((props: any, ref) => (
  <ConnectedComponent {...props} innerRef={ref} />
));

export default BasicInfoStep;
