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

function OrgPersonnelSelectModalInner(props) {
  const { open, onCancel, onConfirm, existingIds = [] } = props;
  const [searchForm] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [viewId, setViewId] = 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.staffInfoList({
        current: page,
        size: pageSize,
        userName: values.staffName || undefined,
        employmentStatusCode: 1,
      });
      if (res?.success !== false) {
        setDataSource(res?.data || []);
        setPagination((prev) => ({ ...prev, current: page, pageSize, total: res?.total || 0 }));
      }
    } catch (err) {
      console.warn("[OrgPersonnelSelectModal] 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="staffName">
            <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}
          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),
          }}
          scroll={ { y: 400 }}
          columns={[
            { title: "人员姓名", dataIndex: "userName", ellipsis: true },
            { title: "类型", dataIndex: "personTypeName" },
           
            { title: "职称", dataIndex: "titleName", ellipsis: true, render: (_, record) => TITLE_LEVEL_MAP[record.titleCode] ?? (record.titleCode || "-") },
            {
              title: "操作",
              width: 80,
              render: (_, record) => (
                <Button type="link" size="small" onClick={() => setViewId(record.id)}>查看</Button>
              ),
            },
          ]}
        />
      </Modal>
      <StaffViewModal
        open={!!viewId}
        currentId={viewId}
       
        onCancel={() => setViewId("")}
      />
    </>
  );
}

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