import { CameraOutlined } from "@ant-design/icons";
import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, Divider, message, Modal, QRCode, Space, Spin } from "antd";
import { useEffect, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
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_FIRST_LEVEL_DOOR_INFO, NS_TEMPORARY_VEHICLE, NS_VEHICLE_APPLY, NS_VEHICLE_AUDIT } from "~/enumerate/namespace";
import {UseDecodeIdCard} from "~/utils";

function List(props) {
  const [qrCodeModalVisible, setQrCodeModalVisible] = useState(false);
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [approvalDetailsModalVisible, setApprovalDetailsModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [vehicleApplyId, setCurrentVehicleApplyId] = useState("");
  const [firstLevelDoorInfoListAll, setFirstLevelDoorInfoListAll] = useState([]);

  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["vehicleAuditList"], {
    form,
    params: { processOrRecord: !props.isRecords ? 1 : 2,vehicleBelongType: props.vehicleBelongType ? props.vehicleBelongType :""},
  });
  const getFirstLevelDoorInfoListAll = async () => {
    const { data } = await props["firstLevelDoorInfoListAll"]({ mkmjLevel: 1 });
    setFirstLevelDoorInfoListAll(data);
  };
  useEffect(() => {
    getFirstLevelDoorInfoListAll();
  }, []);

  return (
    <Page isShowAllAction={false}>
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "employeeVehicleUserName", label: "访问人姓名" },
          { name: "licenceNo", label: "车牌号" },
          { name: "visitStartTime", label: "访问开始时间", render: FORM_ITEM_RENDER_ENUM.DATE },
          { name: "visitEndTime", label: "访问结束时间", render: FORM_ITEM_RENDER_ENUM.DATE },
          { name: "processOrRecord", label: "审批状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: VEHICLE_AUDIT_STATUS_ENUM },
          {
            name: "gateLevelAuthAreaId",
            label: "访问口门名称",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: firstLevelDoorInfoListAll,
            itemsField: { labelKey: "mkmjName", valueKey: "id" },
          },
        ]}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {(!props.isRecords && props.permission(props.addBtn || "jgd-entry-temp-vehicle-add")) && (
              <Button
                type="primary"
                icon={(<AddIcon />)}
                onClick={() => {
                  props.history.push("./add");
                }}
              >
                新增
              </Button>
            )}
            {!props.isRecords && (
              <Button
                type="primary"
                icon={(<CameraOutlined />)}
                onClick={() => {
                  setQrCodeModalVisible(true);
                }}
                ghost
              >
                访客二维码
              </Button>
            )}
          </Space>
        )}
        columns={[
          { title: "访问人姓名", dataIndex: "employeeVehicleUserName" },
          { title: "手机号", dataIndex: "lsUserPhone" },
          { title: "身份证号", dataIndex: "lsUserIdcard",render: (_, record) =>  UseDecodeIdCard(record.lsUserIdcard), },
          { title: "车牌号", dataIndex: "licenceNo" },
          { title: "车牌类型", dataIndex: "licenceTypeName" },
          { title: "车辆类型", dataIndex: "vehicleTypeName" },
          { title: "来访事由", dataIndex: "reasonVisit" },
          { title: "访问起始时间", dataIndex: "visitStartTime" },
          { title: "访问结束时间", dataIndex: "visitEndTime" },
          { title: "访问口门名称", dataIndex: "mkmjName" },
          {
            title: "审批状态",
            dataIndex: "auditStatus",
            render: (_, record) => getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: record.auditStatus }),
          },
          {
            title: "操作",
            width: 200,
            render: (_, record) => (
              <Space>
                {props.permission(props.viewBtn || "jgd-entry-temp-vehicle-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      props.history.push(`./view?id=${record.vehicleApplyId}`);
                    }}
                  >
                    查看
                  </Button>
                )}
                {/* {props.permission(props.auditInfoBtn || "jgd-entry-temp-vehicle-audit-info") && ( */}
                {/*  <Button */}
                {/*    type="link" */}
                {/*    onClick={() => { */}
                {/*      setApprovalDetailsModalVisible(true); */}
                {/*      setCurrentId(record.id); */}
                {/*      setCurrentVehicleApplyId(record.vehicleApplyId); */}
                {/*    }} */}
                {/*  > */}
                {/*    审批详情 */}
                {/*  </Button> */}
                {/* )} */}
                {(!props.isRecords && record.currentUserCanAudit === 1 && props.permission(props.auditBtn || "jgd-entry-temp-vehicle-audit")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setReviewModalVisible(true);
                      setCurrentId(record.id);
                      setCurrentVehicleApplyId(record.vehicleApplyId);
                    }}
                  >
                    审核
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        qrCodeModalVisible && (
          <QrCodeModal
            onCancel={() => {
              setQrCodeModalVisible(false);
              setCurrentId("");
            }}
          />
        )
      }
      {
        reviewModalVisible && (
          <ReviewModal
            id={currentId}
            vehicleApplyId={vehicleApplyId}
            onCancel={() => {
              setReviewModalVisible(false);
              setCurrentId("");
            }}
            getData={getData}
          />
        )
      }
      {
        approvalDetailsModalVisible && (
          <ApprovalDetailsModal
            id={currentId}
            vehicleApplyId={vehicleApplyId}
            onCancel={() => {
              setApprovalDetailsModalVisible(false);
              setCurrentId("");
            }}
          />
        )
      }
    </Page>
  );
}

const QrCodeModal = (props) => {
  return (
    <Modal
      title="访客二维码"
      open
      width={600}
      maskClosable={false}
      onCancel={props.onCancel}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <div style={{ textAlign: "center" }}>
        <QRCode value={`${window.location.origin}/primeport-h5/container/mobile/firstLevelDoor/personnelApplication/apply`} style={{ margin: "0 auto", marginBottom: 10 }} />
        <div>温馨提示：此二维码支持临时入港申请预约及预约结果查询</div>
      </div>
    </Modal>
  );
};

const ReviewModalComponent = (props) => {
  const [form] = FormBuilder.useForm();
  const { loading: getFileLoading, getFile } = useGetFile();

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

  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();
  }, []);

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

  return (
    <Modal
      title="审核"
      open
      width={600}
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={form.submit}
      confirmLoading={props.vehicleAudit.vehicleAuditLoading || getFileLoading}
    >
      <Spin spinning={props.vehicleAudit.vehicleAuditLoading || getFileLoading}>
        <Divider orientation="left">申请信息</Divider>
        <Descriptions
          column={1}
          bordered
          styles={{ label: { width: 200 } }}
          items={[
            { label: "访问人姓名", children: info.employeeVehicleUserName },
            { label: "手机号", children: info.lsUserPhone },
            { label: "身份证号", children: info.lsUserIdcard },
            { label: "车牌号", children: info.licenceNo },
            { label: "车牌类型", children: info.licenceTypeName },
            { label: "车辆类型", children: info.vehicleTypeName },
            { label: "访问开始时间", children: info.visitStartTime },
            { label: "访问结束时间", children: info.visitEndTime },
            {
              label: "访问港区",
              children: info.gateLevelAuthArea && JSON.parse(info.gateLevelAuthArea).area.map(item => item.value).join("、"),
            },
            { label: "访问口门名称", children: info.mkmjName },
            { label: "来访事由", children: info.reasonVisit },
            { label: "行驶证照片", children: (<PreviewImg files={info.drivingLicenseFile} />) },
            { label: "车辆照片", children: (<PreviewImg files={info.attachmentFile} />) },
            { label: "申请人安全告知签字", children: (<PreviewImg files={info.informSignFile} />) },
          ]}
        />
        <Divider orientation="left">审批信息</Divider>
        <FormBuilder
          form={form}
          onFinish={onSubmit}
          showActionButtons={false}
          labelCol={{ span: 10 }}
          span={24}
          values={{
            auditStatus: "2",
          }}
          options={[
            {
              name: "auditStatus",
              label: "是否通过",
              render: FORM_ITEM_RENDER_ENUM.RADIO,
              items: [{ bianma: "2", name: "通过" }, { bianma: "3", name: "不通过" }],
            },
            {
              name: "remarks",
              label: "不通过原因",
              render: FORM_ITEM_RENDER_ENUM.TEXTAREA,
              dependencies: ["auditStatus"],
              hidden: formValues => !(formValues.auditStatus === "3"),
            },
          ]}
        />
      </Spin>
    </Modal>
  );
};

const ApprovalDetailsModalComponent = (props) => {
  const [list, setList] = useState([]);

  const getData = async () => {
    // TODO
    const { data } = await props["temporaryVehicleReviewList"]({ id: props.id });
    setList(data);
  };

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

  return (
    <Modal
      title="审批详情"
      open
      width={800}
      maskClosable={false}
      onCancel={props.onCancel}
      loading={props.temporaryVehicle.temporaryVehicleLoading}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <style>
        {`
          .step {
            display:flex;
            gap:20px;
            margin-top:10px;
          }
          .index {
            border:1px solid #000;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .info {
            flex:1;
            border:1px solid #ccc;
            border-radius: 4px;
            padding:10px 20px;
          }
        `}
      </style>
      <div className="steps">
        {
          list.map((item, index) => (
            <div className="step" key={index}>
              <div className="index">{index + 1}</div>
              <div className="info">
                <div>
                  <span>审批人：</span>
                  <span>{item.user}</span>
                </div>
                <div>
                  <span>审批人公司：</span>
                  <span>{item.corpInfo}</span>
                </div>
                <div>
                  <span>审批人部门：</span>
                  <span>{item.department}</span>
                </div>
                <div>
                  <span>审批状态：</span>
                  <span>{getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: item.status })}</span>
                </div>
              </div>
            </div>
          ))
        }
      </div>
    </Modal>
  );
};

const ReviewModal = Connect([NS_VEHICLE_AUDIT, NS_VEHICLE_APPLY], true)(ReviewModalComponent);
const ApprovalDetailsModal = Connect([NS_TEMPORARY_VEHICLE], true)(ApprovalDetailsModalComponent);

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