import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message } from "antd";
import { useEffect, 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 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 {
  NS_APPROVER_USER,
  NS_FIRST_LEVEL_DOOR_INFO,
  NS_TEMPORARY_VEHICLE,
  NS_VEHICLE_APPLY,
} from "~/enumerate/namespace";
import {VEHICLE_TYPE_ENUM} from "~/enumerate/constant";

function Add(props) {
  const [form] = FormBuilder.useForm();
  const gateLevelAuthArea = FormBuilder.useWatch("gateLevelAuthArea", form);
  const visitStartTime = FormBuilder.useWatch("visitStartTime", form);
  const { loading: uploadFileLoading, uploadFile } = useUploadFile();

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

  const getApprovalUserListAll = async () => {
    const { data } = await props["approvalUserListAll"]();
    setApprovalUserListAll(data);
  };
  const getFirstLevelDoorInfoListAll = async () => {
    const { data } = await props["firstLevelDoorInfoListAll"]({ mkmjLevel: 1, hgAuthArea: gateLevelAuthArea });
    setFirstLevelDoorInfoListAll(data);
  };

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

  useEffect(() => {
    if (gateLevelAuthArea) {
      getFirstLevelDoorInfoListAll();
    }
  }, [gateLevelAuthArea]);

  const onSubmit = async (values) => {
    if (values.drivingLicenseFile.length !== 2) {
      message.error("请上传两张驾驶证");
      return;
    }
    const { id: drivingLicenseId } = await uploadFile({
      single: false,
      files: values.drivingLicenseFile,
      params: { type: UPLOAD_FILE_TYPE_ENUM[601], foreignKey: "" },
    });
    const { id: attachmentId } = await uploadFile({
      single: false,
      files: values.attachmentFile,
      params: { type: UPLOAD_FILE_TYPE_ENUM[602], foreignKey: "" },
    });

    const { success } = await props["temporaryVehicleAdd"]({
      ...values,
      drivingLicenseId,
      attachmentId,
      lsUserIdcard: btoa(values.lsUserIdcard),
      gateLevelAuthArea: JSON.stringify({ area: values.area }),
    });
    if (success) {
      message.success("新增成功");
      props.history.goBack();
    }
  };

  return (
    <Page headerTitle="新增" isShowFooter={false} contentPadding="0 20px 20px 20px">
      <FormBuilder
        form={form}
        onFinish={onSubmit}
        loading={props.temporaryVehicle.temporaryVehicleLoading || uploadFileLoading}
        options={[
          { label: "申请信息", render: FORM_ITEM_RENDER_ENUM.DIVIDER },
          { name: "employeeVehicleUserName", label: "访问人姓名" },
          { name: "lsUserPhone", label: "手机号", rules: [{ pattern: PHONE, message: "请输入正确的手机号" }] },
          { name: "lsUserIdcard", label: "身份证号", rules: [{ pattern: ID_NUMBER, message: "请输入正确的身份证号" }] },
          {
            name: "licenceNo",
            label: "车牌号",
            rules: [
              { 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",
              },
            ],
            formItemProps: { validateTrigger: ["onChange", "onBlur"] },
          },
          {
            name: "licenceType",
            label: "车牌类型",
            render: (
              <DictionarySelect
                dictValue="LICENSE_PLATE_TYPE"
                onGetLabel={label => form.setFieldValue("licenceTypeName", label)}
              />
            ),
          },
          { name: "licenceTypeName", label: "车牌类型名称", onlyForLabel: true },
          {
            name: "vehicleType",
            label: "车辆类型",
            render: (
              <DictionarySelect
                dictValue="VEHICLE_TYPE"
                onGetLabel={label => form.setFieldValue("vehicleTypeName", label)}
              />
            ),
          },
          { name: "vehicleTypeName", 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: "vehicleBelongType",
            label: "车辆所属类型",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items:VEHICLE_TYPE_ENUM
          },

          {
            name: "gateLevelAuthArea",
            label: "访问港区",
            render: (
              <DictionarySelect
                dictValue="HG_AUTH_AREA"
                onGetOption={(option) => {
                  const area = [{ value: option.dictLabel, bianma: option.dictValue }];
                  form.setFieldValue("area", area);
                }}
                onChange={() => {
                  form.setFieldValue("mkmjId", "");
                  form.setFieldValue("mkmjName", "");
                }}
              />
            ),
          },
          { name: "area", label: "访问港区", onlyForLabel: true },
          {
            name: "mkmjId",
            label: "访问口门名称",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: firstLevelDoorInfoListAll,
            itemsField: { labelKey: "mkmjName", valueKey: "id" },
            componentProps: {
              onChange: event =>
                form.setFieldValue("mkmjName", getLabelName({
                  list: firstLevelDoorInfoListAll,
                  status: event,
                  idKey: "id",
                  nameKey: "mkmjName",
                })),
            },
          },
          { name: "mkmjName", label: "访问口门名称", onlyForLabel: true },
          { name: "remarks", label: "来访事由", span: 24, render: FORM_ITEM_RENDER_ENUM.TEXTAREA },
          {
            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>
                )}
              />
            ),
          },
          {
            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>
                )}
              />
            ),
          },
          { label: "审批信息", render: FORM_ITEM_RENDER_ENUM.DIVIDER },
          {
            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: "auditDeptId", label: "审批企业ID", onlyForLabel: true },
          { name: "auditDeptName", label: "审批企业名称", onlyForLabel: true },
          { name: "auditCorpId", label: "审批企业ID", onlyForLabel: true },
          { name: "auditCorpName", label: "审批企业名称", onlyForLabel: true },
          {
            name: "securityProtocol",
            label: " ",
            span: 24,
            required: false,
            rules: [{ required: true, message: "请勾选" }],
            formItemProps: { colon: false, required: false, style: { textAlign: "center" } },
            render: FORM_ITEM_RENDER_ENUM.CHECKBOX,
            items: [{
              bianma: "1",
              name: (
                <>
                  我已阅读并同意
                  <Button type="link" style={{ padding: 0 }}>《安全协议》</Button>
                </>
              ),
            }],
          },
        ]}
      />
    </Page>
  );
}

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