<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 sameOption = {
  type: "effectScatter",
  coordinateSystem: "geo",
  geoIndex: 0,
  symbolSize: 10,
  encode: {
    tooltip: 2,
  },
}
const defaultOption = (map, data = []) => {
return {
  tooltip: {},
  geo: {
    tooltip: {
      show: false,
    },
    map,
    roam: true, // 一定要关闭拖拽
  },
  series: [
    {
      ...sameOption,
      itemStyle: {
        color: data?.[0]?.[2]?.device_normal_color || "#b02a02",
      },
      data,
    },
    // {
    //   itemStyle: {
    //     color: "#555555",
    //   },
    //   data: data?.[1],
    // }
  ],
}

};

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>
