import React, { forwardRef, useImperativeHandle, useEffect, useState } from 'react';
import { Card } from 'antd';
import styles from '../supplierTaskManageAdd.less';
import SupplierSelector from '@/components/SupplierSelector';
import type { SupplierItem } from '@/servers/dao/supplierEvaluateTask';
import type { Dispatch } from 'umi';
import { connect } from 'umi';
import type { SupplierTaskModelState } from '@/models/supplierTaskManage';

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

// 定义组件，使用 innerRef 代替直接的 ref
const SupplierSelectStepComponent = (props: SupplierSelectStepProps) => {
  const { supplierTaskManage, dispatch, innerRef } = props;

  // 从model获取数据
  const { taskFormData } = supplierTaskManage;

  // 内部状态，避免直接操作formData导致循环更新
  const [selectedSuppliers, setSelectedSuppliers] = useState<SupplierItem[]>([]);

  // 当taskFormData.selectedSuppliers更新时，同步到本地状态
  useEffect(() => {
    if (taskFormData.selectedSuppliers && taskFormData.selectedSuppliers.length > 0) {
      setSelectedSuppliers(taskFormData.selectedSuppliers);
    }
  }, [taskFormData.selectedSuppliers]); // 只在表单ID变化时更新（编辑模式加载时）

  // 暴露表单方法给父组件，使用 innerRef
  useImperativeHandle(innerRef, () => ({
    validateFields: () => {
      // 这里可以添加自定义验证逻辑
      return Promise.resolve();
    },
    // 删除不必要的方法，因为现在使用Dva管理数据
  }));

  // 处理供应商选择
  const handleSupplierSelect = (suppliers: SupplierItem[]) => {
    // 确保每个供应商都有evaluators字段
    const suppliersWithEvaluators = suppliers.map(supplier => ({
      ...supplier,
      evaluators: supplier.evaluators || [],  // 确保evaluators字段存在，即使是空数组
      evaluatorCount: supplier.evaluators?.length || 0  // 计算评价人员数量
    }));

    // 更新本地状态
    setSelectedSuppliers(suppliersWithEvaluators);

    // 通过dispatch更新model数据
    dispatch({
      type: 'supplierTaskManage/updateFormData',
      payload: {
        selectedSuppliers: suppliersWithEvaluators,
        supplierIds: suppliersWithEvaluators.map(supplier => ({ id: supplier.id }))
      }
    });
  };

  return (
    <div className={styles.supplierSelectStep}>
      <Card title="供应商选择" bordered={false} className="inner-card">
        <SupplierSelector
          onSelect={handleSupplierSelect}
          selectedSuppliers={selectedSuppliers}
        />
      </Card>
    </div>
  );
};

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

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

export default SupplierSelectStep;
