import React, { forwardRef, useImperativeHandle } from 'react';
import { Card, Form } from 'antd';
import styles from '../supplierTaskManageAdd.less';
import SupplierSelector from '@/components/SupplierSelector';

interface SupplierSelectStepProps {
  formData: any;                    // 从父组件传递的表单数据
  onFormDataChange: (data: any) => void;  // 表单数据变更的回调函数
}

interface SupplierItem {
  id: string;                       // 供应商ID
  name: string;                     // 供应商名称
  supplierType: string;             // 供应商类型
  [key: string]: any;               // 其他可能的字段
}

const SupplierSelectStep = forwardRef<any, SupplierSelectStepProps>(({ formData, onFormDataChange }, ref) => {
  // 暴露表单方法给父组件
  useImperativeHandle(ref, () => ({
    validateFields: () => {
      // 这里可以添加自定义验证逻辑
      return Promise.resolve();
    },
    getFieldsValue: () => {
      return {
        selectedSuppliers: formData.selectedSuppliers || [],
        supplierIds: (formData.selectedSuppliers || []).map((supplier: SupplierItem) => ({ id: supplier.id }))
      };
    },
    setFieldsValue: (values: any) => {
      if (values.selectedSuppliers) {
        onFormDataChange({
          ...formData,
          selectedSuppliers: values.selectedSuppliers
        });
      }
    },
  }));

  // 处理供应商选择
  const handleSupplierSelect = (suppliers: SupplierItem[]) => {

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


    onFormDataChange({
      ...formData,
      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={formData.selectedSuppliers || []}
        />
      </Card>
    </div>
  );
});

export default SupplierSelectStep;
