import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Form, Input, Modal, Table } from "antd";
import { useEffect, useState } from "react";
import { NS_EQUIP_INFO } from "~/enumerate/namespace";

function OrgEquipmentSelectModalInner(props) {
  const { open, onCancel, onConfirm, existingIds = [] } = props;
  const [searchForm] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });

  const getData = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const values = searchForm.getFieldsValue();
      const res = await props.equipInfoList({
        current: page,
        size: pageSize,
        deviceName: values.deviceName || undefined,
      });
      if (res?.success !== false) {
        setDataSource(res?.data || []);
        setPagination((prev) => ({ ...prev, current: page, pageSize, total: res?.total || 0 }));
      }
    } catch (err) {
      console.warn("[OrgEquipmentSelectModal] list failed:", err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSearch = () => {
    getData(1, pagination.pageSize);
  };

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

  return (
    <Modal
      open={open}
      title="添加备案装备"
      width={800}
      destroyOnHidden
      onCancel={onCancel}
      onOk={handleOk}
      okText="确认添加"
    >
      <Form form={searchForm} layout="inline" style={{ marginBottom: 16 }}>
        <Form.Item name="deviceName">
          <Input placeholder="关键字搜索" allowClear />
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleSearch}>搜索</Button>
          <Button style={{ marginLeft: 8 }} onClick={() => { searchForm.resetFields(); getData(); }}>重置</Button>
        </Form.Item>
      </Form>
      <Table
        rowKey="id"
        loading={loading}
        dataSource={dataSource}
        scroll={ { y: 400 }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
          getCheckboxProps: (record) => ({
            disabled: existingIds.includes(String(record.id)),
          }),
        }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: (t) => `共 ${t} 条`,
          onChange: (page, pageSize) => getData(page, pageSize),
        }}
        columns={[
          { title: "装备名称", dataIndex: "deviceName" },
          { title: "规格型号", dataIndex: "deviceModel" },
          { title: "生产厂家", dataIndex: "manufacturer" },
        ]}
      />
    </Modal>
  );
}

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