import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message, Modal } 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 Table from "zy-react-library/components/Table";
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 { getLabelName } from "zy-react-library/utils";
import NeedToKnowModal from "~/components/NeedToKnowModal";
import { TRAINING_STATE_ENUM } from "~/enumerate/constant";
import {
  NS_APPROVER_USER,
  NS_ENCLOSED_AREA_PERSONNEL_APPLY,
  NS_FIRST_LEVEL_DOOR_INFO,
  NS_PERSONNEL_APPLICATION,
} from "~/enumerate/namespace";
import useGetUserInfo from "zy-react-library/hooks/useGetUserInfo";
function Add(props) {
  const [form] = FormBuilder.useForm();
  const gateLevelAuthArea = FormBuilder.useWatch("gateLevelAuthArea", form);
  const { loading: uploadFileLoading, uploadFile } = useUploadFile();

  const [personnelList, setPersonnelList] = useState([]);
  const [addPersonnelModalVisible, setAddPersonnelModalVisible] = useState(false);
  const [needToKnowModalVisible, setNeedToKnowModalVisible] = useState(false);
  const [firstLevelDoorInfoListAll, setFirstLevelDoorInfoListAll] = useState([]);
  const [xgfProjectListAll, setXgfProjectListAll] = useState([]);
  const [approvalUserListAll, setApprovalUserListAll] = useState([]);
  const [xgfProjectUser, setXgfProjectUser] = useState([]);
  const [userId, setUserId] = useState("");
  const { getUserInfo } = useGetUserInfo();

  const signatureUrl = useRef("");

  const getInfoData = async () => {
    const data = await getUserInfo();
    setUserId(data.id);
  };

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

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

  const getApprovalUserListAll = async () => {
    const { data } = await props["approvalUserListAll"]({ personnelPermissionFlag: 1 });
    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 (!userId || xgfProjectUser.length === 0) {
      return;
    }
    const currentUser = xgfProjectUser.find(item => String(item.userId) === String(userId));
    if (!currentUser) {
      return;
    }
    setPersonnelList(list => (
      list.some(item => String(item.userId) === String(userId)) ? list : [...list, currentUser]
    ));
  }, [userId, xgfProjectUser]);

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

  const onSubmit = async (values) => {
    if (!values.informSignFile) {
      message.warning("请勾选《安全进港须知》并签字");
      return;
    }
    const submitValues = { ...values };
    delete submitValues.auditUserRecordId;
    const { id: informSignId } = await uploadFile({
      files: [{ originFileObj: values.informSignFile }],
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[611] },
    });
    const { success } = await props["personnelApplicationAdd"]({
      ...submitValues,
      gateLevelAuthArea: JSON.stringify({ area: values.area }),
      visitStartTime: values.visitTime[0],
      visitEndTime: values.visitTime[1],
      personApplyList: personnelList.map(item => ({
        personCorpId: item.corpId,
        personCorpName: item.corpName,
        personDepartmentId: item.deptId,
        personDepartmentName: item.deptName,
        employeePersonUserId: item.userId,
        employeePersonUserName: item.userName,
        userFaceUrl: item.userFaceUrl,
        userPhone: item.phone,
        userCard: btoa(item.userCard),
        ...item,
      })),
      informSignId,
      personBelongType: 3,
    });
    if (success) {
      message.success("操作成功");
      props.history.goBack();
    }
  };

  return (
    <Page headerTitle="新增" isShowFooter={false}>
      <FormBuilder
        form={form}
        onFinish={onSubmit}
        loading={props.personnelApplication.personnelApplicationLoading || 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);
                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: "auditUserRecordId",
            label: "审核人员",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: approvalUserListAll,
            itemsField: { labelKey: item => `${item.userName}（${item.corpName}）（${item.deptName}）`, valueKey: "id" },
            componentProps: {
              onChange: (value) => {
                const item = approvalUserListAll.find(item => item.id === value) || {};
                form.setFieldValue("auditUserId", item.userId);
                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: "auditUserId", label: "审核人员ID", onlyForLabel: true },
          { 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 },
          {
            customizeRender: true,
            span: 24,
            render: (
              <Table
                toolBarRender={() => (
                  <Button
                    type="primary"
                    onClick={() => {
                      if (!form.getFieldValue("projectId")) {
                        message.warning("请先选择项目");
                      }
                      else {
                        setAddPersonnelModalVisible(true);
                      }
                    }}
                  >
                    添加人员
                  </Button>
                )}
                options={false}
                disabledResizer={true}
                columns={[
                  { title: "姓名", dataIndex: "userName" },
                  { title: "部门", dataIndex: "deptName" },
                  {
                    title: "是否培训",
                    dataIndex: "trainingState",
                    render: (_, record) => getLabelName({ list: TRAINING_STATE_ENUM, status: record.trainingState }),
                  },
                  // { title: "现口门权限范围", dataIndex: "todo4" },
                  {
                    title: "操作",
                    width: 80,
                    fixed: "right",
                    render: (_, record) => (
                      <Button
                        type="link"
                        danger
                        disabled={Boolean(userId) && String(record.userId) === String(userId)}
                        onClick={() => {
                          Modal.confirm({
                            title: "删除确认",
                            content: "确定删除吗？",
                            onOk: () => {
                              setPersonnelList(personnelList.filter(item => item.userId !== record.userId));
                            },
                          });
                        }}
                      >
                        删除
                      </Button>
                    ),
                  },
                ]}
                dataSource={personnelList}
                pagination={false}
              />
            ),
          },
          {
            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 },
        ]}
      />
      {
        addPersonnelModalVisible && (
          <AddPersonnelModal
            personnelList={personnelList}
            xgfProjectUser={xgfProjectUser}
            userId={userId}
            onCancel={() => {
              setAddPersonnelModalVisible(false);
            }}
            onOk={(values) => {
              setPersonnelList(values);
              setAddPersonnelModalVisible(false);
            }}
          />
        )
      }
      {
        needToKnowModalVisible && (
          <NeedToKnowModal
            signatureUrl={signatureUrl.current}
            onCancel={() => {
              setNeedToKnowModalVisible(false);
            }}
            onOk={(values) => {
              form.setFieldValue("informSignFile", values.file);
              signatureUrl.current = values.base64;
              setNeedToKnowModalVisible(false);
            }}
          />
        )
      }
    </Page>
  );
}

const AddPersonnelModalComponent = (props) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState(props.personnelList.map(item => item.userId));

  const selectedRowsRef = useRef(props.personnelList || []);

  return (
    <Modal
      open
      title="选择人员"
      width={800}
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={() => {
        if (selectedRowKeys.length === 0) {
          message.warning("请选择人员");
        }
        else {
          props.onOk(selectedRowsRef.current);
        }
      }}
    >
      <Table
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRowKeys(selectedRowKeys);
            selectedRowsRef.current = selectedRows;
          },
          preserveSelectedRowKeys: true,
          getCheckboxProps: record => ({
            disabled: record.trainingState === "0" || (Boolean(props.userId) && String(record.userId) === String(props.userId)),
          }),
        }}
        options={false}
        disabledResizer={true}
        rowKey="userId"
        columns={[
          { title: "姓名", dataIndex: "userName" },
          { title: "部门", dataIndex: "deptName" },
          {
            title: "是否培训",
            dataIndex: "trainingState",
            render: (_, record) => getLabelName({ list: TRAINING_STATE_ENUM, status: record.trainingState }),
          },
          // { title: "现口门权限范围", dataIndex: "todo4" },
        ]}
        dataSource={props.xgfProjectUser}
        pagination={false}
      />
    </Modal>
  );
};

const AddPersonnelModal = Connect([NS_PERSONNEL_APPLICATION], true)(AddPersonnelModalComponent);

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