import { Button, Form, Input, Modal, Table } from "antd";
import { useEffect, useState } from "react";
import { apiGet } from "~/utils/enterpriseInfo/http";
import { CAPABILITY_MAP, GENDER_MAP } from "~/enumerate/constant";
import StaffViewModal from "~/components/StaffViewModal";

function calcAge(birthDate) {
  if (!birthDate) return "-";
  const birth = new Date(birthDate);
  if (isNaN(birth.getTime())) return "-";
  const now = new Date();
  let age = now.getFullYear() - birth.getFullYear();
  const m = now.getMonth() - birth.getMonth();
  if (m < 0 || (m === 0 && now.getDate() < birth.getDate())) age--;
  return age >= 0 ? age : "-";
}

export default function OrgPersonnelSelectModal(props) {
  const { open, onCancel, onConfirm, existingIds = [] } = props;
  const [searchForm] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = 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 apiGet("/safetyEval/org-personnel/filing/page", {
        current: page,
        size: pageSize,
        personName: values.personName || undefined,
      });
      if (res?.success !== false) {
        setDataSource((res?.data || []).map((item) => ({ ...item, age: calcAge(item.birthDate) })));
        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([]);
      setSelectedRows([]);
      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 = selectedRows.filter((row) => ids.includes(row.id));
    onConfirm?.(ids, rows);
  };

  return (
    <>
      <Modal
        open={open}
        title="添加备案人员"
        width={900}
        destroyOnHidden
        onCancel={onCancel}
        onOk={handleOk}
        okText="确认添加"
      >
        <Form form={searchForm} layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item name="personName">
            <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,
            preserveSelectedRowKeys: true,
            onChange: (keys, rows) => {
              setSelectedRowKeys(keys);
              setSelectedRows(rows);
            },
            getCheckboxProps: (record) => ({
              disabled: existingIds.includes(String(record.id)),
            }),
          }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showTotal: (t) => `共 ${t} 条`,
            onChange: (page, pageSize) => getData(page, pageSize),
          }}
          scroll={{ x: 1100, y: 400 }}
          columns={[
            { title: "人员姓名", dataIndex: "personName", ellipsis: true, width: 100 },
            { title: "部门", dataIndex: "deptName", ellipsis: true, width: 150 },
            { title: "岗位", dataIndex: "positionName", ellipsis: true, width: 120 },
            { title: "性别", dataIndex: "genderCode", width: 70, render: (v) => GENDER_MAP[v] || "-" },
            { title: "年龄", dataIndex: "age", width: 70 },
            { title: "注册安全工程师", dataIndex: "registerEngineerFlag", width: 130, render: (v) => v === 1 ? "是" : "否" },
            { title: "评价师", dataIndex: "evaluatorCertNo", width: 80, render: (v) => v ? "是" : "否" },
            {
              title: "能力",
              render: (_, record) => {
                const codes = record.professionalCapabilityCodeList || [];
                return codes.length
                  ? codes.map((code) => CAPABILITY_MAP[code] || code).join("、")
                  : "-";
              },
            },
            {
              title: "操作",
              width: 80,
              fixed: "right",
              render: (_, record) => (
                <Button type="link" size="small" onClick={() => setViewId(record.id)}>查看</Button>
              ),
            },
          ]}
        />
      </Modal>
      <StaffViewModal
        open={!!viewId}
        currentId={viewId}
        onCancel={() => setViewId("")}
      />
    </>
  );
}
