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

//selected 类型
interface Reviewer {
  userId: string;
  name: string;
  id: string;
  deptId: string;
}
// 传入的人接口
interface ReviewerSelectorData {
  selected: Reviewer[];
  leader: Reviewer | null;
}
//列表参数人类型
type ReviewerChecks = {
  [reviewerKey: string]: boolean;
};
//列表参数
type DivisionRow = {
  key: string;
  itemName: string;
  reviewerChecks: ReviewerChecks;
};
//列表头接口
interface ColumnsRow {
  itemName: string;
  reviewerChecks: { [userId: string]: boolean };
}
//主体
const DivisionModal: React.FC<{
  reviewerSelector: ReviewerSelectorData;
  visible: boolean;
  onCancel: () => void;
  onSelect?: (divisionData: any[]) => void;
}> = ({ visible, onCancel, onSelect, reviewerSelector }) => {

  // 过滤出组长
  const nonLeaderReviewers = useMemo(
    () => (reviewerSelector?.selected || []).filter(
      r => reviewerSelector.leader && r.id !== reviewerSelector.leader.id
    ), [reviewerSelector]
  );
  //列表数据渲染  -默认第一条
  const [data, setData] = useState<DivisionRow[]>([
    { key: '1', itemName: '合规检查', reviewerChecks: {} },
  ]);

  // 评审项 选择
  const handleReviewerCheck = (rowIndex: number, reviewerKey: string, checked: boolean) => {
    const newData = [...data];
    newData[rowIndex].reviewerChecks[reviewerKey] = checked;
    setData(newData);
  };
  //全部评审项 多选
  const handleReviewerCheckAllColumn = (reviewerKey: string, checked: boolean) => {
    const newData = data.map(row => ({
      ...row,
      reviewerChecks: {
        ...row.reviewerChecks,
        [reviewerKey]: checked,
      },
    }));
    setData(newData);
  };
  //列表头
  const columns: ColumnsType<ColumnsRow> = [
    {
      title: '评审项',
      dataIndex: 'itemName',
      fixed: 'left',
      width: 360,
      render: (text: string, record: any, index: number) => (
        <Input
          value={text}
          onChange={e => {
            const newData = [...data];
            newData[index].itemName = e.target.value;
            setData(newData);
          }}
        />
      ),
    },
    ...nonLeaderReviewers.map(r => ({
      title: (
        <Checkbox
          onChange={e => handleReviewerCheckAllColumn(r.userId, e.target.checked)}
          checked={data.every(row => row.reviewerChecks?.[r.userId])}
        >{r.name}</Checkbox>
      ),
      width: 140,
      dataIndex: r.userId,
      render: (val: any, record: any, rowIndex: number) => (
        <Checkbox
          checked={record.reviewerChecks?.[r.userId] || false}
          onChange={e => handleReviewerCheck(rowIndex, r.userId, e.target.checked)}
        />
      ),
    })),
    {
      title: '操作',
      fixed: 'right',
      width: '80px',
      render: (text: any, record: any, index: number) => (
        <Button
          danger
          disabled={data.length === 1}
          onClick={() => {
            const newData = data.filter((_, i) => i !== index);
            setData(newData);
          }}
        >删除</Button>
      ),
    },
  ];
  //增加行
  const addRow = () => {
    const newRow = { key: Date.now().toString(), itemName: '', reviewerChecks: {} };
    setData([...data, newRow]);
  };

  return (
    <Modal title="评审分工" visible={visible} onCancel={onCancel} footer={null} width="90%">
      <div style={{ margin: '0 0 24px' }}>
        <Button onClick={addRow}>新增行</Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="key"
        pagination={false}
        scroll={{ x: true }}
      />

      <div style={{ textAlign: 'right', marginTop: 16 }}>
        <Button style={{ marginRight: 8 }} onClick={onCancel}>取消</Button>
        <Button
          type="primary"
          onClick={() => {
            onSelect?.(data); // 回传分工数据
            onCancel();
          }}
        >
          确认
        </Button>
      </div>
    </Modal>
  );
};

export default DivisionModal;
