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 LocationIcon from "zy-react-library/components/Icon/LocationIcon";
import Map from "zy-react-library/components/Map";
import MapSelector from "zy-react-library/components/Map/MapSelector";
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 { FARE_GATE_STATUS_ENUM } from "~/enumerate/constant";
import { NS_FIRST_LEVEL_DOOR_INFO } from "~/enumerate/namespace";

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

  const query = useGetUrlQuery();
  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["firstLevelDoorInfoFareGateList"], {
    form,
    params: { mkmjId: query.mkmjId, passageId: query.id },
  });

  const onDelete = (id) => {
    Modal.confirm({
      title: "删除确认",
      content: "确定要删除吗？",
      onOk: async () => {
        const { success } = await props["firstLevelDoorInfoFareGateDelete"]({ id });
        if (success) {
          message.success("删除成功");
          getData();
        }
      },
    });
  };

  return (
    <Page headerTitle="设备">
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "gateName", label: "闸机名称" },
          { name: "gateStatus", label: "闸机状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: FARE_GATE_STATUS_ENUM },
          { name: "gateType", label: "闸机类型", render: (<DictionarySelect dictValue="HGKM_MKMJ_GATE_TYPE" />) },
          { name: "gateCategory", label: "闸机类别", render: (<DictionarySelect dictValue="HGKM_MKMJ_CATEGORY_TYPE" />) },
        ]}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.entrance !== "enterprise" && (
              <Button
                type="primary"
                icon={<AddIcon />}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          { dataIndex: "gateName", title: "闸机名称" },
          { dataIndex: "gateCategoryName", title: "闸机类别", width: 100 },
          {
            dataIndex: "latitude",
            title: "闸机位置",
            render: (_, record) => `${record.longitude || ""}--${record.latitude || ""}`,
          },
          { dataIndex: "videoCount", title: "摄像头个数", width: 100 },
          {
            dataIndex: "gateStatus",
            title: "闸机状态",
            width: 100,
            render: (_, record) => getLabelName({ list: FARE_GATE_STATUS_ENUM, status: record.gateStatus }),
          },
          {
            title: "操作",
            width: 240,
            render: (_, record) => (
              <Space>
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    onClick={() => {
                      setAddModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    编辑
                  </Button>
                )}
                <Button
                  type="link"
                  onClick={() => {
                    props.history.push(`./camera/list?id=${record.id}&deviceType=2`);
                  }}
                >
                  {props.entrance !== "enterprise" ? "添加摄像头" : "查看摄像头"}
                </Button>
                <Button
                  type="link"
                  onClick={() => {
                    setInfoModalVisible(true);
                    setCurrentId(record.id);
                  }}
                >
                  查看
                </Button>
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record.id);
                    }}
                  >
                    删除
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        addModalVisible && (
          <AddModal
            onCancel={() => {
              setAddModalVisible(false);
              setCurrentId("");
            }}
            id={currentId}
            query={query}
            getData={getData}
          />
        )
      }
      {
        infoModalVisible && (
          <InfoModal
            onCancel={() => {
              setInfoModalVisible(false);
              setCurrentId("");
            }}
            id={currentId}
          />
        )
      }
    </Page>
  );
}

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

  const getData = async () => {
    const { data } = await props["firstLevelDoorInfoFareGateInfo"]({ id: props.id });
    form.setFieldsValue({
      ...data,
      gateType: data.gateType.toString(),
      gateCategory: data.gateCategory.toString(),
      gateStatus: data.gateStatus.toString(),
    });
  };
  useEffect(() => {
    props.id && getData();
  }, []);

  const onSubmit = async (values) => {
    const { success } = await props[!props.id ? "firstLevelDoorInfoFareGateAdd" : "firstLevelDoorInfoFareGateEdit"]({
      ...values,
      id: props.id,
      mkmjId: props.query.mkmjId,
      passageId: props.query.id,
    });
    if (success) {
      props.onCancel();
      props.getData();
    }
  };

  return (
    <Modal
      open
      onCancel={props.onCancel}
      onOk={form.submit}
      title={props.id ? "编辑" : "新增"}
      maskClosable={false}
      confirmLoading={props.firstLevelDoorInfo.firstLevelDoorInfoFareGateLoading}
      width={800}
    >
      <FormBuilder
        labelCol={{ span: 6 }}
        form={form}
        loading={props.firstLevelDoorInfo.firstLevelDoorInfoFareGateLoading}
        span={24}
        onFinish={onSubmit}
        showActionButtons={false}
        options={[
          {
            name: "gateType",
            label: "闸机类型",
            render: (
              <DictionarySelect
                dictValue="HGKM_MKMJ_GATE_TYPE"
                onGetLabel={label => form.setFieldValue("gateTypeName", label)}
              />
            ),
          },
          { name: "gateTypeName", label: "闸机类型名称", onlyForLabel: true },
          {
            name: "gateName",
            label: "闸机名称",
            rules: [{
              validator: async (_, value) => {
                if (value) {
                  const { data } = await props["firstLevelDoorInfoFareGateCheckName"]({
                    gateName: value,
                    id: props.id,
                    passageId: props.query.id,
                  });
                  return data.available ? Promise.resolve() : Promise.reject(new Error("闸机名称已存在"));
                }
                else {
                  Promise.resolve();
                }
              },
              validateTrigger: "onBlur",
            }],
            formItemProps: { validateTrigger: ["onChange", "onBlur"] },
          },
          {
            name: "gateCategory",
            label: "闸机类别",
            render: (
              <DictionarySelect
                dictValue="HGKM_MKMJ_CATEGORY_TYPE"
                onGetLabel={label => form.setFieldValue("gateCategoryName", label)}
              />
            ),
          },
          { name: "gateCategoryName", label: "闸机类别名称", onlyForLabel: true },
          { name: "gateModel", label: "闸机型号" },
          { name: "gatePosition", label: "闸机位置" },
          { key: "map", customizeRender: true, render: <Map type="cesium" /> },
          { name: "gateStatus", label: "闸机状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: FARE_GATE_STATUS_ENUM },
        ]}
      />
    </Modal>
  );
};

const InfoModalComponent = (props) => {
  const [info, setInfo] = useState({});
  const [mapVisible, setMapVisible] = useState(false);

  const getData = async () => {
    const { data } = await props["firstLevelDoorInfoFareGateInfo"]({ id: props.id });
    setInfo(data);
  };
  useEffect(() => {
    props.id && getData();
  }, []);

  return (
    <Modal
      open
      onCancel={props.onCancel}
      title="查看"
      maskClosable={false}
      loading={props.firstLevelDoorInfo.firstLevelDoorInfoFareGateLoading}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "闸机类型", children: info.gateTypeName },
          { label: "闸机名称", children: info.gateName },
          { label: "闸机类别", children: info.gateCategoryName },
          { label: "闸机型号", children: info.gateModel },
          { label: "闸机位置", children: info.gatePosition },
          {
            label: "地理位置",
            children: (
              <Button type="text"  style={{ display: "flex", alignItems: "center", gap: "8px" }} onClick={() => {
                setMapVisible(true);
              }}>
                <span>{info.longitude}</span>
                <span>--</span>
                <span>{info.latitude}</span>

              </Button>
            ),
          },
          { label: "闸机状态", children: getLabelName({ list: FARE_GATE_STATUS_ENUM, status: info.gateStatus }) },
        ]}
      />
      <MapSelector
        visible={mapVisible}
        onClose={() => setMapVisible(false)}
        longitude={info.longitude}
        latitude={info.latitude}
        disable={true}
        type="cesium"
      />
    </Modal>
  );
};

const AddModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(AddModalComponent);
const InfoModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(InfoModalComponent);
export default Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(List);
