import React, { forwardRef, useImperativeHandle, useEffect, useState } from 'react';
import { Card, Form } from 'antd';
import styles from '../supplierTaskManageAdd.less';
import SupplierSelector from '@/components/SupplierSelector';
import type { TaskAddRequest,SupplierItem } from '@/servers/types/supplierEvaluateTask';

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

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

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

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

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

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

    // 通知父组件
    onFormDataChange({
      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>
  );
});

export default SupplierSelectStep;
