import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message } from "antd";
import dayjs from "dayjs";
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 useUploadFile from "zy-react-library/hooks/useUploadFile";
import { LICENSE_PLATE_NUMBER } from "zy-react-library/regular";
import { getLabelName } from "zy-react-library/utils";
import NeedToKnowModal from "~/components/NeedToKnowModal";
import {
  NS_APPROVER_USER,
  NS_ENCLOSED_AREA_PERSONNEL_APPLY,
  NS_FIRST_LEVEL_DOOR_INFO,
  NS_VEHICLE_APPLY,
} from "~/enumerate/namespace";

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

  const [needToKnowModalVisible, setNeedToKnowModalVisible] = useState(false);
  const [firstLevelDoorInfoListAll, setFirstLevelDoorInfoListAll] = useState([]);
  const [xgfProjectListAll, setXgfProjectListAll] = useState([]);
  const [approvalUserListAll, setApprovalUserListAll] = useState([]);
  const [xgfProjectUser, setXgfProjectUser] = useState([]);

  const signatureUrl = useRef("");

  const getXgfProjectListAll = async () => {
    const { data } = await props["xgfProjectListAll"]({betweenProjectTime :1 });
    setXgfProjectListAll(data);
  };

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

  const getXgfProjectUserGetPeopleProject = async (id) => {
    const { data } = await props["xgfProjectUserGetPeopleProject"]({ id });
    setXgfProjectUser(data);
  };

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

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

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

  const onSubmit = async (values) => {
    if (!values.informSignFile) {
      message.warning("请勾选《安全进港须知》并签字");
      return;
    }
    if (values.drivingLicenseFile.length !== 2) {
      message.error("请上传两张驾驶证");
      return;
    }
    const { id: informSignId } = await uploadFile({
      files: [{ originFileObj: values.informSignFile }],
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[606] },
    });
    const { id: drivingLicenseId } = await uploadFile({
      files: values.drivingLicenseFile,
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[601] },
    });
    const { id: attachmentId } = await uploadFile({
      files: values.attachmentFile,
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[602] },
    });
    const { success } = await props["vehicleApplyAdd"]({
      ...values,
      gateLevelAuthArea: JSON.stringify({ area: values.area }),
      visitStartTime: values.visitTime[0],
      visitEndTime: values.visitTime[1],
      informSignId,
      drivingLicenseId,
      attachmentId,
      vehicleBelongType: 5,
    });
    if (success) {
      message.success("操作成功");
      props.history.goBack();
    }
  };

  return (
    <Page headerTitle="新增" isShowFooter={false}>
      <FormBuilder
        form={form}
        onFinish={onSubmit}
        loading={props.vehicleApply.vehicleApplyLoading || uploadFileLoading}
        options={[
          {
            name: "projectId",
            label: "项目",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: xgfProjectListAll,
            itemsField: { labelKey: "projectName", valueKey: "id" },
            componentProps: {
              onChange: (value) => {
                const item = xgfProjectListAll.find(i => i.id === value) || {};
                form.setFieldValue("projectName", item.projectName);
                form.setFieldValue("drivingUserId", "");
                form.setFieldValue("drivingUserName", "");
                if (value) {
                  getXgfProjectUserGetPeopleProject(value);
                  form.setFieldValue("visitTime", [dayjs(item.startProjectTime).format("YYYY-MM-DD"), dayjs(item.endProjectTime).format("YYYY-MM-DD")]);
                }
                else {
                  setXgfProjectUser([]);
                  form.setFieldValue("visitTime", []);
                }
              },
            },
          },
          { name: "projectName", 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" },
            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 },
          {
            name: "visitTime",
            label: "时间",
            render: FORM_ITEM_RENDER_ENUM.DATE_RANGE,
            componentProps: { disabled: true },
          },
          {
            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: "drivingUserId",
            label: "驾驶人员",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: xgfProjectUser,
            itemsField: { labelKey: "userName", valueKey: "userId" },
            componentProps: {
              onChange: (value) => {
                form.setFieldValue("drivingUserName", getLabelName({
                  list: xgfProjectUser,
                  status: value,
                  idKey: "userId",
                  nameKey: "userName",
                }));
              },
            },
          },
          { name: "drivingUserName", label: "驾驶人员名称", onlyForLabel: true },
          {
            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: "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: "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>
                )}
              />
            ),
          },
          {
            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: "securityProtocol",
            label: " ",
            span: 24,
            required: false,
            rules: [{ required: true, message: "请勾选" }],
            formItemProps: {
              colon: false,
              required: false,
              style: { textAlign: "center" },
              labelCol: { span: 0 },
              wrapperCol: { span: 24 },
            },
            render: FORM_ITEM_RENDER_ENUM.CHECKBOX,
            items: [{
              bianma: "1",
              name: (
                <>
                  我已阅读并同意
                  <Button
                    type="link"
                    style={{ padding: 0 }}
                    onClick={() => {
                      setNeedToKnowModalVisible(true);
                    }}
                  >
                    《安全进港须知》
                  </Button>
                </>
              ),
            }],
          },
          { name: "informSignFile", label: "签字", onlyForLabel: true },
        ]}
      />
      {
        needToKnowModalVisible && (
          <NeedToKnowModal
            signatureUrl={signatureUrl.current}
            onCancel={() => {
              setNeedToKnowModalVisible(false);
            }}
            onOk={(values) => {
              form.setFieldValue("informSignFile", values.file);
              signatureUrl.current = values.base64;
              setNeedToKnowModalVisible(false);
            }}
          />
        )
      }
    </Page>
  );
}

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