<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';

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([])
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 }));
  raw_data.value = data
  data.value = data
}

const subscribeData = ref([]);

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.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 },
        // points: getSubPoint(
        //   d.device_normal_point_name,
        //   d.device_close_point_name,
        //   d.device_error_point_name,
        //   d.points
        // ),
        alarmMsg: "",
        is_show: true,
        currentColor: d.device_normal_point_color,
        spriteDbId: 10 + index,
      })),
    ];
  });
  data.value = raw_data.value;
  subscribeData.value = items;
}

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

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 })

</script>

<template>
  <SystemFloorBar />
  <div class="grid grid-cols-2 gap-5 mt-8 mb-4">
    <div class="col-span-1 h-[80vh] flex flex-col justify-between">
      <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>