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 Search from "zy-react-library/components/Search";
import BasicSelectTree from "zy-react-library/components/SelectTree/Basic";
import DepartmentSelectTree from "zy-react-library/components/SelectTree/Department/Gwj";
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 useTable from "zy-react-library/hooks/useTable";
import useUploadFile from "zy-react-library/hooks/useUploadFile";
import NeedToKnowModal from "~/components/NeedToKnowModal";
import { NS_APPROVER_USER, NS_ENCLOSED_AREA, NS_ENCLOSED_AREA_PERSONNEL_APPLY } from "~/enumerate/namespace";

function Add(props) {
  const [enclosedAreaList, setEnclosedAreaList] = useState([]);
  const [entourageList, setEntourageList] = useState([]);
  const [selectEntourageModalVisible, setSelectEntourageModalVisible] = useState(false);
  const [needToKnowModalVisible, setNeedToKnowModalVisible] = useState(false);
  const [approvalUserListAll, setApprovalUserListAll] = useState([]);
  const [xgfProjectListAll, setXgfProjectListAll] = useState([]);

  const signatureUrl = useRef("");

  const [form] = FormBuilder.useForm();
  const { loading: uploadFileLoading, uploadFile } = useUploadFile();

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

  const getEnclosedAreaList = async (jurisdictionalCorpId) => {
    const { data } = await props["enclosedAreaDetailListTree"]({ jurisdictionalCorpId });
    setEnclosedAreaList(data);
  };

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

  useEffect(() => {
    props.entrance === "stakeholder" && getXgfProjectListAll();
  }, []);

  const onSubmit = async (values) => {
    if (!values.informSignFile) {
      message.warning("请勾选《安全进港须知》并签字");
      return;
    }
    let personBelongType = 1;
    if (props.entrance === "enterprise")
      personBelongType = 2;
    if (props.entrance === "stakeholder")
      personBelongType = 3;
    const { id: informSignId } = await uploadFile({
      files: [{ originFileObj: values.informSignFile }],
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[609] },
    });
    const { success } = await props["enclosedAreaPersonnelApplySave"]({
      ...values,
      visitStartTime: values.visitTime[0],
      visitEndTime: values.visitTime[1],
      personBelongType,
      informSignId,
      entourage: JSON.stringify(entourageList),
    });
    if (success) {
      message.success("操作成功");
      props.history.goBack();
    }
  };

  return (
    <Page headerTitle="申请权限" isShowFooter={false}>
      <FormBuilder
        submitButtonText="提交申请"
        onFinish={onSubmit}
        loading={props.enclosedAreaPersonnelApply.enclosedAreaPersonnelApplyLoading || uploadFileLoading}
        options={[
          {
            name: "projectId",
            label: "项目",
            tip: "如果无法找到相应的项目，请在“项目审核管理”栏目中查看，项目是否备案审核成功。",
            span: 24,
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: xgfProjectListAll,
            itemsField: { labelKey: "projectName", valueKey: "id" },
            hidden: !(props.entrance === "stakeholder"),
            componentProps: {
              onChange: (value) => {
                const item = xgfProjectListAll.find(i => i.id === value) || {};
                form.setFieldValue("projectName", item.projectName);
                setEntourageList([]);
                if (value) {
                  form.setFieldValue("visitTime", [dayjs(item.startProjectTime).format("YYYY-MM-DD"), dayjs(item.endProjectTime).format("YYYY-MM-DD")]);
                }
                else {
                  form.setFieldValue("visitTime", []);
                }
              },
            },
          },
          { name: "projectName", label: "项目名称", onlyForLabel: true },
          {
            name: "jurisdictionalCorpId",
            label: "区域管辖单位",
            render: (
              <DepartmentSelectTree
                searchType="inType"
                params={{ enterpriseType: [2] }}
                onChange={(value) => {
                  if (value) {
                    getEnclosedAreaList(value);
                    getApprovalUserListAll(value);
                  }
                  else {
                    setEnclosedAreaList([]);
                    setApprovalUserListAll([]);
                  }
                  form.setFieldValue("closedAreaId", "");
                }}
                onGetLabel={label => form.setFieldValue("jurisdictionalCorpName", label)}
              />
            ),
          },
          { name: "jurisdictionalCorpName", label: "区域管辖单位名称", onlyForLabel: true },
          {
            name: "closedAreaId",
            label: "封闭区域",
            render: (
              <BasicSelectTree
                treeData={enclosedAreaList}
                placeholder="封闭区域"
                onGetLabel={label => form.setFieldValue("closedAreaName", label)}
                nameKey="closedAreaName"
              />
            ),
          },
          { name: "closedAreaName", label: "封闭区域名称", onlyForLabel: true },
          {
            name: "auditPersonUserId",
            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);
                console.log(item);
                form.setFieldValue("auditPersonUserName", item.userName);
                form.setFieldValue("auditPersonCorpId", item.corpId);
                form.setFieldValue("auditPersonCorpName", item.corpName);
                form.setFieldValue("auditPersonDepartmentId", item.deptId);
                form.setFieldValue("auditPersonDepartmentName", item.deptName);
              },
            },
          },
          { name: "auditPersonUserName", label: "审核人员名称", onlyForLabel: true },
          { name: "auditPersonCorpId", label: "审核企业ID", onlyForLabel: true },
          { name: "auditPersonCorpName", label: "审核企业名称", onlyForLabel: true },
          { name: "auditPersonDepartmentId", label: "审核部门ID", onlyForLabel: true },
          { name: "auditPersonDepartmentName", label: "审核部门名称", onlyForLabel: true },
          {
            name: "visitTime",
            label: "申请时间范围",
            render: FORM_ITEM_RENDER_ENUM.DATE_RANGE,
            componentProps: { disabled: props.entrance === "stakeholder" },
          },
          {
            label: "随行人员",
            span: 24,
            customizeRender: true,
            render: (
              <Table
                style={{ marginBottom: 16 }}
                headerTitle={(
                  <span style={{
                    color: "red",
                    fontSize: "14px",
                  }}
                  >
                    如需选择的人员无法添加或查询不到，请确认该人员在集团人资系统入职状态是否正常或人脸照片是否上传。
                  </span>
                )}
                toolBarRender={() => (
                  <Button
                    type="primary"
                    onClick={() => {
                      if (props.entrance === "stakeholder" && !form.getFieldValue("projectId")) {
                        message.warning("请先选择项目");
                        return;
                      }
                      setSelectEntourageModalVisible(true);
                    }}
                  >
                    添加随行人员
                  </Button>
                )}
                options={false}
                disabledResizer={true}
                pagination={false}
                columns={[
                  { title: "姓名", dataIndex: "name", render: (_, record) => record.name || record.userName },
                  { title: "部门", dataIndex: "deptName" },
                  {
                    title: "操作",
                    render: (_, record) => (
                      <Button
                        type="link"
                        danger
                        onClick={() => {
                          setEntourageList(entourageList.filter(item => item.userId !== record.userId));
                        }}
                      >
                        删除
                      </Button>
                    ),
                  },
                ]}
                dataSource={entourageList}
              />
            ),
          },
          { name: "applyReason", label: "申请原因", span: 24, render: FORM_ITEM_RENDER_ENUM.TEXTAREA },
          {
            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 },
        ]}
        form={form}
      />
      {
        selectEntourageModalVisible && (
          <SelectEntourageModal
            entourageList={entourageList}
            entrance={props.entrance}
            projectId={form.getFieldValue("projectId")}
            onClose={() => {
              setSelectEntourageModalVisible(false);
            }}
            onOk={(values) => {
              setEntourageList(values);
              setSelectEntourageModalVisible(false);
            }}
          />
        )
      }
      {
        needToKnowModalVisible && (
          <NeedToKnowModal
            signatureUrl={signatureUrl.current}
            onCancel={() => {
              setNeedToKnowModalVisible(false);
            }}
            onOk={(values) => {
              form.setFieldValue("informSignFile", values.file);
              signatureUrl.current = values.base64;
              setNeedToKnowModalVisible(false);
            }}
          />
        )
      }
    </Page>
  );
}

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

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

  const [form] = Search.useForm();
  const {
    tableProps,
    getData,
  } = useTable(props[props.entrance === "stakeholder" ? "xgfProjectUserGetPeopleProject" : "enclosedAreaPersonnelApplyEntourageList"], {
    form,
    useStorageQueryCriteria: false,
    params: () => {
      if (props.entrance === "stakeholder") {
        return { id: props.projectId };
      }
      else {
        let personBelongType = 1;
        if (props.entrance === "enterprise")
          personBelongType = 2;
        return { personBelongType };
      }
    },
  });

  return (
    <Modal
      title="选择随行人员"
      open
      maskClosable={false}
      width={800}
      onCancel={props.onClose}
      onOk={() => {
        props.onOk(selectedRowsRef.current);
      }}
    >
      <Search
        options={[
          { name: "name", label: "姓名" },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        rowKey="userId"
        rowSelection={{
          selectedRowKeys,
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRowKeys(selectedRowKeys);
            selectedRowsRef.current = selectedRows;
          },
        }}
        options={false}
        disabledResizer={true}
        columns={[
          { title: "部门", dataIndex: "deptName" },
          { title: "姓名", dataIndex: "name", render: (_, record) => record.name || record.userName },
          { title: "手机号", dataIndex: "phone" },
          { title: "是否录入人脸", dataIndex: "userFaceUrl", render: (_, record) => record.userFaceUrl ? "是" : "否" },
        ]}
        {...tableProps}
        dataSource={(tableProps.dataSource || []).filter(item => item.userFaceUrl)}
      />
    </Modal>
  );
};

const SelectEntourageModal = Connect([NS_ENCLOSED_AREA_PERSONNEL_APPLY, NS_ENCLOSED_AREA], true)(SelectEntourageModalComponent);

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