import React, { useEffect, useState } from 'react';
import { Modal, Button, List, message } from 'antd';
import EvaluateTaskPersonnelSelector from '@/components/EvaluateTaskPersonnelSelector/EvaluateTaskPersonnelSelector';
import { ModalMode } from '@/servers/types/evaluator';
import type { PersonnelItem, SupplierItem } from '@/servers/types/evaluator';

interface SupplierEvaluatorModalProps {
  visible: boolean;               // 控制弹窗显示/隐藏
  onCancel: () => void;           // 取消按钮回调函数
  onSelect: (personnel: PersonnelItem[]) => void;  // 选择人员后的回调函数
  currentSupplier: SupplierItem | null;           // 当前操作的供应商对象
  mode: ModalMode;                // 弹窗模式：SELECT(选择) 或 VIEW(查看)
  filter?: boolean;                // 是否过滤评价人员
  filterUserIds?: string[];         // 过滤评价人员ID列表
}

const SupplierEvaluatorModal: React.FC<SupplierEvaluatorModalProps> = ({
  visible,
  onCancel,
  onSelect,
  currentSupplier,
  mode,
  filter,
  filterUserIds,
}) => {
  // 本地保存当前选中的人员，确保在弹窗打开/关闭时能正确处理数据
  const [localSelectedPersonnel, setLocalSelectedPersonnel] = useState<PersonnelItem[]>([]);

  // 当currentSupplier变化时，更新本地的选中人员
  useEffect(() => {
    if (currentSupplier && currentSupplier.evaluators) {
      setLocalSelectedPersonnel(currentSupplier.evaluators);
    } else {
      setLocalSelectedPersonnel([]);
    }
  }, [currentSupplier]);

  // 处理选择人员的回调
  const handleSelect = (personnel: PersonnelItem[]) => {
    if (personnel.length === 0) {
      message.warning('请至少选择一名评价人员');
      return;
    }
    setLocalSelectedPersonnel(personnel);
    onSelect(personnel);
  };

  // 渲染评价人员列表（用于查看模式）
  const renderEvaluatorList = () => {

    if (!currentSupplier) {
      return <div style={{ textAlign: 'center', padding: '20px 0' }}>无供应商数据</div>;
    }

    if (!currentSupplier.evaluators || currentSupplier.evaluators.length === 0) {
      return (
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          当前供应商暂无评价人员，请点击&quot;编辑人员&quot;按钮添加
        </div>
      );
    }

    return (
      <List
        itemLayout="horizontal"
        dataSource={currentSupplier.evaluators}
        renderItem={(item: PersonnelItem) => (
          <List.Item>
            <List.Item.Meta
              title={item.name}
              description={`${item.userDept || '未知部门'}`}
            />
          </List.Item>
        )}
      />
    );
  };

  return (
    <Modal
      title={`${mode === ModalMode.SELECT ? '选择' : '查看'}评价人员 - ${
        currentSupplier?.supplierName || ''
      }`}
      visible={visible}
      onCancel={onCancel}
      footer={
        mode === ModalMode.VIEW
          ? [
              <Button key="close" onClick={onCancel}>
                关闭
              </Button>,
            ]
          : null
      }
      width={700}
      destroyOnClose={false}
    >
      {mode === ModalMode.SELECT ? (
        <EvaluateTaskPersonnelSelector
          key={`personnel-selector-${currentSupplier?.id || 'new'}-${visible}`}
          onSelect={handleSelect}
          filter={filter}
          filterUserIds={filterUserIds}
          selectedPersonnel={localSelectedPersonnel}
          onClose={onCancel}
        />
      ) : (
        renderEvaluatorList()
      )}
    </Modal>
  );
};

export default SupplierEvaluatorModal;
