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

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

  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={personnelList}
        rowSelection={
          !disabled
            ? {
                selectedRowKeys,
                onChange: setSelectedRowKeys,
              }
            : undefined
        }
        columns={[
          { title: "序号", width: 60, render: (_, __, index) => index + 1 },
          { title: "姓名", dataIndex: "personName" },
          managementFlag&&{
            title: "职务",
            width: 120,
            render: (_, record) => {
              const roles = [];
              if (record.technicalDirectorFlag === true) roles.push("技术负责人");
              if (record.processControlLeaderFlag === true) roles.push("过程控制负责人");
              return roles.length ? roles.join("、") : "-";
            },
          },
          !managementFlag&&{
            title: "职称",
            dataIndex: "titleCodeArr",
            width: 100,
            render: (list) => {
              if (!Array.isArray(list) || !list.length) return "-";
              return list
                .map(
                  (item) => TITLE_LEVEL_MAP[item.titleCode] || item.titleCode,
                )
                .join("、");
            },
          },
          {
            title: "专业能力",
            dataIndex: "capabilityAssessment",
            render: (list) => {
              if (!Array.isArray(list) || !list.length) return "-";
              return list
                .map(
                  (item) =>
                    CAPABILITY_MAP[item.professionalCapabilityCode] ||
                    item.professionalCapabilityCode,
                )
                .join("、");
            },
          },
          {
            title: "职业资格等级及证书编号",
            dataIndex: "personnelCertFilingPageCOList",
            width: 200,
            render: (_, record) => {
              const cert = (record.personnelCertFilingPageCOList || []).find(
                (item) => item.certTypeCode === "evaluator",
              );
              if (!cert) return "否";
              const levelMap = CERT_LEVEL_LABEL_BY_TYPE.evaluator || {};
              return (
                <div>
                  <div>{levelMap[cert.certLevel] || cert.certLevel || "-"}</div>
                  <div style={{ color: "rgba(0,0,0,0.45)" }}>
                    {cert.certNo || "-"}
                  </div>
                </div>
              );
            },
          },
          {
            title: "是否具有注册安全工程师资格",
            width: 200,
            render: (_, record) => {
              const cert = (record.personnelCertFilingPageCOList || []).find(
                (item) => item.certTypeCode === "registered_safety_engineer",
              );
              if (!cert) return "否";
              const levelMap =
                CERT_LEVEL_LABEL_BY_TYPE.registered_safety_engineer || {};
              return (
                <div>
                  <div>{levelMap[cert.certLevel] || cert.certLevel || "-"}</div>
                  <div style={{ color: "rgba(0,0,0,0.45)" }}>
                    {cert.certNo || "-"}
                  </div>
                </div>
              );
            },
          },
          {
            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>
            ),
          },
        ].filter(Boolean)}
      />
      <OrgPersonnelSelectModal
        open={selectOpen}
        existingIds={existingIds}
        managementFlag={managementFlag}
        onCancel={() => setSelectOpen(false)}
        onConfirm={(ids, rows) => {
          onAdd?.(ids, rows);
          setSelectOpen(false);
        }}
      />
      <StaffViewModal
        open={!!viewId}
        currentId={viewId}

        onCancel={() => setViewId("")}
      />
    </>
  );
};

export default PersonnelStep;
