import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, Modal } from "antd";
import { useEffect, useState } from "react";
import Page from "zy-react-library/components/Page";
import PreviewImg from "zy-react-library/components/PreviewImg";
import Table from "zy-react-library/components/Table";
import { UPLOAD_FILE_TYPE_ENUM } from "zy-react-library/enum/uploadFile/gwj";
import useGetFile from "zy-react-library/hooks/useGetFile";
import useGetUrlQuery from "zy-react-library/hooks/useGetUrlQuery";
import useTable from "zy-react-library/hooks/useTable";
import { getLabelName } from "zy-react-library/utils";
import { VEHICLE_AUDIT_STATUS_ENUM, VEHICLE_TYPE_ENUM } from "~/enumerate/constant";
import { NS_VEHICLE_AUDIT } from "~/enumerate/namespace";

function ApprovalRecords(props) {
  const [currentId, setCurrentId] = useState("");
  const [infoModalVisible, setInfoModalVisible] = useState(false);

  const query = useGetUrlQuery();
  const { tableProps } = useTable(props["vehicleAuditRecordsList"], {
    params: { vehicleApplyId: query.id },
  });

  return (
    <Page headerTitle="审批记录">
      <Table
        columns={[
          { title: "发起人", dataIndex: "applyUserName" },
          { title: "发起时间", dataIndex: "applyTime" },
          { title: "审批人", dataIndex: "auditUserName" },
          { title: "审批时间", dataIndex: "auditTime" },
          {
            title: "审批状态",
            dataIndex: "auditStatus",
            render: (_, record) => getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: record.auditStatus }),
          },
          { title: "打回原因", dataIndex: "remarks" },
          { title: "类型", dataIndex: "batchState", render: (_, record) => record.batchState === 1 ? "申请" : "更新" },
          {
            title: "操作",
            fixed: "right",
            width: 150,
            render: (_, record) => (
              <Button
                type="link"
                onClick={() => {
                  setInfoModalVisible(true);
                  setCurrentId(record.id);
                }}
              >
                车辆信息记录
              </Button>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        infoModalVisible && (
          <InfoModal
            id={currentId}
            onCancel={() => {
              setInfoModalVisible(false);
              setCurrentId("");
            }}
          />
        )
      }
    </Page>
  );
}

const InfoModalComponent = (props) => {
  const { getFile } = useGetFile();

  const [changeAfter, setChangeAfter] = useState({});
  const [changeBefore, setChangeBefore] = useState({});
  const [batchState, setBatchState] = useState(1);

  const getData = async () => {
    const { data } = await props["vehicleAuditInfo"]({ id: props.id });
    const changeAfter = data.changeAfter ? JSON.parse(data.changeAfter) : {};
    const changeBefore = data.changeBefore ? JSON.parse(data.changeBefore) : {};
    const changeAfterDrivingLicenseFile = await getFile({
      eqType: UPLOAD_FILE_TYPE_ENUM[601],
      eqForeignKey: changeAfter.drivingLicenseId,
    });
    const changeAfterAttachmentFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[602], eqForeignKey: changeAfter.attachmentId });
    setChangeAfter({
      ...changeAfter,
      drivingLicenseFile: changeAfterDrivingLicenseFile,
      attachmentFile: changeAfterAttachmentFile,
    });
    if (changeBefore && Object.keys(changeBefore).length > 0) {
      const changeBeforeDrivingLicenseFile = await getFile({
        eqType: UPLOAD_FILE_TYPE_ENUM[601],
        eqForeignKey: changeBefore.drivingLicenseId,
      });
      const changeBeforeAttachmentFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[602], eqForeignKey: changeBefore.attachmentId });
      setChangeBefore({
        ...changeBefore,
        drivingLicenseFile: changeBeforeDrivingLicenseFile,
        attachmentFile: changeBeforeAttachmentFile,
      });
    }
    setBatchState(data.batchState);
  };

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

  return (
    <Modal
      open
      title="车辆信息记录"
      width={800}
      maskClosable={false}
      onCancel={props.onCancel}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      {
        batchState === 1
          ? (
              <Descriptions
                column={1}
                bordered
                styles={{ label: { width: 200 } }}
                items={[
                  { label: "车辆所属类型", children: getLabelName({ list: VEHICLE_TYPE_ENUM, status: changeAfter.vehicleBelongType }) },
                  { label: "车辆所属部门", children: changeAfter.vehicleDepartmentName },
                  ...(changeAfter.vehicleBelongType === 1 ? [{ label: "车辆归属人", children: changeAfter.employeeVehicleUserName }] : []),
                  { label: "车牌号", children: changeAfter.licenceNo },
                  { label: "车牌类型", children: changeAfter.licenceTypeName },
                  { label: "车辆类型", children: changeAfter.vehicleTypeName },
                  { label: "访问港区范围", children: changeAfter.gateLevelAuthArea && JSON.parse(changeAfter.gateLevelAuthArea).area.map(item => item.value).join("、") },
                  { label: "访问开始时间", children: changeAfter.visitStartTime },
                  { label: "访问结束时间", children: changeAfter.visitEndTime },
                  { label: "行驶证照片", children: (<PreviewImg files={changeAfter.drivingLicenseFile} />) },
                  { label: "车辆照片", children: (<PreviewImg files={changeAfter.attachmentFile} />) },
                  { label: "审批人", children: changeAfter.auditUserName },
                ]}
              />
            )
          : (
              <div>
                <style>
                  {`
                    .comparison-table {
                      width: 100%;
                      border-collapse: collapse;
                    }
                    .comparison-table th,
                    .comparison-table td {
                      border: 1px solid #d9d9d9;
                      padding: 8px;
                      text-align: center;
                    }
                    .comparison-table th {
                      background-color: #f5f5f5;
                    }
                    .comparison-table .name-col {
                      width: 20%;
                    }
                    .comparison-table .before-col {
                      width: 40%;
                    }
                    .comparison-table .after-col {
                      width: 40%;
                    }
                  `}
                </style>
                <table className="comparison-table">
                  <thead>
                    <tr>
                      <th className="name-col">名称</th>
                      <th className="before-col">变更前</th>
                      <th className="after-col">变更后</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <th>车辆所属类型</th>
                      <td>{getLabelName({ list: VEHICLE_TYPE_ENUM, status: changeBefore.vehicleBelongType })}</td>
                      <td>{getLabelName({ list: VEHICLE_TYPE_ENUM, status: changeAfter.vehicleBelongType })}</td>
                    </tr>
                    <tr>
                      <th>车辆所属部门</th>
                      <td>{changeBefore.vehicleDepartmentName}</td>
                      <td>{changeAfter.vehicleDepartmentName}</td>
                    </tr>
                    {changeBefore.vehicleBelongType === 1 && (
                      <tr>
                        <th>车辆归属人</th>
                        <td>{changeBefore.employeeVehicleUserName}</td>
                        <td>{changeAfter.employeeVehicleUserName}</td>
                      </tr>
                    )}
                    <tr>
                      <th>车牌号</th>
                      <td>{changeBefore.licenceNo}</td>
                      <td>{changeAfter.licenceNo}</td>
                    </tr>
                    <tr>
                      <th>车牌类型</th>
                      <td>{changeBefore.licenceTypeName}</td>
                      <td>{changeAfter.licenceTypeName}</td>
                    </tr>
                    <tr>
                      <th>车辆类型</th>
                      <td>{changeBefore.vehicleTypeName}</td>
                      <td>{changeAfter.vehicleTypeName}</td>
                    </tr>
                    <tr>
                      <th>访问港区范围</th>
                      <td>{changeBefore.gateLevelAuthArea && JSON.parse(changeBefore.gateLevelAuthArea).area.map(item => item.value).join("、")}</td>
                      <td>{changeAfter.gateLevelAuthArea && JSON.parse(changeAfter.gateLevelAuthArea).area.map(item => item.value).join("、")}</td>
                    </tr>
                    <tr>
                      <th>访问开始时间</th>
                      <td>{changeBefore.visitStartTime}</td>
                      <td>{changeAfter.visitStartTime}</td>
                    </tr>
                    <tr>
                      <th>访问结束时间</th>
                      <td>{changeBefore.visitEndTime}</td>
                      <td>{changeAfter.visitEndTime}</td>
                    </tr>
                    <tr>
                      <th>行驶证照片</th>
                      <td><PreviewImg files={changeBefore.drivingLicenseFile} /></td>
                      <td><PreviewImg files={changeAfter.drivingLicenseFile} /></td>
                    </tr>
                    <tr>
                      <th>车辆照片</th>
                      <td><PreviewImg files={changeBefore.attachmentFile} /></td>
                      <td><PreviewImg files={changeAfter.attachmentFile} /></td>
                    </tr>
                    <tr>
                      <th>审批人</th>
                      <td>{changeBefore.auditUserName}</td>
                      <td>{changeAfter.auditUserName}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            )
      }
    </Modal>
  );
};

const InfoModal = Connect([NS_VEHICLE_AUDIT], true)(InfoModalComponent);

export default Connect([NS_VEHICLE_AUDIT], true)(ApprovalRecords);
