<script setup>
import { onMounted, ref, inject, onBeforeMount, watch, computed } from "vue";
import EffectScatter from "@/components/chart/EffectScatter.vue";
import AssetBuildFloorAddModal from "./AssetBuildFloorAddModal.vue";
import {
  getAssetBuildList,
  getAssetFloorList,
  postAssetFloor,
} from "@/apis/asset";
import * as yup from "yup";
import { twMerge } from "tailwind-merge";

const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const { updateRightFields, formErrorMsg, formState } = inject(
  "asset_table_modal_form"
);
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 currentBuild = ref(null);
const currentFloor = 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 buildings = ref([]);
const floors = ref([]);

const getBuilds = async () => {
  const res = await getAssetBuildList();
  buildings.value = res.data?.map((d) => ({ ...d, key: d.building_guid }));
};

const getFloors = async (building_guid) => {
  const res = await getAssetFloorList(building_guid);
  floors.value = res.data[0]?.floors.map((d) => ({ ...d, key: d.floor_guid }));
};

watch(
  () => formState.value.building_guid,
  (newValue) => {
    if (newValue) {
      const building = buildings.value.find(
        ({ building_guid }) => building_guid === newValue
      );
      currentBuild.value = building;
      if (building?.building_guid) {
        getFloors(building.building_guid);
      }
    } else {
      currentBuild.value = null;
      floors.value = [];
    }
    currentFloor.value = null;
  },
  { immediate: true }
);

watch(
  [() => formState.value.floor_guid, () => floors.value],
  ([newValue, floors]) => {
    if (newValue) {
      if (!floors || floors.length === 0) {
        return;  
      }
      const floor = floors.find(
        ({ floor_guid }) => floor_guid === newValue
      );
      currentFloor.value = floor;
      if (floor?.floor_map_name) {
        asset_floor_chart.value.updateSvg(
          {
            full_name: floor?.floor_map_name,
            path: `${FILE_BASEURL}/${floor?.floor_map_url}.svg`,
          },
          defaultOption(floor?.floor_map_name, [
            formState.value.device_coordinate
              ? JSON.parse(formState.value.device_coordinate)
              : [],
          ])
        );
      }
    } else {
      currentFloor.value = null;
    }
  },
  { immediate: true }
);

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

onMounted(() => {
  getBuilds();
});

// modal
const openModal = () => {
  asset_add_floor.showModal();
};

const onCancel = () => {
  asset_add_floor.close();
};
</script>

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

  <div class="flex gap-4 mb-5">
    <Select
      :value="formState"
      selectClass="border-info focus-within:border-info"
      name="building_guid"
      Attribute="full_name"
      :options="buildings"
      :isBottomLabelExist="false"
    >
      <template #topLeft>棟別</template>
    </Select>
    <Select
      :value="formState"
      selectClass="border-info focus-within:border-info"
      name="floor_guid"
      Attribute="full_name"
      :options="floors"
      :isBottomLabelExist="false"
    >
      <template #topLeft>樓層</template>
    </Select>
    <button type="button" class="btn btn-success mt-11" @click="openModal()">
      <font-awesome-icon
        :icon="['fas', 'cog']"
        size="lg"
        class="text-white"
      />棟別-樓層
    </button>
  </div>
  <div class="relative">
    <EffectScatter
      id="asset_floor_chart"
      ref="asset_floor_chart"
      :getCoordinate="getCoordinate"
      :class="
        twMerge(
          'absolute top-0 left-0',
          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-[500px] w-full border border-stone-900 shadow-lg bg-sub-success bg-opacity-25 rounded-md"
    >
      <p class="text-2xl">須先上傳樓層地圖</p>
    </div>
  </div>
  <AssetBuildFloorAddModal :openModal="openModal" :onCancel="onCancel" :buildData="buildings"
  :fetchBuildData="getBuilds" />

</template>

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