import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, message, Modal, Space } 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 DictionarySelect from "zy-react-library/components/Select/Dictionary";
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 useTable from "zy-react-library/hooks/useTable";
import { LICENSE_PLATE_NUMBER } from "zy-react-library/regular";
import { NS_VEHICLE_BLACKLIST } from "~/enumerate/namespace";

function List(props) {
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");

  const [form] = Search.useForm();

  const { tableProps, getData } = useTable(props["vehicleBlacklistList"], {
    form,
  });

  const onDelete = (record) => {
    Modal.confirm({
      title: "移除确认",
      content: `确定要将车牌号 ${record.licenceNo} 从黑名单中移除吗？`,
      onOk: async () => {
        const { success } = await props["vehicleBlacklistDelete"]({ id: record.id });
        if (success) {
          message.success("移除成功");
          getData();
        }
      },
    });
  };

  return (
    <Page isShowAllAction={false}>
      <Search
        options={[
          // {
          //   name: "vehicleDepartmentId",
          //   label: "车辆所属部门",
          //   render: (<DepartmentSelectTree searchType="inType" params={{ enterpriseType: [1, 2, 3] }} />),
          // },
          // { name: "employeeVehicleUserName", label: "车辆所属人" },
          { name: "licenceNo", label: "车牌号" },
          { name: "licenceType", label: "车牌类型", render: (<DictionarySelect dictValue="LICENSE_PLATE_TYPE" />) },
          { name: "vehicleType", label: "车辆类型", render: (<DictionarySelect dictValue="VEHICLE_TYPE" />) },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.permission(props.addBtn || "jgd-io-blacklist-add") && (
              <Button
                type="primary"
                icon={(<AddIcon />)}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          // { title: "车辆所属单位", dataIndex: "vehicleCorpName" },
          // { title: "车辆所属部门", dataIndex: "vehicleDepartmentName" },
          // { title: "车辆归属人", dataIndex: "employeeVehicleUserName" },
          { title: "车牌号", dataIndex: "licenceNo" },
          // { title: "车牌类型", dataIndex: "licenceTypeName" },
          // { title: "车辆类型", dataIndex: "vehicleTypeName" },
          {
            title: "操作",
            width: 150,
            fixed: "right",
            render: (_, record) => (
              <Space>
                {/* {props.permission(props.viewBtn || "jgd-io-blacklist-show") && ( */}
                {/*  <Button */}
                {/*    type="link" */}
                {/*    onClick={() => { */}
                {/*      setViewModalVisible(true); */}
                {/*      setCurrentId(record.id); */}
                {/*    }} */}
                {/*  > */}
                {/*    查看 */}
                {/*  </Button> */}
                {/* )} */}
                {props.permission(props.delBtn || "jgd-io-blacklist-del") && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record);
                    }}
                  >
                    移除黑名单
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        addModalVisible && (
          <AddModal
            onCancel={() => {
              setAddModalVisible(false);
            }}
            getData={getData}
          />
        )
      }
      {
        viewModalVisible && (
          <ViewModal
            onCancel={() => {
              setViewModalVisible(false);
            }}
            id={currentId}
          />
        )
      }
    </Page>
  );
}

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

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

  return (
    <Modal
      open
      title="新增"
      width={600}
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={form.submit}
      confirmLoading={props.vehicleBlacklist.vehicleBlacklistLoading}
    >
      <FormBuilder
        loading={props.vehicleBlacklist.vehicleBlacklistLoading}
        form={form}
        showActionButtons={false}
        span={24}
        labelCol={{ span: 8 }}
        onFinish={onSubmit}
        options={[
          { name: "licenceNo", label: "车牌号", rules: [{ pattern: LICENSE_PLATE_NUMBER, message: "请输入正确的车牌号" }] },
          {
            name: "licenceType",
            label: "车牌类型",
            render: (
              <DictionarySelect
                dictValue="LICENSE_PLATE_TYPE"
                onGetLabel={label => form.setFieldValue("licenceTypeName", label)}
              />
            ),
          },
          { name: "licenceTypeName", label: "车牌类型名称", onlyForLabel: true },
          {
            name: "vehicleType",
            label: "车辆类型",
            render: (
              <DictionarySelect
                dictValue="VEHICLE_TYPE"
                onGetLabel={label => form.setFieldValue("vehicleTypeName", label)}
              />
            ),
          },
          { name: "vehicleTypeName", label: "车辆类型名称", onlyForLabel: true },
        ]}
      />
    </Modal>
  );
};

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

  const { loading: getFileLoading, getFile } = useGetFile();

  const getData = async () => {
    const { data } = await props["vehicleBlacklistInfo"]({ id: props.id });
    let drivingLicenseFile = [];
    let attachmentFile = [];
    if (data.drivingLicenseId)
      drivingLicenseFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[601], eqForeignKey: data.drivingLicenseId });
    if (data.attachmentId)
      attachmentFile = await getFile({ eqType: UPLOAD_FILE_TYPE_ENUM[602], eqForeignKey: data.attachmentId });
    setInfo({
      ...data,
      drivingLicenseFile,
      attachmentFile,
    });
  };

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

  return (
    <Modal
      open
      title="查看"
      width={600}
      maskClosable={false}
      onCancel={props.onCancel}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
      loading={props.vehicleBlacklist.vehicleBlacklistLoading || getFileLoading}
    >
      <Descriptions
        bordered
        column={1}
        styles={{ label: { width: 200 } }}
        items={[
          { label: "车辆所属企业", children: info.vehicleCorpName },
          { label: "车辆所属部门", children: info.vehicleDepartmentName },
          { label: "车辆所属人", children: info.employeeVehicleUserName },
          { label: "车牌号", children: info.licenceNo },
          { label: "车牌类型", children: info.licenceTypeName },
          { label: "车辆类型", children: info.vehicleTypeName },
          { label: "访问港区范围", children: info.gateLevelAuthArea && JSON.parse(info.gateLevelAuthArea).area.map(item => item.value).join("、") },
          { label: "车辆照片", children: (<PreviewImg files={info.attachmentFile} />) },
          { label: "行驶证照片", children: (<PreviewImg files={info.drivingLicenseFile} />) },
        ]}
      />
    </Modal>
  );
};

const AddModal = Connect([NS_VEHICLE_BLACKLIST], true)(AddModalComponent);
const ViewModal = Connect([NS_VEHICLE_BLACKLIST], true)(ViewModalComponent);

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