<script setup>
import { onMounted, ref, inject, onBeforeMount, watch, computed } from "vue";
import EffectScatter from "@/components/chart/EffectScatter.vue";
import useBuildingStore from "@/stores/useBuildingStore";
import AssetTableModalLeftInfoIoT from "./AssetTableModalLeftInfoIoT.vue";
import AssetTableModalLeftInfoGraph from "./AssetTableModalLeftInfoGraph.vue";
import * as yup from "yup";
import { twMerge } from "tailwind-merge";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
const { totalCoordinates } = inject("asset_table_data");
const { floors } = inject("asset_modal_options");
const { updateRightFields, formErrorMsg, formState } = inject(
  "asset_table_modal_form"
);
const store = useBuildingStore();
let schema = {
  floor_guid: yup.string().nullable(true),
  device_coordinate: yup.string().nullable(true),
};
onBeforeMount(() => {
  const data = {
    floor_guid: "",
    device_coordinate: "",
  };
  updateRightFields(schema, data);
});

const asset_floor_chart = ref(null);
const currentFloor = ref(null);
const parsedCoordinates = ref(null);

const defaultOption = (map, data = []) => {
  // 生成坐標數據，根據坐標值的不同設置不同顏色
  const formattedData = data.map((coordinate) => {
    const coordString = JSON.stringify(coordinate);
    
    // 解析 device_coordinate 為數值陣列進行比對
    let isSelected = false;
    if (formState.value.device_coordinate) {
      try {
        const deviceCoord = JSON.parse(formState.value.device_coordinate);
        // 比對數值而非字串，避免精度問題
        isSelected = coordinate.length === deviceCoord.length && 
                    coordinate.every((val, index) => Math.abs(val - deviceCoord[index]) < 0.001);
      } catch (e) {
        console.warn('解析 device_coordinate 失敗:', e);
      }
    }
    
    return {
      name: coordString,
      value: coordinate,
      itemStyle: {
        color: isSelected ? "#0000FF" : "#b02a02",
      },
    };
  });

  return {
    tooltip: {},
    geo: {
      tooltip: {
        show: false,
      },
      map,
      roam: true,
    },
    series: {
      type: "effectScatter",
      coordinateSystem: "geo",
      geoIndex: 0,
      symbolSize: 10,
      encode: {
        tooltip: 2,
      },
      data: formattedData, // 使用格式化的數據
    },
  };
};

watch(currentFloor, (newValue) => {
  if (newValue?.floor_map_name) {
    const coordinates =
      totalCoordinates.value?.[newValue.floor_guid]?.filter(
        (coord) => coord !== ""
      ) || [];

    parsedCoordinates.value =
      coordinates.length > 0
        ? coordinates.map((coord) => JSON.parse(coord))
        : [];

    asset_floor_chart.value.updateSvg(
      {
        full_name: newValue.floor_map_name,
        path: `${FILE_BASEURL}/${newValue.floor_map_url}.svg`,
      },
      defaultOption(newValue.floor_map_name, parsedCoordinates.value)
    );
  }
});

watch(
  formState,
  (newValue) => {
    if (newValue.floor_guid) {
      const floor = floors.value.find(
        ({ floor_guid }) => floor_guid === newValue.floor_guid
      );
      currentFloor.value = floor;
    } else {
      currentFloor.value = null;
    }
  },
  {
    deep: true,
  }
);

const getCoordinate = (position) => {
  formState.value.device_coordinate = JSON.stringify(position);
};

</script>

<template>
  <!-- 平面圖 -->

  <div class="flex gap-4 mb-5">
    <Select
      :value="formState"
      selectClass="border-info focus-within:border-info"
      name="floor_guid"
      Attribute="full_name"
      :options="floors"
      :isBottomLabelExist="false"
    >
      <template #topLeft>{{ $t("assetManagement.floor") }}</template>
    </Select>
    <Input
      :value="formState"
      width="270"
      name="device_coordinate"
      :disabled="true"
    >
      <template #topLeft>{{
        $t("assetManagement.device_coordinate")
      }}</template>
      <template #bottomLeft
        ><span class="text-error text-base">
          {{ formErrorMsg.device_coordinate }}
        </span></template
      ></Input
    >
  </div>
  <div class="relative min-h-[70vh]">
    <EffectScatter
      id="asset_floor_chart"
      ref="asset_floor_chart"
      :getCoordinate="getCoordinate"
      :class="
        twMerge(
          'absolute top-0 left-0 bg-white',
          currentFloor?.floor_map_url ? 'opacity-1' : 'opacity-0'
        )
      "
    />
    <div
      v-if="!currentFloor?.floor_map_url"
      class="absolute top-0 left-0 flex justify-center items-center min-h-[70vh] w-full border border-stone-900 shadow-lg bg-sub-success bg-opacity-25 rounded-md"
    >
      <p class="text-2xl">{{ $t("assetManagement.add_floor_text") }}</p>
    </div>
  </div>
<AssetTableModalLeftInfoGraph />
  <AssetTableModalLeftInfoIoT />
</template>

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