<script setup>
import {
  computed,
  ref,
  watch,
  inject,
  onMounted,
  onBeforeUnmount,
  onBeforeMount,
} from "vue";
import { useRoute } from "vue-router";
import ButtonGroup from "@/components/customUI/ButtonGroup.vue";
import EnergyActionButton from "./EnergyActionButton.vue";
import EnergySearchTime from "./EnergySearchTime.vue";
import useActiveBtn from "@/hooks/useActiveBtn";
import { getEnergySearch } from "@/apis/energy";
import { getElecTypeList } from "@/apis/asset";
import useSearchParam from "@/hooks/useSearchParam";
import useBuildingStore from "@/stores/useBuildingStore";

const storeBuild = useBuildingStore();
const { deptData, elecType, subSystem } = inject("energy_table_data");
const { searchParams, changeParams } = useSearchParam();
const route = useRoute();
// 選部門
const {
  items: sysDeptItems,
  changeActiveBtn: changeDeptActiveBtn,
  setItems: setDeptItems,
  selectedBtn: selectedDeptItems,
} = useActiveBtn("multiple");
// 選用電分類
const {
  items: sysElecTypeItems,
  changeActiveBtn: changeElecTypeActiveBtn,
  setItems: setElecTypeItems,
  selectedBtn: selectedElecTypeItems,
} = useActiveBtn("multiple");
// 選大類
const {
  items: sysMainTagItems,
  changeActiveBtn: changeMainSysActiveBtn,
  setItems: setMainSysItems,
  selectedBtn: selectedMainSysItems,
} = useActiveBtn();
// 選小類
const {
  items: sysTagItems,
  changeActiveBtn: changeSysActiveBtn,
  setItems: setSysItems,
  selectedBtn: selectedSysItems,
} = useActiveBtn();

// 選點位
const {
  items: points,
  changeActiveBtn: changeActivePoint,
  setItems: setPoints,
  selectedBtn: selectedPoints,
} = useActiveBtn("multiple");

const getElecType = async () => {
  const res = await getElecTypeList();
  const elecType = res.data.map((d, index) => ({
    ...d,
    title: d.name,
    key: d.id,
    active: true,
  }));
  setElecTypeItems(elecType);
};

const getSystems = async (type) => {
  const res = await getEnergySearch(Number(type));
  if (res?.data) {
    // 整理 main_system_tag
    const mainSystemMap = new Map();
    res.data.forEach((item) => {
      if (!mainSystemMap.has(item.main_system_tag)) {
        mainSystemMap.set(item.main_system_tag, {
          title: item.full_name,
          key: item.main_system_tag,
          active: false,
          subs: [],
        });
      }
      mainSystemMap.get(item.main_system_tag).subs.push({
        title: item.sub.full_name,
        key: item.sub.sub_system_tag,
        active: false,
        points: item.sub.point,
      });
    });

    const mainSystems = Array.from(mainSystemMap.values());
    if (mainSystems.length > 0) {
      mainSystems[0].active = true;
    }
    setMainSysItems(mainSystems);
  }
};

watch(selectedMainSysItems, (newVal) => {
  if (newVal) {
    let currentSub = newVal.subs;
    if (currentSub && currentSub.length > 0) {
      currentSub[0].active = true;
    }
    setSysItems(currentSub);
    setPoints([]);
  }
});

watch(selectedSysItems, (newVal, oldVal) => {
  if (newVal?.key !== searchParams.value.sub_system_tag) {
    let currentPoints = newVal.points;
    setPoints(
      currentPoints.map((point, index) => ({
        title: point.full_name,
        key: point.point_system_tag,
        active: index == 0,
      }))
    );
    subSystem.value = newVal.key;
  }
});

watch(selectedPoints, (newVal, oldVal) => {
  changeParams({
    ...searchParams.value,
    Points: newVal.map((d) => d.key),
  });
});

watch(selectedDeptItems, (newVal, oldVal) => {
  deptData.value = newVal.map((d) => d.key);
});

watch(selectedElecTypeItems, (newVal, oldVal) => {
  elecType.value = newVal.map((d) => d.key);
});

watch(
  () => route.params.type,
  (newVal) => {
    if (newVal) {
      getSystems(newVal);
    }
  },
  {
    immediate: true,
  }
);

watch(
  () => storeBuild.deptList,
  (newValue) => {
    if (newValue) {
      const deptList = newValue.map((d) => ({
        ...d,
        active: true,
      }));
      setDeptItems(deptList);
    }
  },
  {
    immediate: true,
  }
);

onMounted(() => {
  getElecType();
});
</script>

<template>
  <div class="flex flex-col custom-border p-4 mb-4">
    <div class="flex items-center gap-4 mb-4">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("assetManagement.department") }} :
      </h2>
      <ButtonGroup
        :items="sysDeptItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeDeptActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex items-center gap-4 mb-4" v-if="route.params.type == 3">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("energy.electricity_classification") }} :
      </h2>
      <ButtonGroup
        :items="sysElecTypeItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeElecTypeActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex items-center gap-4 mb-4">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("history.system_category") }} :
      </h2>
      <ButtonGroup
        :items="sysMainTagItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeMainSysActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex items-center gap-4 mb-4">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("history.device_category") }} :
      </h2>
      <ButtonGroup
        :items="sysTagItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeSysActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex items-center gap-4">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("history.point") }} :
      </h2>
      <ButtonGroup
        :items="points"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeActivePoint(item);
          }
        "
      />
    </div>
    <EnergySearchTime />
    <EnergyActionButton />
  </div>
</template>
