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 DictionarySelect from "zy-react-library/components/Select/Dictionary";
import DepartmentSelectTree from "zy-react-library/components/SelectTree/Department/Gwj";
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, VEHICLE_TYPE_ENUM } from "~/enumerate/constant";
import { NS_VEHICLE_AUDIT } from "~/enumerate/namespace";

function ShareVehicles(props) {
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [currentVehicleApplyId, setCurrentVehicleApplyId] = useState("");

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

  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: "vehicleDepartmentId", label: "车辆所属部门", render: (<DepartmentSelectTree />) },
          { name: "gateLevelAuthAreaId", label: "访问港区范围", render: (<DictionarySelect dictValue="HG_AUTH_AREA" />) },
        ]}
      />
      <Table
        columns={[
          {
            dataIndex: "vehicleTypeName",
            title: "车辆所属类型",
            render: (_, record) => getLabelName({ list: VEHICLE_TYPE_ENUM, status: record.vehicleBelongType }),
          },
          { dataIndex: "vehicleDepartmentName", title: "车辆所属部门" },
          { dataIndex: "employeeVehicleUserName", title: "车辆归属人" },
          { dataIndex: "licenceNo", title: "车牌号" },
          { dataIndex: "licenceTypeName", title: "车牌类型" },
          { dataIndex: "vehicleTypeName", title: "车辆类型" },
          {
            dataIndex: "gateLevelAuthArea",
            title: "访问港区范围",
            render: (_, record) => record.gateLevelAuthArea && JSON.parse(record.gateLevelAuthArea).area.map(item => item.value).join("、"),
          },
          { dataIndex: "visitStartTime", title: "访问开始时间" },
          { dataIndex: "visitEndTime", title: "访问结束时间" },
          { dataIndex: "auditStatus", title: "审批状态", render: (_, record) => getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: record.auditStatus }), hidden: !props.isRecords },
          {
            title: "操作",
            width: 100,
            render: (_, record) => (
              <Space>
                {(!props.isRecords && record.currentUserCanAudit === 1 && props.permission(props.auditBtn || "jgd-entry-share-vehicle-approval-audit")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setReviewModalVisible(true);
                      setCurrentId(record.id);
                      setCurrentVehicleApplyId(record.vehicleApplyId);
                    }}
                  >
                    审核
                  </Button>
                )}
                {props.permission(props.viewBtn || "jgd-entry-share-vehicle-approval-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setInfoModalVisible(true);
                      setCurrentId(record.id);
                      setCurrentVehicleApplyId(record.vehicleApplyId);
                    }}
                  >
                    查看
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        reviewModalVisible && (
          <ReviewModal
            id={currentId}
            vehicleApplyId={currentVehicleApplyId}
            onCancel={() => {
              setReviewModalVisible(false);
              setCurrentId("");
              setCurrentVehicleApplyId("");
            }}
            getData={getData}
          />
        )
      }
      {
        infoModalVisible && (
          <InfoModal
            id={currentId}
            vehicleApplyId={currentVehicleApplyId}
            isRecords={props.isRecords}
            onCancel={() => {
              setInfoModalVisible(false);
              setCurrentId("");
              setCurrentVehicleApplyId("");
            }}
          />
        )
      }
    </Page>
  );
}

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

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

  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
          style={{ marginTop: 10 }}
          form={form}
          showActionButtons={false}
          span={24}
          onFinish={onSubmit}
          labelCol={{ span: 6 }}
          values={{
            auditStatus: "2",
          }}
          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>
  );
}

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

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

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

  const getRecordsList = async () => {
    const { data } = await props["vehicleAuditRecordsList"]({ vehicleApplyId: props.vehicleApplyId });
    setRecordsList(data);
  };

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

  return (
    <div>
      <Spin spinning={props.vehicleAudit.vehicleAuditLoading}>
        <Divider orientation="left">申请信息</Divider>
        {
          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>
              )
        }
        {
          // !props.isRecords
          recordsList.length > 0
          && (
            <>
              <Divider orientation="left">审批信息</Divider>
              {recordsList.map((record, index) => (
                <div key={index} style={{ marginTop: 10 }}>
                  <Descriptions
                    column={1}
                    bordered
                    styles={{ label: { width: 200 } }}
                    items={[
                      { label: "审批人", children: record.auditUserName },
                      { label: "审批时间", children: record.auditTime },
                      { label: "审批状态", children:  record.batchState ===1 ? "申请" : record.batchState ===2 ? "更新" :"" },
                      { label: "是否通过", children: getLabelName({ list: VEHICLE_AUDIT_STATUS_ENUM, status: record.auditStatus }) },
                      ...(record.auditStatus === 3 ? [{ label: "打回意见", children: record.remarks }] : []),
                    ]}
                  />
                </div>
              ),
              )}
            </>
           )}
      </Spin>
    </div>
  );
}

function InfoModal(props) {
  return (
    <Modal
      open
      title="查看"
      maskClosable={false}
      onCancel={props.onCancel}
      width={800}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <PublicInfoModal id={props.id} vehicleApplyId={props.vehicleApplyId} isRecords={props.isRecords} />
    </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(ShareVehicles));
