<script setup>
import { useRoute } from 'vue-router';
import EffectScatter from "@/components/chart/EffectScatter.vue";
import { computed, inject, ref, watch } from 'vue';
import { twMerge } from 'tailwind-merge';
import useSelectedFloor from "@/hooks/useSelectedFloor"

const route = useRoute()

const { currentFloor, subscribeData } = inject("system_deviceList")
const { getCurrentInfoModalData } = inject("system_selectedDevice")
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const asset_floor_chart = ref(null);
const defaultOption = (map, data = []) => ({
  tooltip: {},
  geo: {
    tooltip: {
      show: false,
    },
    map,
    roam: true, // 一定要关闭拖拽
  },
  series: {
    type: "effectScatter",
    coordinateSystem: "geo",
    geoIndex: 0,
    symbolSize: 10,
    itemStyle: {
      color: "#b02a02",
    },
    encode: {
      tooltip: 2,
    },
    data,
  },
});

const { selectedFloor } = useSelectedFloor()

watch([selectedFloor, () => asset_floor_chart,], ([newValue, newChart], [oldValue]) => {
  if (newValue && newChart.value && oldValue?.key !== newValue.key) {
    asset_floor_chart.value.updateSvg(
      {
        full_name: newValue?.title,
        path: `${FILE_BASEURL}/${newValue.map_url}`,
      },

      defaultOption(newValue?.title, subscribeData.value.filter(d => d.device_coordinate && d.floor_guid === route.params.floor_id).map(d => [...d.device_coordinate.split(","), d]))
    );
    newChart.value.chart.on("click", function (params) {
      console.log(params, params.data[2])
      getCurrentInfoModalData(params.event, {
        left: params.event.offsetX
        , top: params.event.offsetY
      }, params.data[2])
    });
  }
}, {
  immediate: true,
  deep: true,
})

watch(subscribeData, (newData) => {
  if (selectedFloor.value && asset_floor_chart.value) {
    asset_floor_chart.value.chart.setOption({
      series: {
        data: newData.filter(d => d.device_coordinate && d.floor_guid === route.params.floor_id).map(d => [...d.device_coordinate.split(","), d]),
      },
    })
  }
}, {
  immediate: true,
  deep: true,
})
</script>

<template>
  <!-- <Loading class="absolute" /> -->
  <EffectScatter id="system_floor_chart" ref="asset_floor_chart" class="min-h-[75vh] bg-white" />

  <!-- <div class="text-lg" v-if="!currentFloor?.key">尚未上傳樓層平面圖</div> -->
</template>

<style lang='scss' scoped></style>
