<script setup>
import { ref, inject, onBeforeMount, defineProps, watch, computed } from "vue";
import DashboardProductCompleteModalTarget from "./DashboardProductCompleteModalTarget.vue";
import DashboardProductCompleteModalRecord from "./DashboardProductCompleteModalRecord.vue";
import useActiveBtn from "@/hooks/useActiveBtn";
import dayjs from "dayjs";
import { postDashboardProductTarget } from "@/apis/dashboard";

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

const date = ref([]);
const formState = ref({});
const selectedBtn = ref({});

const onOk = async () => {
  const res = await postDashboardProductTarget({
    date: dayjs(date.value[0].value).format("YYYY-MM-DD"),
    type: selectedBtn.value?.typeOption || 1,
    data: formState.value,
  });
  if (res.isSuccess) {
    // getCompletion();
    onCancel();
  }
};

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

const changeComponent = (e, item) => {
  changeActiveBtn(item);
};

onBeforeMount(() => {
  setItems([
    {
      title: "目標設定",
      key: "Target",
      active: true,
      component: DashboardProductCompleteModalTarget,
    },
    {
      title: "執行紀錄",
      key: "Record",
      active: false,
      component: DashboardProductCompleteModalRecord,
    },
  ]);
});

const activeTab = computed(() => {
  return items.value.find(({ active }) => active);
});
</script>

<template>
  <Modal
    id="dashboard_product"
    title="顯示設定"
    :onCancel="onCancel"
    width="1000"
    modalClass="bg-body"
  >
    <template #modalContent>
      <ButtonGroup
        :items="items"
        :withLine="true"
        class="mt-8 mb-6"
        :onclick="changeComponent"
      />
      <component :is="activeTab.component"></component>
    </template>
    <template #modalAction>
      <div v-if="activeTab.key === 'Target'">
        <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>
      </div>
      <div v-else="activeTab.key === 'Record'">
        <button
          type="reset"
          class="btn btn-outline-success mr-2"
          @click.prevent="onCancel"
        >
          取消
        </button>
      </div>
    </template>
  </Modal>
</template>

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