import { Button, Modal, Space, Table } from "antd";
import { useMemo, useState } from "react";
import { CAPABILITY_MAP, GENDER_MAP } from "~/enumerate/constant";
import StaffViewModal from "~/components/StaffViewModal";
import OrgPersonnelSelectModal from "./OrgPersonnelSelectModal";

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 : "-";
}

const PersonnelStep=({
  personnelList = [],
  disabled,
  onAdd,
  onRemove,
})=> {
  const [selectOpen, setSelectOpen] = useState(false);
  const [viewId, setViewId] = useState("");
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const tableData = useMemo(
    () => personnelList.map((item) => ({ ...item, age: item.age ?? calcAge(item.birthDate) })),
    [personnelList],
  );

  const existingIds = personnelList.map((item) => String(item.sourcePersonnelId || item.id || ""));

  const handleBatchRemove = () => {
    const records = selectedRowKeys
      .map((key) => personnelList.find(
        (item) => String(item.sourcePersonnelId || item.id) === key,
      ))
      .filter(Boolean);
    if (records.length > 0) {
      onRemove?.(records);
    }
    
  };

  return (
    <>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{ fontWeight: 600 }}>
          备案人员信息
          <span style={{ marginLeft: 8, color: "rgba(0,0,0,0.45)", fontWeight: 400 }}>
            当前 {personnelList.length} 人
          </span>
        </span>
        {!disabled && (
          <Space size="small">
            <Button type="primary" size="small" onClick={() => setSelectOpen(true)}>添加人员信息</Button>
            {selectedRowKeys.length > 0 && (
              <Button danger size="small" onClick={handleBatchRemove}>批量删除</Button>
            )}
          </Space>
        )}
      </div>
      <Table
        size="small"
        rowKey={(record) => String(record.sourcePersonnelId || record.id)}
        pagination={false}
        scroll={{ x: 1200, y: 400 }}
        dataSource={tableData}
        rowSelection={!disabled ? {
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        } : undefined}
        columns={[
          { title: "序号", width: 60, render: (_, __, index) => index + 1 },
          { title: "人员姓名", dataIndex: "personName" },
          { title: "部门", dataIndex: "deptName", ellipsis: true },
          { title: "岗位", dataIndex: "positionName", ellipsis: true },
          { title: "性别", dataIndex: "genderCode", width: 70, render: (v) => GENDER_MAP[v] || "-" },
          { title: "年龄", dataIndex: "age", width: 70 },
          { title: "注册安全工程师", dataIndex: "registerEngineerFlag", width: 120, 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: 140,
            fixed: "right",
            render: (_, record) => (
              <Space size="small">
                <Button
                  type="link"
                  size="small"
                  onClick={() => setViewId(record.sourcePersonnelId || record.id)}
                >
                  查看
                </Button>
                {!disabled && (
                  <Button type="link" size="small" danger onClick={() => onRemove?.(record)}>删除</Button>
                )}
              </Space>
            ),
          },
        ]}
      />
      <OrgPersonnelSelectModal
        open={selectOpen}
        existingIds={existingIds}
        onCancel={() => setSelectOpen(false)}
        onConfirm={(ids, rows) => {
          onAdd?.(ids, rows);
          setSelectOpen(false);
        }}
      />
      <StaffViewModal
        open={!!viewId}
        currentId={viewId}
  
        onCancel={() => setViewId("")}
      />
    </>
  );
}

export default PersonnelStep;
