<script setup>
import useActiveBtn from "@/hooks/useActiveBtn";
import { onMounted, watch } from "vue";
import useSearchParams from "@/hooks/useSearchParam";
const { changeParams, searchParams } = useSearchParams();

const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();

const props = defineProps({
  currentIntervalType: {
    type: String,
    default: "interval_hour",
  },
});

onMounted(() => {
  setItems([
    {
      title: "1小時",
      key: "1hour",
      active:
        !searchParams.value?.[props.currentIntervalType] ||
        searchParams.value?.[props.currentIntervalType] === 1,
      timeInterval: 1,
    },
    {
      title: "4小時",
      key: "4hour",
      active: searchParams.value?.[props.currentIntervalType] === 4,
      timeInterval: 4,
    },
    {
      title: "8小時",
      key: "8hour",
      active: searchParams.value?.[props.currentIntervalType] === 8,
      timeInterval: 8,
    },
  ]);
});

watch(
  () => props.currentIntervalType,
  (newValue) => {
    console.log(
      "currentIntervalType",
      newValue,
      searchParams.value,
      searchParams.value?.[newValue]
    );
    setItems([
      {
        title: "1小時",
        key: "1hour",
        active:
          !searchParams.value?.[newValue] ||
          parseInt(searchParams.value?.[newValue]) === 1,
        timeInterval: 1,
      },
      {
        title: "4小時",
        key: "4hour",
        active: parseInt(searchParams.value?.[newValue]) === 4,
        timeInterval: 4,
      },
      {
        title: "8小時",
        key: "8hour",
        active: parseInt(searchParams.value?.[newValue]) === 8,
        timeInterval: 8,
      },
    ]);
  }
);

const onCancel = () => {
  dashboard_more.close();
};

const onOk = async () => {
  console.log(searchParams.value);
  changeParams({
    ...searchParams.value,
    [props.currentIntervalType]: selectedBtn.value.timeInterval,
  });
  onCancel();
};
</script>

<template>
  <Modal id="dashboard_more" title="顯示設定" :onCancel="onCancel" width="500">
    <template #modalContent>
      <ButtonGroup
        :items="items"
        :withLine="true"
        class="mt-8 mb-6"
        :onclick="
          (e, item) => {
            changeActiveBtn(item);
          }
        "
      />
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        取消
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.stop.prevent="onOk"
      >
        確定
      </button>
    </template>
  </Modal>
</template>

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