import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, Divider, message, Modal, Space } from "antd";
import { useEffect, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
import Page from "zy-react-library/components/Page";
import PreviewImg from "zy-react-library/components/PreviewImg";
import Search from "zy-react-library/components/Search";
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 useGetFile from "zy-react-library/hooks/useGetFile";
import useTable from "zy-react-library/hooks/useTable";
import { getLabelName } from "zy-react-library/utils";
import { NS_TEMPORARY_PERSONNEL } from "~/enumerate/namespace";

const STATUS_ENUM = [
  { bianma: "1", name: "审核中" },
  { bianma: "2", name: "通过" },
  { bianma: "3", name: "不通过" },
];

function RelatedPersonnel(props) {
  const [currentId, setCurrentId] = useState("");
  const [reasonsRefusal, setReasonsRefusal] = useState("");
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [viewRejectReasonModalVisible, setViewRejectReasonModalVisible] = useState(false);

  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["xgfPersonnelList"], {
    form,
    params: { processOrRecord: !props.isRecords ? 1 : 2 },
  });

  return (
    <Page isShowAllAction={false}>
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "employeePersonUserName", label: "姓名" },
          { name: "projectName", label: "项目名称" },
        ]}
      />
      <Table
        columns={[
          { title: "相关方名称", dataIndex: "applyCorpName" },
          { title: "项目名称", dataIndex: "projectName" },
          {
            title: "区域范围",
            dataIndex: "gateLevelAuthArea",
            render: (_, record) => record.gateLevelAuthArea && JSON.parse(record.gateLevelAuthArea).area.map(item => item.value).join("、"),
          },
          {
            title: "访问期限",
            dataIndex: "visitStartTime",
            render: (_, record) => `${record.visitStartTime}至${record.visitEndTime}`,
          },
          { title: "项目人员数", dataIndex: "personApplyCount" },
          { title: "申请时间", dataIndex: "applyTime" },
          {
            title: "审批状态",
            dataIndex: "auditFlag",
            render: (_, record) => getLabelName({ list: STATUS_ENUM, status: record.auditFlag }),
          },
          {
            title: "操作",
            width: 150,
            render: (_, record) => (
              <Space>
                {(!props.isRecords && record.currentUserCanAudit === 1 && props.permission(props.auditBtn || "jgd-entry-stk-personnel-approval-audit")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setReviewModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    审核
                  </Button>
                )}
                {props.permission(props.viewBtn || "jgd-entry-stk-personnel-approval-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setInfoModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    查看
                  </Button>
                )}
                {(record.auditFlag === 3 && props.permission(props.viewReasonsRefusalBtn || "jgd-entry-stk-personnel-approval-show-reasons-refusal")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewRejectReasonModalVisible(true);
                      setReasonsRefusal(record.reasonsRefusal);
                    }}
                  >
                    查看原因
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        reviewModalVisible && (
          <ReviewModal
            id={currentId}
            onCancel={() => {
              setReviewModalVisible(false);
              setCurrentId("");
            }}
            getData={getData}
          />
        )
      }
      {
        infoModalVisible && (
          <InfoModal
            id={currentId}
            onCancel={() => {
              setInfoModalVisible(false);
              setCurrentId("");
            }}
          />
        )
      }
      {
        viewRejectReasonModalVisible && (
          <ViewRejectReasonModal
            reasonsRefusal={reasonsRefusal}
            onCancel={() => {
              setViewRejectReasonModalVisible(false);
              setReasonsRefusal("");
            }}
          />
        )
      }
    </Page>
  );
}

const ReviewModalComponent = (props) => {
  const [form] = FormBuilder.useForm();

  const onSubmit = async (values) => {
    const { success } = await props["temporaryPersonnelReview"]({
      ...values,
      id: props.id,
    });
    if (success) {
      message.success("操作成功");
      props.getData();
      props.onCancel();
    }
  };

  return (
    <Modal
      open
      title="审核"
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={form.submit}
      width={800}
      confirmLoading={props.temporaryPersonnel.temporaryPersonnelLoading}
    >
      <PublicInfoModal id={props.id} />
      <FormBuilder
        form={form}
        onFinish={onSubmit}
        labelCol={{ span: 8 }}
        span={24}
        values={{
          auditFlag: "1",
        }}
        showActionButtons={false}
        options={[
          {
            name: "auditFlag",
            label: "是否通过审核",
            render: FORM_ITEM_RENDER_ENUM.RADIO,
            items: [{ bianma: "2", name: "通过" }, { bianma: "3", name: "不通过" }],
          },
          {
            name: "reasonsRefusal",
            label: "驳回原因",
            render: FORM_ITEM_RENDER_ENUM.TEXTAREA,
            dependencies: ["auditFlag"],
            hidden: formValues => !(formValues.auditFlag === "3"),
          },
        ]}
      />
    </Modal>
  );
};

const InfoModalComponent = (props) => {
  const [info, setInfo] = useState({});

  const { getFile } = useGetFile();

  const getData = async () => {
    const { data } = await props["temporaryPersonnelInfo"]({ id: props.id });
    const informSignFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[611], eqForeignKey: data.informSignId });
    setInfo({
      ...data,
      informSignFile,
    });
  };

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

  return (
    <div>
      <Divider orientation="left">申请信息</Divider>
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "相关方名称", children: info.applyCorpName },
          { label: "项目名称", children: info.projectName },
          {
            label: "区域范围",
            children: info.gateLevelAuthArea && JSON.parse(info.gateLevelAuthArea).area.map(item => item.value).join("、"),
          },
          { label: "访问期限", children: `${info.visitStartTime}至${info.visitEndTime}` },
          { label: "项目人员数", children: info.personApplyCount },
          { label: "申请时间", children: info.applyTime },
          { label: "申请状态", children: getLabelName({ list: STATUS_ENUM, status: info.auditFlag }) },
          { label: "申请人签字", children: (<PreviewImg files={info.informSignFile} />) },
        ]}
      />
      <Divider orientation="left">人员信息</Divider>
      <Table
        options={false}
        disabledResizer={true}
        columns={[
          { title: "姓名", dataIndex: "employeePersonUserName" },
          { title: "部门", dataIndex: "personDepartmentName" },
          // { title: "是否培训", dataIndex: "todo3" },
        ]}
        pagination={false}
        dataSource={info.personApplyList}
      />
    </div>
  );
};

const ViewRejectReasonModal = (props) => {
  return (
    <Modal
      open
      title="驳回原因"
      maskClosable={false}
      onCancel={props.onCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "驳回原因", children: props.reasonsRefusal },
        ]}
      />
    </Modal>
  );
};

function InfoModal(props) {
  return (
    <Modal
      open
      title="查看"
      maskClosable={false}
      onCancel={props.onCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <PublicInfoModal id={props.id} />
    </Modal>
  );
}

const ReviewModal = Connect([NS_TEMPORARY_PERSONNEL], true)(ReviewModalComponent);
const PublicInfoModal = Connect([NS_TEMPORARY_PERSONNEL], true)(InfoModalComponent);
export default Connect([NS_TEMPORARY_PERSONNEL], true)(Permission(RelatedPersonnel));
