import useUrlState from "@ahooksjs/use-url-state";
import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Space } from "antd";
import { useEffect } from "react";
import AddIcon from "zy-react-library/components/Icon/AddIcon";
import BackIcon from "zy-react-library/components/Icon/BackIcon";
import DepartmentLeftTree from "zy-react-library/components/LeftTree/Department/Gwj";
import Page from "zy-react-library/components/Page";
import Search from "zy-react-library/components/Search";
import DictionarySelect from "zy-react-library/components/Select/Dictionary";
import Table from "zy-react-library/components/Table";
import { FORM_ITEM_RENDER_ENUM } from "zy-react-library/enum/formItemRender";
import useGetUrlQuery from "zy-react-library/hooks/useGetUrlQuery";
import useTable from "zy-react-library/hooks/useTable";
import { getLabelName } from "zy-react-library/utils";
import { NS_VEHICLE_APPLY } from "~/enumerate/namespace";

const APPROVAL_STATUS_ENUM = [
  { name: "审核中", bianma: "1" },
  { name: "通过", bianma: "2" },
  { name: "不通过", bianma: "3" },
];

function List(props) {
  const query = useGetUrlQuery();
  const [form] = Search.useForm();
  const [urlState, setUrlState] = useUrlState({
    departmentId: "",
    backDepartmentIds: [],
  }, {
    navigateMode: "replace",
    parseOptions: {
      arrayFormat: "index",
    },
    stringifyOptions: {
      arrayFormat: "index",
    },
  });

  const { tableProps, getData } = useTable(props["vehicleApplyList"], {
    form,
    params: () => ({ vehicleDepartmentId: urlState.departmentId, vehicleBelongType: props.vehicleBelongType || 2, corpId: query.id }),
    manual: true,
  });

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

  return (
    <Page isShowAllAction={false}>
      <div style={{ display: "flex", gap: 20 }}>
        <div style={{ width: 300 }}>
          <DepartmentLeftTree
            onGetNodePaths={(event) => {
              const departmentId = event.at(-1).id;
              setUrlState({
                departmentId,
                backDepartmentIds: [...urlState.backDepartmentIds, urlState.departmentId],
              });
            }}
            isNeedCorpInfoId={true}
            params={{ eqCorpinfoId: query.id }}
          />
        </div>
        <div style={{
          backgroundColor: "rgb(241, 241, 242)",
          width: 10,
          marginTop: "-20px",
          marginBottom: "-20px",
          height: "calc(100vh - 112px)",
        }}
        >
        </div>
        <div style={{ width: "calc(100% - 300px - 50px)" }}>
          <Search
            labelCol={{ span: 8 }}
            options={[
              { name: "licenceNo", label: "车牌号" },
              { name: "auditFlag", label: "审批状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: APPROVAL_STATUS_ENUM },
              {
                name: "gateLevelAuthAreaId",
                label: "访问港区范围",
                render: (<DictionarySelect dictValue="HG_AUTH_AREA" />),
              },
              { name: "visitStartTime", label: "访问开始时间", render: FORM_ITEM_RENDER_ENUM.DATE },
              { name: "visitEndTime", label: "访问结束时间", render: FORM_ITEM_RENDER_ENUM.DATE },
            ]}
            onFinish={getData}
            form={form}
          />
          <Table
            toolBarRender={() => (
              <Space>
                {(props.type !== "view" && props.permission(props.addBtn || "jgd-io-stock-unit-vehicle-add")) && (
                  <Button
                    icon={<AddIcon />}
                    type="primary"
                    onClick={() => {
                      props.history.push(`./add`);
                    }}
                  >
                    新增
                  </Button>
                )}
                {
                  (urlState.departmentId !== "" || props.type === "view") && (
                    <Button
                      icon={<BackIcon />}
                      onClick={() => {
                        if (urlState.departmentId === "") {
                          props.history.goBack();
                          return;
                        }
                        setUrlState({
                          departmentId: urlState.backDepartmentIds.at(-1),
                          backDepartmentIds: urlState.backDepartmentIds.slice(0, -1),
                        });
                      }}
                    >
                      返回
                    </Button>
                  )
                }
              </Space>
            )}
            columns={[
              { title: "车牌号", dataIndex: "licenceNo" },
              { title: "车牌类型", dataIndex: "licenceTypeName" },
              { title: "车辆类型", dataIndex: "vehicleTypeName" },
              {
                title: "访问港区范围",
                dataIndex: "gateLevelAuthArea",
                render: (_, record) => record.gateLevelAuthArea && JSON.parse(record.gateLevelAuthArea).area.map(item => item.value).join("、"),
              },
              { title: "访问起始时间", dataIndex: "visitStartTime" },
              { title: "访问结束时间", dataIndex: "visitEndTime" },
              {
                title: "审批状态",
                dataIndex: "auditFlag",
                render: (_, record) => getLabelName({ list: APPROVAL_STATUS_ENUM, status: record.auditFlag }),
              },
              {
                title: "车辆开启状态",
                dataIndex: "blockedFlag",
                render: (_, record) => record.blockedFlag === 2 ? "正常" : "已拉黑",
              },
              {
                title: "操作",
                width: 350,
                fixed: "right",
                render: (_, record) => (
                  <Space>
                    {(props.type !== "view" && props.permission(props.approvalRecordsBtn || "jgd-io-stock-unit-vehicle-auditrecord")) && (
                      <Button
                        type="link"
                        onClick={() => {
                          props.history.push(`./approvalRecords?id=${record.id}`);
                        }}
                      >
                        审核记录
                      </Button>
                    )}
                    {props.permission(props.vehicleRecordsBtn || "jgd-io-stock-unit-vehicle-inout") && (
                      <Button
                        type="link"
                        onClick={() => {
                        // TODO
                          props.history.push(`./vehicleRecords?licenceNo=${record.licenceNo}`);
                        }}
                      >
                        车辆进出记录
                      </Button>
                    )}
                    {(props.type !== "view" && record.auditFlag === 3 && props.permission(props.editBtn || "jgd-io-stock-unit-vehicle-edit")) && (
                      <Button
                        type="link"
                        onClick={() => {
                          props.history.push(`./add?id=${record.id}`);
                        }}
                      >
                        重新申请
                      </Button>
                    )}
                    {props.permission(props.viewBtn || "jgd-io-stock-unit-vehicle-show") && (
                      <Button
                        type="link"
                        onClick={() => {
                          props.history.push(`./view?id=${record.id}`);
                        }}
                      >
                        查看
                      </Button>
                    )}
                  </Space>
                ),
              },
            ]}
            {...tableProps}
          />
        </div>
      </div>
    </Page>
  );
}

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