import { Connect } from "@cqsjjb/jjb-dva-runtime";
import {
  Button,
  Cascader,
  Checkbox,
  DatePicker,
  DotLoading,
  Form,
  Image,
  ImageUploader,
  Input,
  Mask,
  Picker,
  Popup,
  TextArea,
  Toast,
} from "antd-mobile";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { UPLOAD_FILE_TYPE_ENUM } from "zy-react-library/enum/uploadFile/gwj";
import useDictionary from "zy-react-library/hooks/useDictionary";
import useUploadFile from "zy-react-library/hooks/useUploadFile";
import { ID_NUMBER, LICENSE_PLATE_NUMBER, PHONE } from "zy-react-library/regular";
import { getLabelName, validatorEndTime, validatorTimeGECurrentDay } from "zy-react-library/utils";
import SignatureH5 from "~/components/SignatureH5";
import {
  NS_APPROVER_USER,
  NS_ENCLOSED_AREA,
  NS_FIRST_LEVEL_DOOR_INFO,
  NS_MOBILE,
  NS_VEHICLE_APPLY,
} from "~/enumerate/namespace";
import "../../../index.less";

export const ACCESS_TYPE_ENUM = [
  { label: "车辆", value: "CAR_APPLY" },
  { label: "人员", value: "PERSON_APPLY" },
];

export const APPLICATION_GATE_PERSON_TYPE_ENUM = [
  { label: "一级口门", value: "ONE_LEVEL_PERSON_APPLY" },
  { label: "封闭区域口门", value: "TWO_LEVEL_PERSON_APPLY" },
];
export const APPLICATION_GATE_CAR_TYPE_ENUM = [
  { label: "一级口门", value: "ONE_LEVEL_CAR_APPLY" },
  { label: "封闭区域口门", value: "TWO_LEVEL_CAR_APPLY" },
];

function Apply(props) {
  const [primeportAreaList, setPrimeportAreaList] = useState([]);
  const [vehicleTypeList, setVehicleTypeList] = useState([]);
  const [licensePlateTypeList, setLicensePlateTypeList] = useState([]);
  const [firstLevelDoorInfoListAll, setFirstLevelDoorInfoListAll] = useState([]);
  const [twoLevelDoorInfoListAll, setTwoLevelDoorInfoListAll] = useState([]);
  const [approvalUserListAll, setApprovalUserListAll] = useState([]);
  const [departmentList, setDepartmentList] = useState([]);
  const [enclosedAreaList, setEnclosedAreaList] = useState([]);
  const [noticePopupVisible, setNoticePopupVisible] = useState(false);

  const [signatureUrl, setSignatureUrl] = useState("");

  const checkboxRef = useRef(null);

  const [form] = Form.useForm();
  const tmpApplyType = Form.useWatch("tmpApplyType", form);
  const tmpMkmjType = Form.useWatch("tmpMkmjType", form);
  const { getDictionary } = useDictionary();
  const { loading: uploadFileLoading, uploadFile } = useUploadFile();
  const [mkmjType,setMkmjType]=useState([]);

  const transformTreeList = (list, nameKey, idKey) => {
    return list.map(item => ({
      label: item[nameKey],
      value: item[idKey],
      children: item.children ? transformTreeList(item.children ,"closedAreaName", "id") : undefined,
    }));
  };

  const getData = async () => {
    const primeportAreaData = await getDictionary({ dictValue: "HG_AUTH_AREA" });
    setPrimeportAreaList(primeportAreaData);
    const vehicleTypeData = await getDictionary({ dictValue: "VEHICLE_TYPE" });
    setVehicleTypeList(vehicleTypeData);
    const licensePlateTypeData = await getDictionary({ dictValue: "LICENSE_PLATE_TYPE" });
    setLicensePlateTypeList(licensePlateTypeData);
    const { data: departmentList } = await props["getDepartmentListTree"]({ enterpriseType: [2] });
    setDepartmentList(departmentList);
  };

  const getApprovalUserList = async (corpId) => {
    const { data } = await props["approvalUserListAll"]({ temporaryPermissionFlag: 1, corpId });
    setApprovalUserListAll(data);
  };

  const getFirstLevelDoorInfoListAll = async (gateLevelAuthArea) => {
    const { data } = await props["firstLevelDoorInfoListAll"]({ mkmjLevel: 1, hgAuthArea: gateLevelAuthArea,mkmjType:mkmjType === "CAR_APPLY" ?"HGKM_MKMJ_CKM":"HGKM_MKMJ_CKM_R" });
    setFirstLevelDoorInfoListAll(data);
  };

  const getTwoLevelDoorInfoListAll = async (gateLevelAuthArea) => {
    const { data } = await props["firstLevelDoorInfoListAll"]({ mkmjLevel: 2, hgAuthArea: gateLevelAuthArea,mkmjType:mkmjType === "CAR_APPLY" ?"HGKM_MKMJ_CKM":"HGKM_MKMJ_CKM_R" });
    setTwoLevelDoorInfoListAll(data);
  };

  const getEnclosedAreaList = async (jurisdictionalCorpId) => {
    const { data } = await props["enclosedAreaDetailListTree"]({ jurisdictionalCorpId });
    const transformedEnclosedAreaList = transformTreeList(data, "closedAreaName", "id");
    setEnclosedAreaList(transformedEnclosedAreaList);

  };

  useEffect(() => {
    getData();
  }, []);

  const getTreeLabelName = (treeList, value, idKey = "value", nameKey = "label") => {
    if (!treeList || !Array.isArray(treeList) || !value) {
      return "";
    }

    let result = "";

    const findNodeInTree = (tree, targetValue) => {
      for (const node of tree) {
        if (node[idKey] === targetValue) {
          result = node[nameKey];
          return true;
        }
        if (node.children && node.children.length > 0) {
          const found = findNodeInTree(node.children, targetValue);
          if (found) {
            return true;
          }
        }
      }
      return false;
    };

    findNodeInTree(treeList, value);
    return result;
  };

  const onFinish = async (values) => {
    if (!values.safetyNoticeAgreed || !values.signature) {
      Toast.show({
        icon: "fail",
        content: "请勾选《安全进港须知》并签字",
      });
      return;
    }
    if (values.tmpApplyType === "CAR_APPLY" && values.vehicleLicensePhoto.length !== 2) {
      Toast.show({
        icon: "fail",
        content: "请上传两张行驶证照片",
      });
      return;
    }
    const tmpMkmjType = values.tmpMkmjType;
    const informSignType = {
      ONE_LEVEL_PERSON_APPLY: 611,
      TWO_LEVEL_PERSON_APPLY: 609,
      ONE_LEVEL_CAR_APPLY: 606,
      TWO_LEVEL_CAR_APPLY: 610,
    }[tmpMkmjType];
    const { id: drivingLicenseId } = await uploadFile({
      single: false,
      files: (values.vehicleLicensePhoto || []).map(item => ({ ...item, originFileObj: item.file })),
      params: { type: UPLOAD_FILE_TYPE_ENUM[601], foreignKey: "" },
    });
    const { id: attachmentId } = await uploadFile({
      single: false,
      files: (values.vehiclePhoto || []).map(item => ({ ...item, originFileObj: item.file })),
      params: { type: UPLOAD_FILE_TYPE_ENUM[602], foreignKey: "" },
    });
    const { filePath: userFaceUrl } = await uploadFile({
      files: (values.facePhoto || []).map(item => ({ ...item, originFileObj: item.file })),
      params: { type: UPLOAD_FILE_TYPE_ENUM[608], foreignKey: "" },
    });
    const { id: informSignId } = await uploadFile({
      single: false,
      files: [{ originFileObj: values.signature }],
      params: { type: informSignType, foreignKey: "" },
    });
    const { success, data } = await props["temporaryVisitorApplySave"]({
      ...values,
      drivingLicenseId,
      attachmentId,
      userFaceUrl,
      informSignId,
      jurisdictionalCorpId: values.jurisdictionalCorpId?.at(-1),
      closedAreaId: values.closedAreaId?.at(-1),
      userCard: btoa(values.userCard),
    });
    if (success) {
      props.history.push(`./success?id=${data.id}&tmpApplyType=${values.tmpApplyType}&tmpMkmjType=${values.tmpMkmjType}`);
    }
  };

  return (
    <div style={{ padding: "16px" }}>
      <Mask visible={props.mobile.temporaryVisitorLoading || uploadFileLoading}>
        <div style={{
          height: "100vh",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
        }}
        >
          <DotLoading color="white" />
          <div style={{ color: "#fff" }}>加载中...</div>
        </div>
      </Mask>
      <Form
        form={form}
        preserve={false}
        layout="horizontal"
        onFinish={onFinish}
        footer={(
          <Button block type="submit" shape="rounded" color="primary">
            提交申请
          </Button>
        )}
      >
        <Form.Item
          name="tmpApplyType"
          label="访问类型"
          rules={[{ required: true, message: "请选择访问类型" }]}
          trigger="onConfirm"
          onClick={(_, pickerRef) => {
            pickerRef.current?.open();
          }}
          getValueFromEvent={value => value[0]}
          getValueProps={value => [value]}
        >
          <Picker
            columns={[ACCESS_TYPE_ENUM]}
            onConfirm={(event) => {
              setMkmjType(event[0]);
              form.resetFields([
                "tmpMkmjType",
                "drivingUserName",
                "applyPersonUserName",
                "userPhone",
                "userCard",
                "vehicleType",
                "vehicleTypeName",
                "licenceType",
                "licenceTypeName",
                "licenceNo",
                "visitStartTime",
                "visitEndTime",
                "hgAuthArea",
                "hgAuthAreaName",
                "levelOneMkmjId",
                "levelOneMkmjName",
                "jurisdictionalCorpId",
                "jurisdictionalCorpName",
                "closedAreaId",
                "closedAreaName",
                "levelTwoMkmjId",
                "levelTwoMkmjName",
                "vehicleLicensePhoto",
                "vehiclePhoto",
                "facePhoto",
                "applyReason",
                "auditPersonUserId",
                "auditPersonUserName",
                "auditPersonCorpId",
                "auditPersonCorpName",
                "auditPersonDepartmentId",
                "auditPersonDepartmentName",
                "safetyNoticeAgreed",
                "signature",
              ]);
              setSignatureUrl("");
              checkboxRef.current?.uncheck?.();
              form.setFieldValue("tmpMkmjType", "");
              form.setFieldValue("vehicleTypeName", "");
              form.setFieldValue("licenceTypeName", "");
              form.setFieldValue("hgAuthAreaName", "");
              form.setFieldValue("levelOneMkmjName", "");
              form.setFieldValue("auditPersonUserName", "");
              form.setFieldValue("auditPersonCorpId", "");
              form.setFieldValue("auditPersonCorpName", "");
              form.setFieldValue("auditPersonDepartmentId", "");
              form.setFieldValue("auditPersonDepartmentName", "");
              form.setFieldValue("jurisdictionalCorpName", "");
              form.setFieldValue("closedAreaId", "");
              form.setFieldValue("closedAreaName", "");
              form.setFieldValue("levelTwoMkmjId", "");
              form.setFieldValue("levelTwoMkmjName", "");
              setFirstLevelDoorInfoListAll([]);
              setEnclosedAreaList([]);
              setTwoLevelDoorInfoListAll([]);
              setApprovalUserListAll([]);
            }}
          >
            {value => value?.[0]?.label || "请选择访问类型"}
          </Picker>
        </Form.Item>
        {tmpApplyType && (
          <Form.Item
            key={tmpApplyType || "tmpMkmjType"}
            name="tmpMkmjType"
            label="申请口门"
            rules={[{ required: true, message: "请选择选择申请口门" }]}
            trigger="onConfirm"
            onClick={(_, pickerRef) => {
              pickerRef.current?.open();
            }}
            getValueFromEvent={value => value[0]}
            getValueProps={value => [value]}
          >
            <Picker
              columns={[tmpApplyType === "PERSON_APPLY" ? APPLICATION_GATE_PERSON_TYPE_ENUM : APPLICATION_GATE_CAR_TYPE_ENUM]}
              onConfirm={(event) => {

                if (event[0] === "ONE_LEVEL_CAR_APPLY" || event[0] === "ONE_LEVEL_PERSON_APPLY") {
                  getApprovalUserList();
                }
                else {
                  setApprovalUserListAll([]);
                }
                form.setFieldValue("vehicleTypeName", "");
                form.setFieldValue("licenceTypeName", "");
                form.setFieldValue("hgAuthAreaName", "");
                form.setFieldValue("levelOneMkmjName", "");
                form.setFieldValue("auditPersonUserName", "");
                form.setFieldValue("auditPersonCorpId", "");
                form.setFieldValue("auditPersonCorpName", "");
                form.setFieldValue("auditPersonDepartmentId", "");
                form.setFieldValue("auditPersonDepartmentName", "");
                form.setFieldValue("jurisdictionalCorpName", "");
                form.setFieldValue("closedAreaId", "");
                form.setFieldValue("closedAreaName", "");
                form.setFieldValue("levelTwoMkmjId", "");
                form.setFieldValue("levelTwoMkmjName", "");
                setFirstLevelDoorInfoListAll([]);
                setEnclosedAreaList([]);
                setTwoLevelDoorInfoListAll([]);
              }}
            >
              {value => value?.[0]?.label || "请选择选择申请口门"}
            </Picker>
          </Form.Item>
        )}
        {
          tmpApplyType === "CAR_APPLY"
          && (
            <>
              <Form.Item name="drivingUserName" label="驾驶人姓名" rules={[{ required: true }]}>
                <Input placeholder="请输入驾驶人姓名" />
              </Form.Item>
              <BasicInfoFields />
              <Form.Item
                name="vehicleType"
                label="车辆类型"
                rules={[{ required: true, message: "请选择车辆类型" }]}
                trigger="onConfirm"
                onClick={(_, pickerRef) => {
                  pickerRef.current?.open();
                }}
                getValueFromEvent={value => value[0]}
                getValueProps={value => [value]}
              >
                <Picker
                  columns={[vehicleTypeList.map(item => ({ label: item.dictLabel, value: item.dictValue }))]}
                  onConfirm={(value) => {
                    form.setFieldValue("vehicleTypeName", getLabelName({
                      list: vehicleTypeList,
                      status: value[0],
                      idKey: "dictValue",
                      nameKey: "dictLabel",
                    }));
                  }}
                >
                  {value => value?.[0]?.label || "请选择车辆类型"}
                </Picker>
              </Form.Item>
              <Form.Item name="vehicleTypeName" label="车辆类型名称" noStyle>
                <input type="hidden" />
              </Form.Item>
              <Form.Item
                name="licenceType"
                label="车牌类型"
                rules={[{ required: true, message: "请选择车牌类型" }]}
                trigger="onConfirm"
                onClick={(_, pickerRef) => {
                  pickerRef.current?.open();
                }}
                getValueFromEvent={value => value[0]}
                getValueProps={value => [value]}
              >
                <Picker
                  columns={[licensePlateTypeList.map(item => ({ label: item.dictLabel, value: item.dictValue }))]}
                  onConfirm={(value) => {
                    form.setFieldValue("licenceTypeName", getLabelName({
                      list: licensePlateTypeList,
                      status: value[0],
                      idKey: "dictValue",
                      nameKey: "dictLabel",
                    }));
                  }}
                >
                  {value => value?.[0]?.label || "请选择车牌类型"}
                </Picker>
              </Form.Item>
              <Form.Item name="licenceTypeName" label="车牌类型名称" noStyle>
                <input type="hidden" />
              </Form.Item>
              <Form.Item
                name="licenceNo"
                label="车牌号"
                validateTrigger={["onChange", "onBlur"]}
                rules={[
                  { required: true },
                  { pattern: LICENSE_PLATE_NUMBER, message: "请输入正确的车牌号" },
                  {
                    validator: async (_, value) => {
                      if (value) {
                        const { data } = await props["vehicleApplyCheckLicenceNoBlack"]({
                          licenceNo: value,
                        });
                        return data.available ? Promise.resolve() : Promise.reject(new Error(data.availableMessage));
                      }
                      else {
                        Promise.resolve();
                      }
                    },
                    validateTrigger: "onBlur",
                  },
                ]}
              >
                <Input placeholder="请输入车牌号" />
              </Form.Item>
              <VisitTime form={form} />
              <LocationFields
                primeportAreaList={primeportAreaList}
                tmpMkmjType={tmpMkmjType}
                firstLevelDoorInfoListAll={firstLevelDoorInfoListAll}
                twoLevelDoorInfoListAll={twoLevelDoorInfoListAll}
                getFirstLevelDoorInfoListAll={getFirstLevelDoorInfoListAll}
                getTwoLevelDoorInfoListAll={getTwoLevelDoorInfoListAll}
                departmentList={departmentList}
                getTreeLabelName={getTreeLabelName}
                getEnclosedAreaList={getEnclosedAreaList}
                enclosedAreaList={enclosedAreaList}
                getApprovalUserList={getApprovalUserList}
                form={form}
              />
              <Form.Item
                name="vehicleLicensePhoto"
                label="行驶证照片"
                rules={[{ required: true, message: "请上传行驶证照片" }]}
              >
                <ImageUploader
                  upload={file => ({ url: URL.createObjectURL(file), file })}
                  maxCount={2}
                />
              </Form.Item>
              <Form.Item name="vehiclePhoto" label="车辆照片" rules={[{ required: true, message: "请上传车辆照片" }]}>
                <ImageUploader
                  upload={file => ({ url: URL.createObjectURL(file), file })}
                  maxCount={4}
                />
              </Form.Item>
              <Form.Item name="applyReason" label="申请理由" rules={[{ required: true, message: "请上传申请理由" }]}>
                <TextArea autoSize maxLength={500} />
              </Form.Item>
              <Approval form={form} approvalUserListAll={approvalUserListAll} />
              <SafetyNoticeAndSignature
                checkboxRef={checkboxRef}
                signatureUrl={signatureUrl}
                setNoticePopupVisible={setNoticePopupVisible}
              />
            </>
          )
        }
        {
          tmpApplyType === "PERSON_APPLY"
          && (
            <>
              <Form.Item name="applyPersonUserName" label="访问人姓名" rules={[{ required: true }]}>
                <Input placeholder="请输入访问人姓名" />
              </Form.Item>
              <BasicInfoFields />
              <VisitTime form={form} />
              <LocationFields
                primeportAreaList={primeportAreaList}
                tmpMkmjType={tmpMkmjType}
                firstLevelDoorInfoListAll={firstLevelDoorInfoListAll}
                twoLevelDoorInfoListAll={twoLevelDoorInfoListAll}
                getFirstLevelDoorInfoListAll={getFirstLevelDoorInfoListAll}
                getTwoLevelDoorInfoListAll={getTwoLevelDoorInfoListAll}
                departmentList={departmentList}
                getTreeLabelName={getTreeLabelName}
                getEnclosedAreaList={getEnclosedAreaList}
                enclosedAreaList={enclosedAreaList}
                getApprovalUserList={getApprovalUserList}
                form={form}
              />
              <Form.Item name="facePhoto" label="人脸照片" rules={[{ required: true, message: "请上传人脸照片" }]}>
                <ImageUploader
                  upload={file => ({ url: URL.createObjectURL(file), file })}
                  maxCount={1}
                />
              </Form.Item>
              <Form.Item name="applyReason" label="申请理由" rules={[{ required: true, message: "请上传申请理由" }]}>
                <TextArea autoSize maxLength={500} />
              </Form.Item>
              <Approval form={form} approvalUserListAll={approvalUserListAll} />
              <SafetyNoticeAndSignature
                checkboxRef={checkboxRef}
                signatureUrl={signatureUrl}
                setNoticePopupVisible={setNoticePopupVisible}
              />
            </>
          )
        }
      </Form>
      <Popup
        position="right"
        visible={noticePopupVisible}
        showCloseButton
        onClose={() => {
          setNoticePopupVisible(false);
        }}
      >
        <div style={{ padding: "40px 20px", overflowY: "auto", height: "100vh" }}>
          <p style={{
            textAlign: "justify",
            textIndent: "2rem",
          }}
          >
            欢迎您到访秦皇岛港。为保障您的人身安全及港口生产作业秩序，请注意港口属于重点安全监管区域，存在大型机械作业、货物装卸、车辆往来等生产场景，可能面临机械伤害、物体打击、车辆碰撞等安全风险。请您认真阅读以下须知内容，确认遵守后签字：
          </p>
          <p style={{ textAlign: "justify", textIndent: "2rem" }}>
            1.
            入港时请主动出示有效身份证件，配合安保人员进行身份核验与信息登记，凭港口核发的《临时访客证》入港，自觉接受出港查验；不转借、冒用访客凭证，不将无关人员带入港口。
          </p>
          <p style={{ textAlign: "justify", textIndent: "2rem" }}>
            2.
            入港后请严格在指定区域活动，未经陪同人员及港口负责人许可，绝不擅自进入标有"禁止入内""危险区域"等标识的场所，不靠近起重机械、输送设备、危险品存储点等高危部位，不跨越安全护栏、警戒线，不在作业区域逗留围观。
          </p>
          <p style={{ textAlign: "justify", textIndent: "2rem" }}>
            3.
            遵守港口生产秩序，不干扰装卸、运输、检修等正常工作；不随意触摸、操作生产设备、仪器仪表及安全设施，不移动、遮挡安全警示标识；如需拍摄港口场景，须提前征得港口方同意，不拍摄涉及安全、商业秘密的内容。
          </p>
          <p style={{ textAlign: "justify", textIndent: "2rem" }}>
            4.
            严格遵守消防安全规定，不在港口内吸烟，不携带火种、易燃易爆物品、管制器具等违禁物品入港；发现火灾、设备故障等隐患或突发情况，第一时间告知陪同人员或港口工作人员，配合应急处置，不擅自行动引发次生风险。
          </p>
          <p style={{ textAlign: "justify", textIndent: "2rem" }}>
            5.
            注意自身安全防护，行走时主动避让作业车辆与机械，不擅自横穿作业通道；雨天、雾天等恶劣天气下，听从陪同人员安排，加强安全防范。
          </p>
          <p style={{ textAlign: "justify", textIndent: "2rem" }}>
            6.
            已知晓港口所去区域应急逃生路线，遇紧急情况按港口指引有序疏散。
          </p>
          <p>本人确认已完整阅读并理解以上须知，承诺严格遵守。如因违反本须知及港口安全规定导致自身人身伤害或港口、他人财产损失，自愿承担全部责任。</p>
          <SignatureH5
            onConfirm={(value) => {
              setSignatureUrl(value.base64);
              form.setFieldValue("signature", value.file);
            }}
            url={signatureUrl}
          />
          <div style={{ marginTop: "20px" }}>
            <Button
              block
              shape="rounded"
              color="primary"
              onClick={() => {
                if (!signatureUrl) {
                  Toast.show({
                    icon: "fail",
                    content: "请签名",
                  });
                  return;
                }
                setNoticePopupVisible(false);
                checkboxRef.current.check();
              }}
            >
              完成
            </Button>
          </div>
        </div>
      </Popup>
    </div>
  );
}

// 公共基础信息字段组件
const BasicInfoFields = () => (
  <>
    <Form.Item
      name="userPhone"
      label="手机号"
      rules={[{ required: true }, { pattern: PHONE, message: "请输入正确的手机号" }]}
    >
      <Input placeholder="请输入手机号" />
    </Form.Item>
    <Form.Item
      name="userCard"
      label="身份证号"
      rules={[{ required: true }, { pattern: ID_NUMBER, message: "请输入正确的身份证号" }]}
    >
      <Input placeholder="请输入身份证号" />
    </Form.Item>
  </>
);

// 公共访问时间组件
const VisitTime = ({ form }) => {
  const visitStartTime = Form.useWatch("visitStartTime", form);
  return (
    <>
      <Form.Item
        name="visitStartTime"
        label="访问起始时间"
        rules={[{ required: true, message: "请选择访问起始时间" }, validatorTimeGECurrentDay({ type: "date" })]}
        trigger="onConfirm"
        onClick={(_, pickerRef) => {
          pickerRef.current?.open();
        }}
        getValueFromEvent={value => dayjs(value).format("YYYY-MM-DD")}
        getValueProps={value => dayjs(value)}
      >
        <DatePicker>
          {value => value ? dayjs(value).format("YYYY-MM-DD") : "请选择访问起始时间"}
        </DatePicker>
      </Form.Item>
      <Form.Item
        name="visitEndTime"
        label="访问结束时间"
        rules={[{
          required: true,
          message: "请选择访问结束时间",
        }, validatorEndTime({ startTime: visitStartTime })]}
        trigger="onConfirm"
        onClick={(_, pickerRef) => {
          pickerRef.current?.open();
        }}
        getValueFromEvent={value => dayjs(value).format("YYYY-MM-DD")}
        getValueProps={value => dayjs(value)}
      >
        <DatePicker>
          {value => value ? dayjs(value).format("YYYY-MM-DD") : "请选择访问结束时间"}
        </DatePicker>
      </Form.Item>
    </>
  );
};

// 公共地点字段组件
const LocationFields = ({
  primeportAreaList,
  tmpMkmjType,
  firstLevelDoorInfoListAll,
  twoLevelDoorInfoListAll,
  getFirstLevelDoorInfoListAll,
  getTwoLevelDoorInfoListAll,
  departmentList,
  getTreeLabelName,
  getEnclosedAreaList,
  enclosedAreaList,
  getApprovalUserList,
  form,
}) => (
  <>
    <Form.Item
      name="hgAuthArea"
      label="港区"
      rules={[{ required: true, message: "请选择港区" }]}
      trigger="onConfirm"
      onClick={(_, pickerRef) => {
        pickerRef.current?.open();
      }}
      getValueFromEvent={value => value[0]}
      getValueProps={value => [value]}
    >
      <Picker
        columns={[primeportAreaList.map(item => ({ label: item.dictLabel, value: item.dictValue }))]}
        onConfirm={(value) => {
          form.setFieldValue("hgAuthAreaName", getLabelName({
            list: primeportAreaList,
            status: value[0],
            idKey: "dictValue",
            nameKey: "dictLabel",
          }));
          form.setFieldValue("levelOneMkmjId", "");
          form.setFieldValue("levelOneMkmjName", "");
          getFirstLevelDoorInfoListAll(value[0]);
          getTwoLevelDoorInfoListAll(value[0]);
        }}
      >
        {value => value?.[0]?.label || "请选择港区"}
      </Picker>
    </Form.Item>
    <Form.Item name="hgAuthAreaName" label="港区名称" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item
      name="levelOneMkmjId"
      label="一级口门"
      rules={[{ required: true, message: "请选择一级口门" }]}
      trigger="onConfirm"
      onClick={(_, pickerRef) => {
        pickerRef.current?.open();
      }}
      getValueFromEvent={value => value[0]}
      getValueProps={value => [value]}
    >
      <Picker
        columns={[firstLevelDoorInfoListAll.map(item => ({ label: item.mkmjName, value: item.id }))]}
        onConfirm={(value) => {
          form.setFieldValue("levelOneMkmjName", getLabelName({
            list: firstLevelDoorInfoListAll,
            status: value[0],
            idKey: "id",
            nameKey: "mkmjName",
          }));
        }}
      >
        {value => value?.[0]?.label || "请选择一级口门"}
      </Picker>
    </Form.Item>
    <Form.Item name="levelOneMkmjName" label="一级口门名称" noStyle>
      <input type="hidden" />
    </Form.Item>
    {(tmpMkmjType === "TWO_LEVEL_CAR_APPLY" || tmpMkmjType === "TWO_LEVEL_PERSON_APPLY")
      && (
        <EnclosedAreaFields
          form={form}
          departmentList={departmentList}
          getTreeLabelName={getTreeLabelName}
          getEnclosedAreaList={getEnclosedAreaList}
          enclosedAreaList={enclosedAreaList}
          twoLevelDoorInfoListAll={twoLevelDoorInfoListAll}
          getApprovalUserList={getApprovalUserList}
        />
      )}
  </>
);

// 封闭区域相关字段组件
const EnclosedAreaFields = ({
  form,
  departmentList,
  getTreeLabelName,
  getEnclosedAreaList,
  enclosedAreaList,
  twoLevelDoorInfoListAll,
  getApprovalUserList,
}) => (
  <>
    <Form.Item
      name="jurisdictionalCorpId"
      label="区域所属公司"
      rules={[{ required: true, message: "请选择区域所属公司" }]}
      trigger="onConfirm"
      onClick={(_, pickerRef) => {
        pickerRef.current?.open();
      }}
      getValueFromEvent={value => value[0]}
      getValueProps={value => [value]}
    >
      <Picker
        columns={[departmentList.map(item => ({ label: item.name, value: item.id }))]}
        onConfirm={(value) => {
          form.setFieldValue("jurisdictionalCorpName", getLabelName({
            list: departmentList,
            status: value[0],
            idKey: "id",
            nameKey: "name",
          }));
          if (value[0]) {
            getEnclosedAreaList(value[0]);
            getApprovalUserList(value[0]);
          }
          form.setFieldValue("closedAreaId", "");
          form.setFieldValue("closedAreaName", "");
          form.setFieldValue("levelTwoMkmjId", "");
          form.setFieldValue("levelTwoMkmjName", "");
        }}
      >
        {value => value?.[0]?.label || "请选择区域所属公司"}
      </Picker>
    </Form.Item>
    <Form.Item name="jurisdictionalCorpName" label="区域所属公司名称" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item
      name="closedAreaId"
      label="封闭区域"
      rules={[{ required: true, message: "请选择封闭区域" }]}
      trigger="onConfirm"
      onClick={(_, pickerRef) => {
        pickerRef.current?.open();
      }}
      getValueFromEvent={value => value[0]}
      getValueProps={value => [value]}
    >
      <Cascader
        options={enclosedAreaList}
        onConfirm={(value) => {
          form.setFieldValue("closedAreaName", getTreeLabelName(enclosedAreaList, value.at(-1)));
        }}
      >
        {value => value.length > 0 ? value.map(item => item?.label).filter(Boolean).join("-") : "请选择封闭区域"}
      </Cascader>
    </Form.Item>
    <Form.Item name="closedAreaName" label="封闭区域名称" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item
      key={form.getFieldValue("jurisdictionalCorpId") || "levelTwoMkmjId"}
      name="levelTwoMkmjId"
      label="口门"
      rules={[{ required: true, message: "请选择口门" }]}
      trigger="onConfirm"
      onClick={(_, pickerRef) => {
        pickerRef.current?.open();
      }}
      getValueFromEvent={value => value[0]}
      getValueProps={value => [value]}
    >
      <Picker
        columns={[twoLevelDoorInfoListAll.map(item => ({ label: item.mkmjName, value: item.id }))]}
        onConfirm={(value) => {
          form.setFieldValue("levelTwoMkmjName", getLabelName({
            list: twoLevelDoorInfoListAll,
            status: value[0],
            idKey: "id",
            nameKey: "mkmjName",
          }));
        }}
      >
        {value => value?.[0]?.label || "请选择口门"}
      </Picker>
    </Form.Item>
    <Form.Item name="levelTwoMkmjName" label="口门名称" noStyle>
      <input type="hidden" />
    </Form.Item>
  </>
);

// 公共审批字段组件
const Approval = ({ form, approvalUserListAll }) => (
  <>
    <Form.Item
      name="auditPersonUserId"
      label="审批人"
      rules={[{ required: true, message: "请选择审批人" }]}
      trigger="onConfirm"
      onClick={(_, pickerRef) => {
        pickerRef.current?.open();
      }}
      getValueFromEvent={value => value[0]}
      getValueProps={value => [value]}
    >
      <Picker
        columns={[approvalUserListAll.map(item => ({
          label: `${item.userName}（${item.corpName}）（${item.deptName}）`,
          value: item.userId,
        }))]}
        onConfirm={(value) => {
          const item = approvalUserListAll.find(item => item.userId === value[0]);
          form.setFieldValue("auditPersonUserName", item.userName);
          form.setFieldValue("auditPersonCorpId", item.corpId);
          form.setFieldValue("auditPersonCorpName", item.corpName);
          form.setFieldValue("auditPersonDepartmentId", item.deptId);
          form.setFieldValue("auditPersonDepartmentName", item.deptName);
        }}
      >
        {value => value?.[0]?.label || "请选择审批人"}
      </Picker>
    </Form.Item>
    <Form.Item name="auditPersonCorpId" label="审批人员所属企业ID" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item name="auditPersonCorpName" label="审批人员所属企业名称" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item name="auditPersonDepartmentId" label="审批人员所属部门id" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item name="auditPersonDepartmentName" label="审批人员部门名称" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item name="auditPersonUserName" label="审批人员姓名" noStyle>
      <input type="hidden" />
    </Form.Item>
  </>
);

// 安全须知和签名组件
const SafetyNoticeAndSignature = ({ checkboxRef, signatureUrl, setNoticePopupVisible }) => (
  <>
    <Form.Item
      name="safetyNoticeAgreed"
      required={false}
      label=""
      rules={[{ required: true, message: "请勾选" }]}
    >
      <Checkbox style={{ "--icon-size": "18px", "--font-size": "14px", "--gap": "6px" }} ref={checkboxRef}>
        <div style={{ fontSize: "14px" }}>
          <span>我已阅读并同意</span>
          <span
            style={{ color: "#1677ff" }}
            onClick={() => {
              checkboxRef.current.check();
              setNoticePopupVisible(true);
            }}
          >
            《安全进港须知》
          </span>
        </div>
      </Checkbox>
    </Form.Item>
    <Form.Item name="signature" noStyle>
      <input type="hidden" />
    </Form.Item>
    <Form.Item noStyle>
      {signatureUrl && (
        <div style={{
          border: "1px dashed #d9d9d9",
          width: "90%",
          height: "200px",
          marginTop: "16px",
          margin: "16px auto",
        }}
        >
          <Image src={signatureUrl} style={{ width: "100%", height: "200px", objectFit: "contain" }} />
        </div>
      )}
    </Form.Item>
  </>
);

export default Connect([NS_MOBILE, NS_FIRST_LEVEL_DOOR_INFO, NS_APPROVER_USER, NS_ENCLOSED_AREA, NS_VEHICLE_APPLY], true)(Apply);
