<script setup>
import { RouterView, useRoute } from 'vue-router';
import { computed, watch, provide, ref } from "vue";
import SystemFloorBar from './components/SystemFloorBar.vue';
import useBuildingStore from "@/stores/useBuildingStore";
import ForgeForSystem from "@/components/forge/ForgeForSystem.vue";
import { getSystemDevices } from "@/apis/system";
import SystemSubBar from './components/SystemSubBar.vue';
import SystemInfoModal from './components/SystemInfoModal.vue';

const buildingStore = useBuildingStore()

const statusList = computed(() => {
  const sub = buildingStore.selectedSystem

  if (sub) {
    return {
      device_normal_color: sub.device_normal_color,
      device_normal_text: sub.device_normal_text,
      device_close_color: sub.device_close_color,
      device_close_text: sub.device_close_text,
      device_error_color: sub.device_error_color,
      device_error_text: sub.device_error_text
    }
  }
  return null
})

const raw_data = ref([])
const data = ref([]) // filter data
const route = useRoute()

const getData = async () => {
  const res = await getSystemDevices({
    sub_system_tag: route.params.sub_system_id,
    building_tag: buildingStore.selectedBuilding?.building_tag,
  })
  const data = res.data.map(d => ({
    ...d, key: d.full_name, device_list: d.device_list.map((d, index) => ({
      ...d,
      forge_dbid: parseInt(d.forge_dbid),
      device_coordinate_3d: d.device_coordinate_3d
        ? JSON.parse(d.device_coordinate_3d)
        : { x: 0, y: 0 },
      alarmMsg: "",
      is_show: true,
      currentColor: d.device_normal_point_color,
      spriteDbId: 10 + index,
      sensorTypes: d.points.map(({ points }) => points),
      points: d.points.map((p) => ({ ...p, value: "" }))
    })),
  }));
  raw_data.value = data
  data.value = data
}

const subscribeData = ref([]); // flat data

const getSubPoint = (normal, close, error, sub_points) => {
  let points = {
    ...Object.fromEntries(sub_points.map((p) => [p, ""])),
  };
  if (normal) points[normal] = "";
  if (close) points[close] = "";
  if (error) points[error] = "";
  return points;
};

const getSubData = (value) => {
  let items = [];
  value.forEach((device) => {
    items = [
      ...items,
      ...device.device_list
    ];
  });
  data.value = raw_data.value;
  subscribeData.value = items;
}

watch(raw_data, (newValue) => {
  updateDataByGas("all")
});

watch(data, (newValue) => {
  console.log(newValue);
})

const updateDataByGas = (gas) => {
  console.log(gas)
  if (gas === "all") {
    getSubData(raw_data.value)
  } else {
    data.value = raw_data.value.map((d) => ({
      ...d,
      device_list: d.device_list.filter(({ points }) => points.some(({ points: p }) => p === gas))
    }))
  }
}

watch([() => route, () => buildingStore.selectedBuilding], ([newRoute, newBuilding]) => {
  if (newBuilding && newRoute.params.sub_system_id) {
    getData()
  }
}, {
  deep: true,
  immediate: true,
})

const currentFloor = ref(null);

const updateCurrentFloor = (floor) => {
  currentFloor.value = floor;
}

provide("system_deviceList", { data, subscribeData, currentFloor, updateCurrentFloor, updateDataByGas })


// 傳遞目前點擊資訊
const currentInfoModalData = ref(null);
const isMobile = (pointerType) => {
  // let flag =
  //   /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone/gi.test(
  //     navigator.userAgent
  //   );
  // console.log("isMobile", flag);
  return pointerType !== "mouse"; // is desktop
};
const getCurrentInfoModalData = (e, position, value) => {
  const mobile = isMobile(e.pointerType);
  selectedDevice.value = {
    initPos: mobile
      ? { left: `50%`, top: `50%` }
      : { left: `${position.left}px`, top: `${position.top}px` },
    value,
    isMobile: mobile,
  };;
  document.getElementById('system_info_modal').showModal();
};

const selectedDevice = ref(null);

provide("system_selectedDevice", { selectedDevice, getCurrentInfoModalData })

</script>

<template>
  <SystemInfoModal :data="selectedDevice" />
  <SystemFloorBar />
  <div class="grid grid-cols-2 gap-5 mt-8 mb-4">
    <div class="col-span-1 h-[80vh] flex flex-col justify-start">
      <div>
        <div class="flex mb-4 items-center">
          <span class="flex items-center mr-3" v-if="statusList?.device_normal_text">
            <span class="w-7 h-7 rounded-full inline-block mr-1"
              :style="{ backgroundColor: statusList.device_normal_color }"></span>
            <span>{{ statusList.device_normal_text }}</span>
          </span>
          <span class="flex items-center mr-3" v-if="statusList?.device_close_text">
            <span class="w-7 h-7 rounded-full inline-block mr-1"
              :style="{ backgroundColor: statusList.device_close_color }"></span>
            <span>{{ statusList.device_close_text }}</span>
          </span>
          <span class="flex items-center mr-3" v-if="statusList?.device_error_text">
            <span class="w-7 h-7 rounded-full inline-block mr-1"
              :style="{ backgroundColor: statusList.device_error_color }"></span>
            <span>{{ statusList.device_error_text }}</span>
          </span>
        </div>
        <SystemSubBar class="mt-2 mb-4" />
      </div>
      <div class="max-h-[75vh] pr-2 overflow-y-auto">
        <RouterView />
      </div>
    </div>
    <div class="col-span-1 h-full">
      <ForgeForSystem :initialData="{}" />
    </div>
  </div>

</template>

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