import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, Divider, Modal, Space } from "antd";
import { useEffect, useState } from "react";
import AddIcon from "zy-react-library/components/Icon/AddIcon";
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 { ENCLOSED_AREA_AUDIT_STATUS_ENUM } from "~/enumerate/constant";
import { NS_PERSONNEL_APPLICATION } from "~/enumerate/namespace";

function List(props) {
  const [currentId, setCurrentId] = useState("");
  const [reasonsRefusal, setCurrentReasonsRefusal] = useState("");
  const [viewRejectReasonModalVisible, setViewRejectReasonModalVisible] = useState(false);
  const [viewModalVisible, setViewModalVisible] = useState(false);

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

  return (
    <Page isShowAllAction={false}>
      <Search
        labelCol={{ span: 4 }}
        options={[
          { name: "employeePersonUserName", label: "姓名" },
          { name: "projectName", label: "项目名称" },
          {
            name: "auditFlag",
            label: "审核状态",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: ENCLOSED_AREA_AUDIT_STATUS_ENUM,
            hidden: !props.isRecords,
          },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {(!props.isRecords && props.permission("xgf-stk-personnel-application-add")) && (
              <Button
                type="primary"
                icon={(<AddIcon />)}
                onClick={() => {
                  props.history.push("./add");
                }}
              >
                新增申请
              </Button>
            )}
          </Space>
        )}
        columns={[
          { 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: ENCLOSED_AREA_AUDIT_STATUS_ENUM, status: record.auditFlag }),
          },
          {
            title: "操作",
            width: 150,
            fixed: "right",
            render: (_, record) => (
              <Space>
                {props.permission(props.viewBtn || "xgf-stk-personnel-application-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    查看
                  </Button>
                )}
                {(record.auditFlag === 3 && props.permission(props.viewReasonsRefusalBtn || "xgf-stk-personnel-application-show-reasons-refusal")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewRejectReasonModalVisible(true);
                      setCurrentReasonsRefusal(record.reasonsRefusal);
                    }}
                  >
                    查看原因
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        viewRejectReasonModalVisible && (
          <ViewRejectReasonModal
            reasonsRefusal={reasonsRefusal}
            onCancel={() => {
              setViewRejectReasonModalVisible(false);
              setCurrentReasonsRefusal("");
            }}
          />
        )
      }
      {
        viewModalVisible && (
          <ViewModal
            id={currentId}
            onCancel={() => {
              setViewModalVisible(false);
              setCurrentId("");
            }}
          />
        )
      }
    </Page>
  );
}

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>
  );
};

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

  const { loading: getFileLoading, getFile } = useGetFile();

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

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

  return (
    <Modal
      open
      title="查看"
      maskClosable={false}
      onCancel={props.onCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
      loading={props.personnelApplication.personnelApplicationLoading || getFileLoading}
    >
      <Divider orientation="left">申请信息</Divider>
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { 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.personApplyList?.length },
          { label: "申请时间", children: info.applyTime },
          { label: "申请状态", children: getLabelName({ list: ENCLOSED_AREA_AUDIT_STATUS_ENUM, status: info.auditFlag }) },
          ...(
              info.auditFlag === 3 ? [
                { label: "驳回原因", children: info.reasonsRefusal },
              ] :[]
          ),
          { label: "申请人签字", children: (<PreviewImg files={info.informSignFile} />) },
        ]}
      />

      <Divider orientation="left">人员信息</Divider>

      <Table
        options={false}
        disabledResizer={true}
        columns={[
          { title: "姓名", dataIndex: "employeePersonUserName" },
          { title: "部门", dataIndex: "personDepartmentName" },
          // { title: "是否培训", dataIndex: "trainingState" ,render: (_, record) => getLabelName({ list: TRAINING_STATE_ENUM, status: record.trainingState })},
          // { title: "现口门权限范围", dataIndex: "todo4" },
        ]}
        dataSource={info.personApplyList}
        pagination={false}
      />
    </Modal>
  );
};

const ViewModal = Connect([NS_PERSONNEL_APPLICATION], true)(ViewModalComponent);

export default Connect([NS_PERSONNEL_APPLICATION], true)(Permission(List));
