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 { CHANNEL_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["firstLevelDoorInfoChannelList"], {
    form,
    params: { eqMkmjId: query.id },
  });

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

  return (
    <Page headerTitle="通道">
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "likePassageName", label: "通道名称" },
          {
            name: "eqPassageStatus",
            label: "通道状态",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: CHANNEL_STATUS_ENUM,
          },
          { name: "eqPassageType", label: "通道类型", render: (<DictionarySelect dictValue="HGKM_MKMJ_PASSAGE_TYPE" />) },
        ]}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.entrance !== "enterprise" && (
              <Button
                type="primary"
                icon={<AddIcon />}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          { dataIndex: "passageTypeName", title: "通道类型", width: 100 },
          { dataIndex: "passageName", title: "通道名称" },
          { dataIndex: "gateCount", title: "设备数", width: 100 },
          {
            title: "操作",
            width: 240,
            render: (_, record) => (
              <Space>
                <Button
                  type="link"
                  onClick={() => {
                    setInfoModalVisible(true);
                    setCurrentId(record.id);
                  }}
                >
                  查看
                </Button>
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    onClick={() => {
                      setAddModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    编辑
                  </Button>
                )}
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record.id);
                    }}
                  >
                    删除
                  </Button>
                )}
                <Button
                  type="link"
                  onClick={() => {
                    props.history.push(`./fareGate?id=${record.id}&mkmjId=${query.id}`);
                  }}
                >
                  {props.entrance !== "enterprise" ? "添加设备" : "查看设备"}
                </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["firstLevelDoorInfoChannelInfo"]({ id: props.id });
    form.setFieldsValue({
      ...data,
      passageStatus: data.passageStatus.toString(),
    });
  };
  useEffect(() => {
    props.id && getData();
  }, []);

  const onSubmit = async (values) => {
    const { success } = await props[!props.id ? "firstLevelDoorInfoChannelAdd" : "firstLevelDoorInfoChannelEdit"]({
      ...values,
      id: props.id,
      mkmjId: 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.firstLevelDoorInfoChannelLoading}
      width={800}
    >
      <FormBuilder
        labelCol={{ span: 6 }}
        form={form}
        loading={props.firstLevelDoorInfo.firstLevelDoorInfoChannelLoading}
        span={24}
        onFinish={onSubmit}
        showActionButtons={false}
        options={[
          {
            name: "passageName",
            label: "通道名称",
            rules: [{
              validator: async (_, value) => {
                if (value) {
                  const { data } = await props["firstLevelDoorInfoChannelCheckName"]({
                    passageName: value,
                    id: props.id,
                    mkmjId: props.query.id,
                  });
                  return data.available ? Promise.resolve() : Promise.reject(new Error("通道名称已存在"));
                }
                else {
                  Promise.resolve();
                }
              },
              validateTrigger: "onBlur",
            }],
            formItemProps: { validateTrigger: ["onChange", "onBlur"] },
          },
          {
            name: "passageType",
            label: "通道类型",
            render: (
              <DictionarySelect
                dictValue="HGKM_MKMJ_TYPE"
                onGetLabel={label => form.setFieldValue("passageTypeName", label)}
              />
            ),
          },
          { name: "passageTypeName", label: "通道类型名称", onlyForLabel: true },
          { name: "passageStatus", label: "通道状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: CHANNEL_STATUS_ENUM },
          { key: "map", customizeRender: true, render: <Map type="cesium" /> },
        ]}
      />
    </Modal>
  );
};

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

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

  return (
    <Modal
      open
      onCancel={props.onCancel}
      title="查看"
      maskClosable={false}
      loading={props.firstLevelDoorInfo.firstLevelDoorInfoChannelLoading}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "通道名称", children: info.passageName },
          { label: "通道类型", children: info.passageTypeName },
          { label: "通道状态", children: getLabelName({ list: CHANNEL_STATUS_ENUM, status: info.passageStatus }) },
          {
            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>
            ),
          },
        ]}
      />
      <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);
