import React, { useEffect } from 'react';
import { Table, Space, Button, Tag, Modal, Tooltip } from 'antd';
import type { SupplierItem } from '@/servers/types/evaluator';

interface SupplierTableProps {
  suppliers: SupplierItem[]; // 供应商数据列表
  selectedRowKeys: React.Key[]; // 选中的行keys
  onSelectChange: (selectedRowKeys: React.Key[]) => void; // 选择行变化的回调
  onViewEvaluators: (supplier: SupplierItem) => void; // 查看评价人员的回调
  onSelectEvaluators: (supplier: SupplierItem) => void; // 选择评价人员的回调
  onDeleteSupplier: (key: string) => void; // 删除供应商的回调
  mode?: string; // 模式
}

const SupplierTable: React.FC<SupplierTableProps> = ({
  suppliers,
  selectedRowKeys,
  onSelectChange,
  onViewEvaluators,
  onSelectEvaluators,
  onDeleteSupplier,
  mode,
}) => {
  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  // 删除确认对话框
  const showDeleteConfirm = (record: SupplierItem) => {
    Modal.confirm({
      title: '确定要删除此供应商吗？',
      content: `供应商: ${record.supplierName}${
        record.evaluatorCount > 0 ? `，将同时删除 ${record.evaluatorCount} 名关联的评价人员` : ''
      }`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => onDeleteSupplier(record.id),
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '供应商名称', // 列标题
      dataIndex: 'supplierName', // 数据字段名
      key: 'supplierName', // 列的唯一标识
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'socialCreditCode',
      key: 'socialCreditCode',
    },
    {
      title: '准入品类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      render: (categoryName: string) => (
        <Tooltip placement="topLeft" title={categoryName}>
          {categoryName || '-'}
        </Tooltip>
      ),
    },
    {
      title: '准入部门',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '评价人员数',
      align: 'center' as const, // 列对齐方式
      dataIndex: 'evaluatorCount', // 评价人员数量字段
      key: 'evaluatorCount',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: SupplierItem) => (
        <Space>
          <Button
            type="link"
            onClick={() => {
              onViewEvaluators(record);
            }}
          >
            查看
          </Button>
          <Button type="link" onClick={() => onSelectEvaluators(record)}>
            编辑人员
          </Button>
          {mode !== 'division' && (
            <>
              <Button type="link" onClick={() => showDeleteConfirm(record)}>
                删除
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Table
      rowSelection={mode === 'division' ? undefined : rowSelection} // 行选择配置
      columns={columns} // 列配置
      dataSource={suppliers} // 数据源
      pagination={false} // 分页配置，这里禁用了分页
      rowKey="id" // 行的唯一标识字段
    />
  );
};

export default SupplierTable;
