import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, Divider, message, Modal, Space, Spin } 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, getMatchedItems } from "zy-react-library/utils";
import { VEHICLE_AUDIT_STATUS_ENUM } from "~/enumerate/constant";
import { NS_VEHICLE_AUDIT } from "~/enumerate/namespace";

function RelatedVehicles(props) {
  const [currentId, setCurrentId] = useState("");
  const [currentVehicleApplyId, setCurrentVehicleApplyId] = useState("");
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [viewRejectReasonModalVisible, setViewRejectReasonModalVisible] = useState(false);
  const [remarks, setRemarks] = useState("");

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

  return (
    <Page isShowAllAction={false}>
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "licenceNo", label: "车牌号" },
          { name: "projectName", label: "项目名称" },
        ]}
      />
      <Table
        columns={[
          { dataIndex: "projectName", title: "项目名称" },
          {
            dataIndex: "gateLevelAuthArea",
            title: "区域范围",
            render: (_, record) => record.gateLevelAuthArea && JSON.parse(record.gateLevelAuthArea).area.map(item => item.value).join("、"),
          },
          {
            dataIndex: "visitStartTime",
            title: "访问期限",
            render: (_, record) =>`${record.visitStartTime}至${record.visitEndTime}`,
          },
          { dataIndex: "vehicleTypeName", title: "车辆类型" },
          { dataIndex: "licenceTypeName", title: "车牌类型" },
          { dataIndex: "licenceNo", title: "车牌号" },
          {
            dataIndex: "auditStatus",
            title: "审核状态",
            render: (_, record) => getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: record.auditStatus }),
          },
          {
            title: "操作",
            width: 150,
            render: (_, record) => (
              <Space>
                {(!props.isRecords && record.currentUserCanAudit === 1 && props.permission(props.auditBtn || "jgd-entry-stk-vehicle-approval-audit")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setReviewModalVisible(true);
                      setCurrentId(record.id);
                      setCurrentVehicleApplyId(record.vehicleApplyId);
                    }}
                  >
                    审核
                  </Button>
                )}
                {props.permission(props.viewBtn || "jgd-entry-stk-vehicle-approval-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setInfoModalVisible(true);
                      setCurrentId(record.id);
                      setCurrentVehicleApplyId(record.vehicleApplyId);
                    }}
                  >
                    查看
                  </Button>
                )}
                {(record.auditStatus === 3 && props.permission(props.viewReasonsRefusalBtn || "jgd-entry-stk-vehicle-approval-show-reasons-refusal")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewRejectReasonModalVisible(true);
                      setRemarks(record.remarks);
                    }}
                  >
                    查看原因
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        reviewModalVisible && (
          <ReviewModal
            id={currentId}
            vehicleApplyId={currentVehicleApplyId}

            onCancel={() => {
              setReviewModalVisible(false);
              setCurrentId("");
              setCurrentVehicleApplyId("");
            }}
            getData={getData}
          />
        )
      }
      {
        infoModalVisible && (
          <InfoModal
            id={currentId}
            vehicleApplyId={currentVehicleApplyId}
            onCancel={() => {
              setInfoModalVisible(false);
              setCurrentId("");
              setCurrentVehicleApplyId("");
            }}
          />
        )
      }
      {
        viewRejectReasonModalVisible && (
          <ViewRejectReasonModal
            remarks={remarks}
            onCancel={() => {
              setViewRejectReasonModalVisible(false);
              setRemarks("");
            }}
          />
        )
      }
    </Page>
  );
}

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

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

  return (
    <Modal
      open
      title="审核"
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={form.submit}
      width={800}
      confirmLoading={props.vehicleAudit.vehicleAuditLoading}
    >
      <Spin spinning={props.vehicleAudit.vehicleAuditLoading}>
        <PublicInfoModal id={props.id} vehicleApplyId={props.vehicleApplyId} />
        <FormBuilder
          form={form}
          onFinish={onSubmit}
          labelCol={{ span: 8 }}
          span={24}
          values={{
            auditStatus: "2",
          }}
          showActionButtons={false}
          options={[
            {
              name: "auditStatus",
              label: "是否通过审核",
              render: FORM_ITEM_RENDER_ENUM.RADIO,
              items: getMatchedItems({ list: VEHICLE_AUDIT_STATUS_ENUM, value: ["2", "3"] }),
            },
            {
              name: "remarks",
              label: "驳回原因",
              render: FORM_ITEM_RENDER_ENUM.TEXTAREA,
              dependencies: ["auditStatus"],
              hidden: formValues => !(formValues.auditStatus === "3"),
            },
          ]}
        />
      </Spin>
    </Modal>
  );
};

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 InfoModalComponent = (props) => {
  const [info, setInfo] = useState({});

  const { getFile } = useGetFile();

  const getData = async () => {
    const { data } = await props["vehicleApplyInfo"]({ id: props.vehicleApplyId });
    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 });
    setInfo({
      ...data,
      drivingLicenseFile,
      attachmentFile,
      informSignFile,
    });
  };

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

  return (
    <div>
      <Divider orientation="left">申请信息</Divider>
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "相关方名称", children: info.vehicleCorpName },
          { label: "项目名称", children: info.projectName },
          { label: "时间范围", children: `${info.visitStartTime}-${info.visitEndTime}` },
          { 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: (<PreviewImg files={info.attachmentFile} />) },
          { label: "车辆行驶证照片", children: (<PreviewImg files={info.drivingLicenseFile} />) },
          { label: "申请人签字", children: (<PreviewImg files={info.informSignFile} />) },
        ]}
      />
      {
        info.auditFlag !== 1 &&(
          <>
            <Divider orientation="left">审核信息</Divider>
            <Descriptions
              column={1}
              bordered
              styles={{ label: { width: 200 } }}
              items={[
                { label: "审核人员", children: info.currentAuditUserName },
                { label: "审核状态", children: getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: info.auditFlag }) },
                ...(info.auditFlag === 3 ? [{ label: "驳回原因", children: info.refusalReason }] : []),
                { label: "审核时间", children: info.currentAuditTime },

              ]}
            />
          </>
        )
      }

    </div>
  );
};

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} vehicleApplyId={props.vehicleApplyId} />
    </Modal>
  );
}

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