import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Form, Modal, 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_EQUIP_INFO } from "~/enumerate/namespace";
import { safeListRequest } from "~/utils";

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

  const { tableProps, getData } = useTable(safeListRequest(props.equipInfoList), {
    form: searchForm,
    transform: (formData) => ({ likeDeviceName: formData.deviceName }),
  });

  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: "deviceName", label: "装备名称", placeholder: "关键字搜索" }]}
        onFinish={getData}
      />
      <Table
        {...tableProps}
        rowKey="id"
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
          getCheckboxProps: (record) => ({
            disabled: existingIds.includes(String(record.id)),
          }),
        }}
        columns={[
          { title: "装备名称", dataIndex: "deviceName" },
          { title: "规格型号", dataIndex: "deviceModel" },
          { title: "生产厂家", dataIndex: "manufacturer" },
        ]}
      />
    </Modal>
  );
}

export default Connect([NS_EQUIP_INFO], true)(OrgEquipmentSelectModalInner);
