import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Table, Radio, Button, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';

// 评审人数据结构
interface Reviewer {
  id: string;
  name: string;
  userId: string;
  deptId: string;
  isLeader: number;
}
interface ReviewerSelectorData {
  selected: Reviewer[];
  leader: Reviewer | null;
}

interface ReviewerSelectorProps {
  visible: boolean;
  onCancel: () => void;
  onSelect?: (selected: ReviewerSelectorData) => void;
}

// 模拟分页接口
const fetchReviewers = async ({
  pageNum,
  pageSize,
}: {
  pageNum: number;
  pageSize: number;
}): Promise<{ list: Reviewer[]; total: number }> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const all: Reviewer[] = Array.from({ length: 36 }, (_, i) => ({
        id: `u-${i + 1}`,
        name: `评审人${i + 1}`,
        userId: `E000${i + 1}`,
        deptId: `部门${(i % 3) + 1}`,
        isLeader: 0,
      }));
      resolve({
        list: all.slice((pageNum - 1) * pageSize, pageNum * pageSize),
        total: all.length,
      });
    }, 300);
  });
};

const ReviewerSelector: React.FC<ReviewerSelectorProps> = ({
  visible,
  onCancel,
  onSelect,
}) => {
  // 分页
  const [page, setPage] = useState<number>(1);
  const [pageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);

  // 数据
  const [data, setData] = useState<Reviewer[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  // 已选评审人 & 组长
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [leader, setLeader] = useState<string>('');

  // 加载数据
  useEffect(() => {
    if (!visible) return;
    setLoading(true);
    fetchReviewers({ pageNum: page, pageSize })
      .then((res) => {
        setData(res.list);
        setTotal(res.total);
      })
      .finally(() => setLoading(false));
  }, [visible, page, pageSize]);

  // 当前已选项（全局选中的都能做组长）
  const selectedReviewerObjs = useMemo(
    () => data.filter((item) => selectedRowKeys.includes(item.userId)),
    [data, selectedRowKeys]
  );

  // 列
  const columns: ColumnsType<Reviewer> = [
    { title: '姓名', dataIndex: 'name' },
    { title: '工号', dataIndex: 'userId' },
    { title: '部门', dataIndex: 'deptId' },
    {
      title: '组长',
      render: (_: any, record: Reviewer) => (
        <Radio
          disabled={!selectedRowKeys.includes(record.userId)}
          checked={leader === record.userId}
          onChange={() => setLeader(record.userId)}
        />
      ),
    },
  ];

  // 提交校验
  const handleOk = () => {
    if (!selectedRowKeys.length) {
      message.warning('请先选择评审人员');
      return;
    }
    if (!leader) {
      message.warning('请指定组长');
      return;
    }
    // 组长和其他人员isLeader赋值
    const selected = data
      .filter((item) => selectedRowKeys.includes(item.userId))
      .map((item) => ({
        ...item,
        isLeader: item.userId === leader ? 1 : 0,
      }));

    // 完整数据传回
    onSelect?.({
      selected,
      leader: selected.find((item) => item.isLeader === 1) ?? null,
    });
    onCancel();
  };

  return (
    <Modal
      title="选择评审人员"
      visible={visible}
      onCancel={onCancel}
      footer={null}
      width="70%"
      destroyOnClose
    >
      <Table<Reviewer>
        rowSelection={{
          type: 'checkbox',
          selectedRowKeys,
          onChange: (keys) => {
            setSelectedRowKeys(keys);
            // 如果组长不在新选中里，清掉
            if (!keys.includes(leader)) setLeader('');
          },
          getCheckboxProps: (record) => ({
            // 可根据需要禁用某些行
            // disabled: record.disabled,
          }),
        }}
        columns={columns}
        dataSource={data}
        rowKey="userId"
        loading={loading}
        pagination={{
          current: page,
          pageSize,
          total,
          showSizeChanger: false,
          onChange: (p) => setPage(p),
        }}
      />
      <div style={{ textAlign: 'right', marginTop: 16 }}>
        <Button style={{ marginRight: 8 }} onClick={onCancel}>
          取消
        </Button>
        <Button type="primary" onClick={handleOk}>
          确认
        </Button>
      </div>
    </Modal>
  );
};

export default ReviewerSelector;
