import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { message } from "antd";
import { useEffect, useRef, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
import Page from "zy-react-library/components/Page";
import DictionarySelect from "zy-react-library/components/Select/Dictionary";
import Upload from "zy-react-library/components/Upload";
import { FORM_ITEM_RENDER_ENUM } from "zy-react-library/enum/formItemRender";
import { UPLOAD_FILE_TYPE_ENUM } from "zy-react-library/enum/uploadFile/gwj";
import useDeleteFile from "zy-react-library/hooks/useDeleteFile";
import useGetFile from "zy-react-library/hooks/useGetFile";
import useGetUrlQuery from "zy-react-library/hooks/useGetUrlQuery";
import useGetUserInfo from "zy-react-library/hooks/useGetUserInfo";
import useUploadFile from "zy-react-library/hooks/useUploadFile";
import { LICENSE_PLATE_NUMBER } from "zy-react-library/regular";
import { validatorEndTime, validatorTimeGECurrentDay } from "zy-react-library/utils";
import { VEHICLE_TYPE_ENUM } from "~/enumerate/constant";
import { NS_APPROVER_USER, NS_VEHICLE_APPLY } from "~/enumerate/namespace";

function Add(props) {
  const query = useGetUrlQuery();
  const { getUserInfo } = useGetUserInfo();
  const [form] = FormBuilder.useForm();
  const visitStartTime = FormBuilder.useWatch("visitStartTime", form);
  const { loading: uploadFileLoading, uploadFile } = useUploadFile();
  const { loading: deleteFileLoading, deleteFile } = useDeleteFile();
  const { loading: getFileLoading, getFile } = useGetFile();

  const [approvalUserListAll, setApprovalUserListAll] = useState([]);

  const info = useRef([]);

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

  const getData = async () => {
    if (query.id) {
      const { data } = await props["vehicleApplyInfo"]({ id: query.id });
      const drivingLicenseFile = await getFile({
        eqType: UPLOAD_FILE_TYPE_ENUM[601],
        eqForeignKey: data.drivingLicenseId,
      });
      const attachmentFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[602], eqForeignKey: data.attachmentId });
      form.setFieldsValue({
        ...data,
        drivingLicenseFile,
        attachmentFile,
        area: JSON.parse(data.gateLevelAuthArea).area,
        gateLevelAuthArea: JSON.parse(data.gateLevelAuthArea).area.map(item => item.bianma),
        auditUserId: data.currentAuditUserId,
        auditUserName: data.currentAuditUserName,
        auditCorpId: data.currentAuditCorpId,
        auditCorpName: data.currentAuditCorpName,
        auditDeptId: data.currentAuditDeptId,
        auditDeptName: data.currentAuditDeptName,
      });
      info.current = data;
      getApprovalUserListAll(data.vehicleCorpId);
    }
    else {
      if (query.employeeVehicleUserId) {
        form.setFieldsValue({
          employeeVehicleUserId: query.employeeVehicleUserId,
          employeeVehicleUserName: query.employeeVehicleUserName,
          vehicleDepartmentName: query.vehicleDepartmentName,
          vehicleDepartmentId: query.vehicleDepartmentId,
          vehicleCorpId: query.vehicleCorpId,
          vehicleCorpName: query.vehicleCorpName,
        });
        getApprovalUserListAll(query.vehicleCorpId);
        return;
      }
      const userInfo = await getUserInfo();
      form.setFieldsValue({
        employeeVehicleUserId: userInfo.id,
        employeeVehicleUserName: userInfo.name,
        vehicleDepartmentName: userInfo.departmentName,
        vehicleDepartmentId: userInfo.departmentId,
        vehicleCorpId: userInfo.corpinfoId,
        vehicleCorpName: userInfo.corpinfoName,
      });
      getApprovalUserListAll(userInfo.corpinfoId);
    }
  };

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

  const onSubmit = async (values) => {
    if (values.drivingLicenseFile.length !== 2) {
      message.error("请上传两张驾驶证");
      return;
    }
    await deleteFile({ single: false, files: values.drivingLicenseDeleteFile });
    await deleteFile({ single: false, files: values.attachmentDeleteFile });
    const { id: drivingLicenseId } = await uploadFile({
      single: false,
      files: values.drivingLicenseFile,
      params: { foreignKey: info.current.drivingLicenseId, type: UPLOAD_FILE_TYPE_ENUM[601] },
    });
    const { id: attachmentId } = await uploadFile({
      single: false,
      files: values.attachmentFile,
      params: { foreignKey: info.current.attachmentId, type: UPLOAD_FILE_TYPE_ENUM[602] },
    });
    const { success } = await props[!query.id ? "vehicleApplyAdd" : "vehicleApplyUpdate"]({
      ...values,
      id: query.id,
      drivingLicenseId,
      attachmentId,
      gateLevelAuthArea: JSON.stringify({ area: values.area }),
    });
    if (success) {
      message.success("操作成功");
      props.history.goBack();
    }
  };

  const getVehicleBelongFields = () => {
    if (!props.vehicleBelongType) {
      return [
        { name: "vehicleBelongType", label: "车辆所属类型", onlyForLabel: true },
        { name: "employeeVehicleUserName", label: "车辆所属人", span: 24, componentProps: { disabled: true } },
        { name: "employeeVehicleUserId", label: "车辆所属人ID", onlyForLabel: true },
        { name: "vehicleDepartmentName", label: "车辆所属部门", onlyForLabel: true },
        { name: "vehicleDepartmentId", label: "车辆所属部门ID", onlyForLabel: true },
        { name: "vehicleCorpId", label: "车辆所属企业ID", onlyForLabel: true },
        { name: "vehicleCorpName", label: "车辆所属企业名称", onlyForLabel: true },
      ];
    }
    else if (props.vehicleBelongType === 2 || props.vehicleBelongType === 4) {
      return [
        {
          name: "vehicleBelongType",
          label: "车辆所属类型",
          render: FORM_ITEM_RENDER_ENUM.SELECT,
          items: VEHICLE_TYPE_ENUM,
          componentProps: { disabled: true },
        },
        { name: "vehicleDepartmentName", label: "车辆所属部门", componentProps: { disabled: true } },
        { name: "vehicleDepartmentId", label: "车辆所属部门ID", onlyForLabel: true },
        { name: "vehicleCorpId", label: "车辆所属企业ID", onlyForLabel: true },
        { name: "vehicleCorpName", label: "车辆所属企业名称", onlyForLabel: true },
      ];
    }
    else if (props.vehicleBelongType === 1 || props.vehicleBelongType === 3 || props.vehicleBelongType === 8) {
      return [
        {
          name: "vehicleBelongType",
          label: "车辆所属类型",
          span: 24,
          render: FORM_ITEM_RENDER_ENUM.SELECT,
          items: VEHICLE_TYPE_ENUM,
          componentProps: { disabled: true },
        },
        { name: "vehicleDepartmentName", label: "车辆所属部门", componentProps: { disabled: true } },
        { name: "vehicleDepartmentId", label: "车辆所属部门ID", onlyForLabel: true },
        { name: "employeeVehicleUserName", label: "车辆所属人", componentProps: { disabled: true } },
        { name: "employeeVehicleUserId", label: "车辆所属人ID", onlyForLabel: true },
        { name: "vehicleCorpId", label: "车辆所属企业ID", onlyForLabel: true },
        { name: "vehicleCorpName", label: "车辆所属企业名称", onlyForLabel: true },
      ];
    }
    return [];
  };

  return (
    <Page headerTitle={query.id ? "重新申请" : "新增"} isShowFooter={false}>
      <FormBuilder
        form={form}
        loading={props.vehicleApply.vehicleApplyLoading || uploadFileLoading || deleteFileLoading || getFileLoading}
        onFinish={onSubmit}
        values={{
          vehicleBelongType: props.vehicleBelongType ? props.vehicleBelongType.toString() : "1",
        }}
        options={[
          ...getVehicleBelongFields(),
          {
            name: "licenceType",
            label: "车牌类型",
            render: (
              <DictionarySelect
                dictValue="LICENSE_PLATE_TYPE"
                disabled={!!query.id}
                onGetLabel={label => form.setFieldValue("licenceTypeName", label)}
              />
            ),
          },
          { name: "licenceTypeName", label: "车牌类型名称", onlyForLabel: true },
          {
            name: "licenceNo",
            label: "车牌号",
            rules: [
              { pattern: LICENSE_PLATE_NUMBER, message: "请输入正确的车牌号" },
              {
                validator: async (_, value) => {
                  if (value) {
                    const { data } = await props["vehicleApplyCheckLicenceNo"]({
                      licenceNo: value,
                      id: query.id,
                    });
                    return data.available ? Promise.resolve() : Promise.reject(new Error(data.availableMessage));
                  }
                  else {
                    Promise.resolve();
                  }
                },
                validateTrigger: "onBlur",
              },
            ],
            formItemProps: { validateTrigger: ["onChange", "onBlur"] },
            componentProps: { disabled: !!query.id },
          },
          {
            name: "vehicleType",
            label: "车辆类型",
            render: (
              <DictionarySelect
                dictValue="VEHICLE_TYPE"
                disabled={!!query.id}
                onGetLabel={label => form.setFieldValue("vehicleTypeName", label)}
              />
            ),
          },
          { name: "vehicleTypeName", label: "车辆类型名称", onlyForLabel: true },
          {
            name: "gateLevelAuthArea",
            label: "访问港区",
            render: (
              <DictionarySelect
                dictValue="HG_AUTH_AREA"
                mode="multiple"
                onGetOption={(option) => {
                  const area = option.map(item => ({ value: item.dictLabel, bianma: item.dictValue }));
                  form.setFieldValue("area", area);
                }}
              />
            ),
          },
          { name: "area", label: "访问港区", onlyForLabel: true },
          {
            name: "visitStartTime",
            label: "访问开始时间",
            render: FORM_ITEM_RENDER_ENUM.DATE,
            rules: [validatorTimeGECurrentDay({ type: "date" })],
          },
          {
            name: "visitEndTime",
            label: "访问结束时间",
            render: FORM_ITEM_RENDER_ENUM.DATE,
            rules: [validatorEndTime({ startTime: visitStartTime })],
          },
          {
            name: "drivingLicenseFile",
            label: "行驶证照片",
            span: 24,
            render: (
              <Upload
                maxCount={2}
                size={5}
                tipContent={(
                  <div style={{ color: "red", fontSize: 12 }}>
                    <div>1. 请拍摄行驶证正面和反面，确保四角完整、无遮挡</div>
                    <div>2. 文字、印章清晰可见，避免反光</div>
                    <div>3. 支持格式:.jpg/.jpeg/.png，单张5MB</div>
                  </div>
                )}
                onGetRemoveFile={file => form.setFieldValue("drivingLicenseDeleteFile", [...(form.getFieldValue("drivingLicenseDeleteFile") || []), file])}
              />
            ),
          },
          { name: "drivingLicenseDeleteFile", label: "删除的行驶证照片", onlyForLabel: true },
          {
            name: "attachmentFile",
            label: "车辆图片",
            span: 24,
            render: (
              <Upload
                maxCount={4}
                size={5}
                tipContent={(
                  <div style={{ color: "red", fontSize: 12 }}>
                    <div>1.上限4张</div>
                    <div>2. 请从车辆左前侧45°拍摄，车牌清晰可见</div>
                    <div>3. 背景简洁，避免逆光或阴影</div>
                    <div>4. 支持格式:.jpg/.jpeg/.png，单张5MB</div>
                  </div>
                )}
                onGetRemoveFile={file => form.setFieldValue("attachmentDeleteFile", [...(form.getFieldValue("attachmentDeleteFile") || []), file])}
              />
            ),
          },
          { name: "attachmentDeleteFile", label: "删除的车辆图片", onlyForLabel: true },
          {
            name: "auditUserId",
            label: "审批人",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: approvalUserListAll,
            itemsField: { labelKey: item => `${item.userName}（${item.corpName}）（${item.deptName}）`, valueKey: "userId" },
            span: 24,
            componentProps: {
              onChange: (value) => {
                const item = approvalUserListAll.find(item => item.userId === value);
                form.setFieldValue("auditUserName", item.userName);
                form.setFieldValue("auditCorpId", item.corpId);
                form.setFieldValue("auditCorpName", item.corpName);
                form.setFieldValue("auditDeptId", item.deptId);
                form.setFieldValue("auditDeptName", item.deptName);
              },
            },
          },
          { name: "auditUserName", label: "审批人名称", onlyForLabel: true },
          { name: "auditCorpId", label: "审核企业ID", onlyForLabel: true },
          { name: "auditCorpName", label: "审核企业名称", onlyForLabel: true },
          { name: "auditDeptId", label: "审核部门ID", onlyForLabel: true },
          { name: "auditDeptName", label: "审核部门名称", onlyForLabel: true },
        ]}
      />
    </Page>
  );
}

export default Connect([NS_VEHICLE_APPLY, NS_APPROVER_USER], true)(Add);
