<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 } from "@/apis/history";
import useSearchParam from "@/hooks/useSearchParam";
import dayjs from "dayjs";

const { searchParams, changeParams } = useSearchParam();

// 選小類
const store = useBuildingStore();
const {
  items: sysTagItems,
  changeActiveBtn: changeSysActiveBtn,
  setItems: setSysItems,
  selectedBtn: selectedSysItems,
} = useActiveBtn();

const {
  items: searchTypeItems,
  changeActiveBtn: changeSearchTypeItemActiveBtn,
  setItems: setSearchTypeItems,
  selectedBtn: selectedTypeItems,
} = useActiveBtn();

watch(
  () => selectedTypeItems,
  (newVal, oldVal) => {
    if (newVal.value?.key !== searchParams.value.Cumulant) {
      changeParams({
        ...searchParams.value,
        Cumulant: newVal.value?.key,
      });
    }
  },
  {
    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,
  }
);

watch(
  [() => store.subSys, () => searchParams.value.Cumulant],
  ([newSubSys, newCumulant]) => {
    const isCumulant = newCumulant == 2;
    // 根據 Cumulant 過濾設備列表
    const filteredSubSys = newSubSys.filter((item) =>
      isCumulant ? item.is_cumulant === 1 : true
    );

    // 更新 SysItems
    setSysItems(
      filteredSubSys.map(({ full_name, sub_system_tag }, index) => ({
        title: full_name,
        key: sub_system_tag,
        active: searchParams.value.sub_system_tag
          ? searchParams.value.sub_system_tag === sub_system_tag
          : index === 0,
      }))
    );
  },
  {
    deep: true,
    immediate: true,
  }
);

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

const getPoint = async (Device_list, Cumulant) => {
  const res = await getHistoryPoints({ Device_list, Cumulant });
  const data = Array.isArray(res.data) ? res.data : [];
  setPoints(
    data.map((d, index) => ({
      ...d,
      title: d.item_name,
      key: d.points,
      active: index === 0,
    }))
  );
};

watch(
  selectedPoints,
  (newVal, oldVal) => {
    changeParams({
      ...searchParams.value,
      Points: newVal.map((d) => d.points),
    });
  },
  {
    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) ||
    (oldValue?.Cumulant && newVal?.Cumulant !== oldValue?.Cumulant)
  ) {
    getPoint(
      typeof newVal.Device_list == "string"
        ? [newVal.Device_list]
        : newVal.Device_list,
      newVal.Cumulant
    );

    setSearchTypeItems([
      {
        title: "IOT數據",
        key: 1,
        active: parseInt(newVal?.Cumulant) === 1,
      },
      // {
      //   title: "累積數據",
      //   key: 2,
      //   active: parseInt(newVal?.Cumulant) === 2,
      // },
    ]);
  }
});

onMounted(() => {
  setSysItems(
    store.subSys.map(({ full_name, sub_system_tag }, index) => ({
      title: full_name,
      key: sub_system_tag,
      active: index === 0,
    }))
  );

  setSearchTypeItems([
    {
      title: "IOT數據",
      key: 1,
      active: searchParams.value.Cumulant
        ? parseInt(searchParams.value.Cumulant) === 1
        : true,
    },
    // {
    //   title: "累積數據",
    //   key: 2,
    //   active: searchParams.value.Cumulant
    //     ? parseInt(searchParams.value.Cumulant) === 2
    //     : false,
    // },
  ]);
});

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

<template>
  <div class="flex flex-col custom-border p-4 mb-4">
    <HistoryFavoriteOption class="mb-4" />
    <div class="flex mb-4">
      <button
        :disabled="true"
        class="btn btn-outline-success disabled:text-opacity-100 mr-4 my-1"
      >
        數據類別
      </button>
      <ButtonGroup
        :items="searchTypeItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeSearchTypeItemActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex mb-4">
      <button
        :disabled="true"
        class="btn btn-outline-success disabled:text-opacity-100 mr-4 my-1"
      >
        設備類別
      </button>
      <ButtonGroup
        :items="sysTagItems"
        :withLine="true"
        :onclick="
          (e, item) => {
            changeSysActiveBtn(item);
          }
        "
      />
    </div>
    <div class="flex mb-4">
      <button
        :disabled="true"
        class="btn btn-outline-success text-white disabled:text-opacity-100 mr-4 my-1"
      >
        點位
      </button>
      <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>
