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, 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_PERSONNEL } from "~/enumerate/namespace";


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) => {
    const { filePath: userFaceUrl } = await uploadFile({
      files: values.userFace,
      params: { type: UPLOAD_FILE_TYPE_ENUM[608] },
    });

    const { success } = await props["temporaryPersonnelAdd"]({
      ...values,
      personBelongType: 4,
      personApplyList: [
        { userFaceUrl,
         employeePersonUserName: values.employeePersonUserName ,
         userPhone: values.userPhone ,
         userCard: btoa(values.userCard) },
      ],
      gateLevelAuthArea: JSON.stringify({ area: values.area }),
    });
    if (success) {
      message.success("新增成功");
      props.history.goBack();
    }
  };

  return (
    <Page headerTitle="新增" isShowFooter={false}>
      <FormBuilder
        form={form}
        onFinish={onSubmit}
        loading={props.temporaryPersonnel.temporaryPersonnelLoading || uploadFileLoading}
        options={[
          { label: "申请信息", render: FORM_ITEM_RENDER_ENUM.DIVIDER },
          { name: "employeePersonUserName", label: "访问人姓名", span: 24 },
          { name: "userPhone", label: "手机号", rules: [{ pattern: PHONE, message: "请输入正确的手机号" }] },
          { name: "userCard", label: "身份证号", rules: [{ pattern: ID_NUMBER, message: "请输入正确的身份证号" }] },
          {
            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: "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: "reasonVisit", label: "来访事由", span: 24, render: FORM_ITEM_RENDER_ENUM.TEXTAREA },
          {
            name: "userFace",
            label: "人脸照片",
            span: 24,
            render: (
              <Upload
                maxCount={1}
                size={4}
                tipContent={(
                  <div style={{ color: "red", fontSize: 12 }}>
                    <div>• 图像格式：JPG、JPEG、PNG</div>
                    <div>• 图像大小：不超过4M</div>
                    <div>• 照片大小：推荐 500*500</div>
                    <div>• 人脸无遮挡（如戴帽子、口罩、眼镜等）、无修图</div>
                    <div>• 人脸需双眼睁开、表情自然、露额，头发不要遮挡</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" },
              labelCol: { span: 0 },
              wrapperCol: { span: 24 },
            },
            render: FORM_ITEM_RENDER_ENUM.CHECKBOX,
            items: [{
              bianma: "1",
              name: (
                <>
                  我已阅读并同意
                  <Button type="link" style={{ padding: 0 }}>《安全协议》</Button>
                </>
              ),
            }],
          },
        ]}
      />
    </Page>
  );
}

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