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 { VEHICLE_AUDIT_STATUS_ENUM } from "~/enumerate/constant";
import { NS_VEHICLE_APPLY, NS_VEHICLE_AUDIT } from "~/enumerate/namespace";

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

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

  return (
    <Page isShowAllAction={false}>
      <Search
        labelCol={{ span: 4 }}
        options={[
          { name: "licenceNo", label: "车牌号" },
          { name: "projectName", label: "项目名称" },
          {
            name: "auditStatus",
            label: "审核状态",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: VEHICLE_AUDIT_STATUS_ENUM,
            hidden: !props.isRecords,
          },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {(!props.isRecords && props.permission("xgf-stk-vehicle-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: "vehicleTypeName" },
          { title: "车牌类型", dataIndex: "licenceTypeName" },
          { title: "车牌号", dataIndex: "licenceNo" },
          {
            title: "审批状态",
            dataIndex: "auditStatus",
            render: (_, record) => getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: record.auditStatus }),
          },
          {
            title: "操作",
            width: 150,
            fixed: "right",
            render: (_, record) => (
              <Space>
                {props.permission(props.viewBtn || "xgf-stk-vehicle-application-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewModalVisible(true);
                      setCurrentId(record.vehicleApplyId);
                    }}
                  >
                    查看
                  </Button>
                )}
                {(record.auditStatus === 3 && props.permission(props.viewReasonsRefusalBtn || "xgf-stk-vehicle-application-show-reasons-refusal")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewRejectReasonModalVisible(true);
                      setCurrentRemarks(record.remarks);
                    }}
                  >
                    查看原因
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        viewRejectReasonModalVisible && (
          <ViewRejectReasonModal
            remarks={currentRemarks}
            onCancel={() => {
              setViewRejectReasonModalVisible(false);
              setCurrentRemarks("");
            }}
          />
        )
      }
      {
        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.remarks },
        ]}
      />
    </Modal>
  );
};

const ViewModalComponent = (props) => {
  const [info, setInfo] = useState({});
  const { loading: getFileLoading, getFile } = useGetFile();

  const getData = async () => {
    const { data } = await props["vehicleApplyInfo"]({ id: props.id });

    const drivingLicenseFile = await getFile({
      eqType: UPLOAD_FILE_TYPE_ENUM[601],
      eqForeignKey: data.drivingLicenseId,
    });
    const attachmentFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[602], eqForeignKey: data.attachmentId });
    const informSignFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[606], eqForeignKey: data.informSignId });
    const arr = []
    if(data.vehicleAuditLogList && data.vehicleAuditLogList.length > 0) {
      data.vehicleAuditLogList.forEach(item => {
        arr.push(item.auditUserName)
      })
    }
    data.auditUserName = arr.join(',');
    setInfo({
      ...data,
      drivingLicenseFile,
      attachmentFile,
      informSignFile,
    });
  };

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

  return (
    <Modal
      open
      title="查看"
      maskClosable={false}
      onCancel={props.onCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
      loading={props.vehicleApply.vehicleApplyLoading || getFileLoading}
    >
      <Divider orientation="left">申请信息</Divider>
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "项目名称", children: info.projectName },
          { label: "时间范围", children: `${info.visitStartTime}-${info.visitStartTime}` },
          {
            label: "地域范围",
            children: info.gateLevelAuthArea && JSON.parse(info.gateLevelAuthArea).area.map(item => item.value).join("、"),
          },
          { label: "驾驶人员", children: info.drivingUserName },
          { label: "车辆类型", children: info.vehicleTypeName },
          { label: "车牌类型", children: info.licenceTypeName },
          { label: "车牌号", children: info.licenceNo },
          { label: "审核人员", children: info.auditUserName },
          { label: "车辆照片", children: (<PreviewImg files={info.drivingLicenseFile} />) },
          { label: "车辆行驶证照片", children: (<PreviewImg files={info.attachmentFile} />) },
          { label: "申请人签字", children: (<PreviewImg files={info.informSignFile} />) },
        ]}
      />
    </Modal>
  );
};

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

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