import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Form, Input, Modal, Space, Table } from "antd";
import { useEffect, useState } from "react";
import Search from "zy-react-library/components/Search";
import useTable from "zy-react-library/hooks/useTable";
import { NS_STAFF_INFO } from "~/enumerate/namespace";
import { safeListRequest } from "~/utils";
import StaffViewModal from "~/pages/Container/EnterpriseInfo/PersonnelInfo/StaffViewModal";

function OrgPersonnelSelectModalInner(props) {
  const { open, onCancel, onConfirm, existingIds = [] } = props;
  const [searchForm] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [viewId, setViewId] = useState("");

  const { tableProps, getData } = useTable(safeListRequest(props.staffInfoList), {
    form: searchForm,
    transform: (formData) => ({ likeStaffName: formData.staffName }),
  });

  useEffect(() => {
    if (open) {
      setSelectedRowKeys([]);
      getData();
    }
  }, [open]);

  const handleOk = () => {
    const ids = selectedRowKeys.filter((id) => !existingIds.includes(String(id)));
    if (!ids.length) {
      Modal.warning({ title: "提示", content: "请选择至少一名未添加的人员" });
      return;
    }
    const rows = (tableProps.dataSource || []).filter((row) => ids.includes(row.id));
    onConfirm?.(ids, rows);
  };

  return (
    <>
      <Modal
        open={open}
        title="添加备案人员"
        width={800}
        destroyOnClose
        onCancel={onCancel}
        onOk={handleOk}
        okText="确认添加"
      >
        <Search
          form={searchForm}
          options={[{ name: "staffName", label: "人员姓名", placeholder: "关键字搜索" }]}
          onFinish={getData}
        />
        <Table
          {...tableProps}
          rowKey="id"
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            getCheckboxProps: (record) => ({
              disabled: existingIds.includes(String(record.id)),
            }),
          }}
          columns={[
            { title: "人员姓名", dataIndex: "staffName" },
            { title: "类型", dataIndex: "personType" },
            { title: "职务", dataIndex: "positionName" },
            { title: "职称", dataIndex: "titleName" },
            {
              title: "操作",
              width: 80,
              render: (_, record) => (
                <Button type="link" size="small" onClick={() => setViewId(record.id)}>查看</Button>
              ),
            },
          ]}
        />
      </Modal>
      <StaffViewModal
        open={!!viewId}
        currentId={viewId}
        requestDetails={props.staffInfoGet}
        onCancel={() => setViewId("")}
      />
    </>
  );
}

export default Connect([NS_STAFF_INFO], true)(OrgPersonnelSelectModalInner);
