<script setup>
import {
  computed,
  ref,
  watch,
  inject,
  onMounted,
  onBeforeUnmount,
  onBeforeMount,
} from "vue";
import ButtonGroup from "@/components/customUI/ButtonGroup.vue";
import Toast from "@/components/customUI/Toast.vue";
import HistoryFavoriteOption from "./HistoryFavoriteOption.vue";
import HistoryActionButton from "./HistoryActionButton.vue";
import HistorySearchTime from "./HistorySearchTime.vue";
import useActiveBtn from "@/hooks/useActiveBtn";
import useBuildingStore from "@/stores/useBuildingStore";
import {
  getHistoryPoints,
  getHistoryData,
} from "@/apis/history";
import useSearchParam from "@/hooks/useSearchParam";
import dayjs from "dayjs";

const { searchParams, changeParams } = useSearchParam();

const store = useBuildingStore();
// 選部門
const {
  items: sysDeptItems,
  changeActiveBtn: changeDeptActiveBtn,
  setItems: setDeptItems,
  selectedBtn: selectedDeptItems,
} = 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");

watch(
  () => store.mainSys,
  () => {
    setMainSysItems(
      store.mainSubSys.map(({ full_name, main_system_tag }, index) => ({
        title: full_name,
        key: main_system_tag,
        active: searchParams.value.main_system_tag
          ? searchParams.value.main_system_tag === mian_system_tag
          : index === 0,
      }))
    );
  }
);

watch(
  () => selectedMainSysItems,
  (newVal, oldVal) => {
    setSysItems(
      store.subSys
        .filter((s) => s.main_system_tag === newVal.value?.key)
        .map(({ full_name, sub_system_tag }, index) => ({
          title: full_name,
          key: sub_system_tag,
          active: index === 0,
        }))
    );
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => selectedSysItems,
  (newVal, oldVal) => {
    if (newVal.value?.key !== searchParams.value.sub_system_tag) {
      changeParams({
        ...searchParams.value,
        sub_system_tag: newVal.value?.key,
        Device_list:
          newVal.value?.key != searchParams.value.sub_system_tag
            ? []
            : searchParams.value?.Device_list,
      });
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const getPoint = async (deviceList) => {
  const res = await getHistoryPoints(deviceList);
  setPoints(
    res.data.map((d, index) => ({
      ...d,
      title: d.item_name,
      key: d.points,
      active: index === 0,
    }))
  );
};

watch(
  [selectedPoints, selectedDeptItems],
  ([newPoints, newDeptItems], [oldPoints, oldDeptItems]) => {
    changeParams({
      ...searchParams.value,
      Points: newPoints.map((d) => d.points),
      Dept: newDeptItems.map((d) => d.id),
    });
  },
  { immediate: true }
);

const form = ref(null);

watch(searchParams, (newVal, oldValue) => {
  if (
    (newVal?.Device_list?.length && typeof oldValue.Device_list === "string") ||
    (newVal?.Device_list?.length && !oldValue?.Device_list?.length)
  ) {
    if (newVal?.Device_list[0]!==null){
      getPoint(
        typeof newVal.Device_list == "string"
          ? [newVal.Device_list]
          : newVal.Device_list
      );
    }
  }
});

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

onMounted(() => {
  setMainSysItems(
    store.mainSubSys.map(({ full_name, main_system_tag }, index) => ({
      title: full_name,
      key: main_system_tag,
      active: index === 0,
    }))
  );
});

onBeforeMount(() => {
  changeParams({});
});
</script>

<template>
  <div class="flex flex-col custom-border p-4 mb-4">
    <!-- <HistoryFavoriteOption class="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">
      <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 mb-4">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("history.point") }} :
      </h2>
      <ButtonGroup
        v-if="searchParams?.Device_list"
        :items="points"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeActivePoint(item);
          }
        "
      />
    </div>
    <div class="flex justify-start">
      <form ref="form" class="flex">
        <HistorySearchTime v-if="searchParams?.Points" />
      </form>

      <HistoryActionButton :form="form" />
    </div>
  </div>
</template>
