<template>
  <div class="tabs-detail">
    <div v-if="deviceDetail?.deviceInfo?.avatar">
      <p>设备图片</p>
      <Image :src="deviceDetail.deviceInfo.avatar" :width="200" />
    </div>
    <div>
      <div class="flex" style="align-items: center">
        <div>设备信息</div>
        <Tooltip
          title="复制或查看设备topic"
          @click="openTopicModal"
          placement="right"
          v-if="deviceDetail.deviceType !== DeviceTypeEnum.SENSOR"
        >
          <QuestionCircleOutlined class="ml-2" style="font-size: 1rem" />
        </Tooltip>
        <BasicModal
          @register="registerTopicModal"
          centered
          :footer="null"
          title="设备Topic"
          :canFullscreen="false"
          :minHeight="50"
          :height="50"
          :useWrapper="false"
        >
          <div v-if="deviceDetail.deviceType === DeviceTypeEnum.GATEWAY" class="flex">
            <div> 网关设备Topic : v1/gateway/telemetry </div>
            <a-button
              size="small"
              class="ml-4"
              @click="copyTopic('v1/gateway/telemetry')"
              color="success"
              >复制</a-button
            >
          </div>
          <div v-if="deviceDetail.deviceType === DeviceTypeEnum.DIRECT_CONNECTION" class="flex">
            <div> 直连设备Topic : v1/devices/me/telemetry </div>
            <a-button
              size="small"
              class="ml-4"
              @click="copyTopic('v1/devices/me/telemetry')"
              color="success"
              >复制</a-button
            >
          </div>
        </BasicModal>
      </div>
      <Description @register="register" class="mt-4" :data="deviceDetail" />
    </div>
    <div class="mt-4">
      <a-button type="primary" class="mr-4" @click="copyTbDeviceId">复制设备ID</a-button>
      <a-button type="primary" class="mr-4" @click="copyDeviceToken">复制访问令牌</a-button>
      <a-button type="primary" class="mr-4" @click="manageDeviceToken">管理设备凭证</a-button>
      <ManageDeviceTokenModal @register="registerModal" />
    </div>
    <div class="mt-4">
      <p>设备位置</p>
      <div v-if="deviceDetail?.deviceInfo?.address">
        <div ref="mapWrapRef" style="height: 550px; width: 100%"></div>
      </div>
      <Empty
        v-if="!deviceDetail?.deviceInfo?.address"
        :image="locationImage"
        :imageStyle="{ display: 'flex', 'justify-content': 'center', height: '150px' }"
        description="请添加设备地理位置"
      />
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, nextTick } from 'vue';
  import { Empty, Image, Tooltip } from 'ant-design-vue';
  import { descSchema } from '../../config/detail.config';
  import { useAsyncScript } from '/@/hooks/web/useAsyncScript';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BAI_DU_MAP_URL } from '/@/utils/fnUtils';
  import { BasicModal, useModal } from '/@/components/Modal';
  import ManageDeviceTokenModal from '../modal/ManageDeviceTokenModal.vue';
  import { getDeviceToken } from '/@/api/device/deviceManager';
  import { Description, useDescription } from '/@/components/Description';
  import { QuestionCircleOutlined } from '@ant-design/icons-vue';
  import { DeviceTypeEnum } from '/@/api/device/model/deviceModel';

  import wz from '/@/assets/images/wz.png';
  import { useAsyncQueue } from '../../../localtion/useAsyncQueue';
  import locationImage from '/@/assets/icons/location.svg';

  export default defineComponent({
    components: {
      Image,
      Description,
      ManageDeviceTokenModal,
      QuestionCircleOutlined,
      BasicModal,
      Tooltip,
      Empty,
    },
    props: {
      deviceDetail: {
        type: Object,
        required: true,
      },
    },
    emits: ['open-gateway-device'],
    setup(props, { emit }) {
      const [register] = useDescription({
        layout: 'vertical',
        schema: descSchema(emit),
        column: 2,
      });

      // 地图
      const mapWrapRef = ref<HTMLDivElement>();

      const { executeFlag, setTask } = useAsyncQueue();
      const { toPromise } = useAsyncScript({ src: BAI_DU_MAP_URL });

      async function initMap(longitude: number, latitude: number, address: string) {
        if (!(window as any).BMap) {
          setTask(() => markerMap(longitude, latitude, address));
          let interval: Nullable<NodeJS.Timer> = setInterval(() => {
            if ((window as any).BMap) {
              executeFlag.value = true;
              clearInterval(interval!);
              interval = null;
            }
          }, 300);
          await toPromise();
          return;
        }
        markerMap(longitude, latitude, address);
      }

      async function markerMap(longitude: number, latitude: number, address: string) {
        await nextTick();
        const wrapEl = unref(mapWrapRef);
        const BMap = (window as any).BMap;
        if (!wrapEl) return;
        const map = new BMap.Map(wrapEl);
        let myIcon = new BMap.Icon(wz, new BMap.Size(20, 30));

        const point = new BMap.Point(Number(longitude), Number(latitude));
        var content = `我在 ${address}`;
        var label = new BMap.Label(content, {
          // 创建文本标注
          position: point,
          offset: new BMap.Size(15, -35),
        });
        map.addOverlay(label); // 将标注添加到地图中
        label.setStyle({
          // 设置label的样式
          color: '#000',
          fontSize: '10px',
          border: '1px solid #1E90FF',
        });
        let marker = new BMap.Marker(point, { icon: myIcon });
        map.centerAndZoom(point, 15);
        map.enableScrollWheelZoom(true);
        map.addOverlay(marker);
      }

      const { createMessage } = useMessage();
      const { clipboardRef } = useCopyToClipboard();
      const copyTbDeviceId = () => {
        clipboardRef.value = props.deviceDetail.tbDeviceId;
        if (unref(clipboardRef)) {
          createMessage.success('复制成功~');
        }
      };
      const copyDeviceToken = async () => {
        const token = await getDeviceToken(props.deviceDetail.tbDeviceId);
        if (token.credentialsType === 'ACCESS_TOKEN') {
          clipboardRef.value = token.credentialsId;
        } else {
          clipboardRef.value = token.credentialsValue;
        }
        createMessage.success('复制成功~');
      };
      const [registerModal, { openModal }] = useModal();
      const manageDeviceToken = async () => {
        const token = await getDeviceToken(props.deviceDetail.tbDeviceId);
        openModal(true, token);
      };
      const copyTopic = (val) => {
        const { isSuccessRef } = useCopyToClipboard(
          JSON.parse(JSON.stringify(unref(val), null, 2))
        );
        unref(isSuccessRef);
        createMessage.success('复制成功！');
      };

      const [registerTopicModal, { openModal: openTopicModal }] = useModal();
      const remoteConnectiondGateway = () => {};

      return {
        mapWrapRef,
        copyTbDeviceId,
        copyDeviceToken,
        initMap,
        manageDeviceToken,
        registerModal,
        register,
        openTopicModal,
        registerTopicModal,
        DeviceTypeEnum,
        copyTopic,
        remoteConnectiondGateway,
        locationImage,
      };
    },
  });
</script>
<style lang="less" scoped></style>
