<script setup>
import {
  //事件參數
  blankEvent,
  //事件功能
  useCalendar,
} from "@/views/apps/calendar/useCalendar";
//事件API

import { useCalendarStore } from "@/views/apps/calendar/useCalendarStore";
import FullCalendar from "@fullcalendar/vue3";

// Components
//開啟右側
import CalendarEventHandler from "@/views/apps/calendar/CalendarEventHandler.vue";

// 👉 Store
const store = useCalendarStore();
const router = useRouter();
const userData = useCookie("userData");

const project_number = ref("");
const project_name = ref("");
const initial_date = ref("");
const work_duration = ref("");

// Fetch project data
const fetchProjectData = async () => {
  try {
    const response = await $api(`/pdet/project/show`, {
      method: "POST",
      body: JSON.stringify({ project_number: import.meta.env.VITE_PROJECT_NUMBER }),
    });

    project_number.value = response.no;
    project_name.value = response.name;
    initial_date.value = response.expectedBeginAt;
    work_duration.value = response.work_duration;
  } catch (error) {
    console.error("Error fetching project data:", error);
  }
};

// Fetch data on component mount
onMounted(() => {
  fetchProjectData();
});

// 👉 Event
const event = ref(structuredClone(blankEvent));
const isEventHandlerSidebarActive = ref(false);

watch(isEventHandlerSidebarActive, (val) => {
  if (!val) event.value = structuredClone(blankEvent);
});

const isProjectEditorOpen = ref(false);

const toggleProjectEditor = () => {
  isProjectEditorOpen.value = !isProjectEditorOpen.value;
};

const { isLeftSidebarOpen } = useResponsiveLeftSidebar();

// 👉 useCalendar
const {
  refCalendar,
  calendarOptions,
  addEvent,
  addEvents,
  updateEvent,
  removeEvent,
  jumpToDate,
} = useCalendar(event, isEventHandlerSidebarActive, isLeftSidebarOpen);

const isCompletionDateCardOpen = ref(false);
const calculatedCompletionDate = ref(""); // 這裡存儲計算後的完成日
const daysUntilCompletion = ref(0); // 這裡存儲距離完成日的天數

const openCompletionDateCard = () => {
  // 假設 calculateCompletionDate 是一個函數，返回計算後的竣工完成日
  calculatedCompletionDate.value = calculateCompletionDate();

  // 計算距離竣工完成日的天數
  daysUntilCompletion.value = calculateDaysUntilCompletion(
    calculatedCompletionDate.value
  );

  isCompletionDateCardOpen.value = !isCompletionDateCardOpen.value;
};

// 示例：計算竣工完成日的函數
const calculateCompletionDate = () => {
  if (!initial_date.value || !work_duration.value) {
    console.error("Initial date or work duration is not defined.");
    return null;
  }

  const startDate = new Date(initial_date.value);
  let duration = parseFloat(work_duration.value);

  if (isNaN(duration)) {
    console.error("Invalid duration value.");
    return null;
  }

  // 用來存放已計算的日期
  const calculatedDates = new Set();

  // 加上行事曆事件的天數
  const calendarEvents = refCalendar.value.getApi().getEvents();
  calendarEvents.forEach((event) => {
    const eventDate = event.startStr;

    if (!calculatedDates.has(eventDate)) {
      if (event.extendedProps.work_duration === "半天") {
        duration += 0.5;
      } else if (event.extendedProps.work_duration === "全天") {
        duration += 1;
      }

      // 計算後將日期加入 Set
      calculatedDates.add(eventDate);
    }
  });

  const wholeDays = Math.floor(duration);
  const halfDay = duration % 1 === 0.5;

  startDate.setDate(startDate.getDate() + wholeDays - 1); // 減去 1 天以包含起始日期
  let completionDate = startDate.toISOString().slice(0, 10);
  if (halfDay) {
    completionDate += " 上午";
  }

  return completionDate;
};

const calculateDaysUntilCompletion = (completionDate) => {
  const today = new Date();
  const endDate = new Date(completionDate.split(" ")[0]);
  const diffTime = Math.abs(endDate - today);
  let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  if (completionDate.split(" ")[1]) {
    diffDays += 0.5;
  }
  return diffDays;
};

// SECTION Sidebar

// 👉 Check all
//用於檢查是否所有的日曆選項都被選中，用在左下角的filter。
const checkAll = computed({
  /*GET: Return boolean `true` => if length of options matches length of selected filters => Length matches when all events are selected
SET: If value is `true` => then add all available options in selected filters => Select All
Else if => all filters are selected (by checking length of both array) => Empty Selected array  => Deselect All
*/
  get: () => store.selectedCalendars.length === store.availableCalendars.length,
  set: (val) => {
    if (val)
      store.selectedCalendars = store.availableCalendars.map((i) => i.label);
    else if (store.selectedCalendars.length === store.availableCalendars.length)
      store.selectedCalendars = [];
  },
});
// !SECTION

const close = () => {
  isProjectEditorOpen.value = false;
};

const closeCalculateCompletionDate = () => {
  isCompletionDateCardOpen.value = false;
};

definePage({
  meta: {
    action: "read",
    subject: "pdet",
  },
});
</script>

<template>
  <div>
    <!-- 竣工完成日的VCard -->
    <VCard v-if="isCompletionDateCardOpen" class="completion-date-card">
      <VRow>
        <VCol cols="6">
          <label>預計竣工完成日：</label>
        </VCol>
        <VCol cols="6">
          <!-- 這裡顯示計算出的竣工完成日 -->
          <span>{{ calculatedCompletionDate }}</span>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="6">
          <label>距離預計竣工完成日還有幾天：</label>
        </VCol>
        <VCol cols="6">
          <!-- 這裡顯示距離竣工完成日的天數 -->
          <span>{{ daysUntilCompletion }} 天</span>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="11" class="text-right">
          <VBtn color="primary" @click="closeCalculateCompletionDate"
            >確認</VBtn
          >
        </VCol>
      </VRow>
    </VCard>

    <VCard class="project-editor-card">
      <!-- 新的顯示區塊 -->

      <div v-if="isProjectEditorOpen">
        <VRow>
          <VCol cols="2">
            <label>計畫編號：</label>
          </VCol>
          <VCol cols="9">
            <VTextField v-model="project_number" readonly />
          </VCol>
        </VRow>

        <VRow>
          <VCol cols="2">
            <label>工程名稱：</label>
          </VCol>
          <VCol cols="9">
            <VTextField v-model="project_name" readonly />
          </VCol>
        </VRow>

        <VRow>
          <VCol cols="2">
            <label>開工日期：</label>
          </VCol>
          <VCol cols="9">
            <AppDateTimePicker v-model="initial_date" />
          </VCol>
        </VRow>

        <VRow>
          <VCol cols="2">
            <label>契約工期：</label>
          </VCol>
          <VCol cols="9">
            <VTextField v-model="work_duration" />
          </VCol>
        </VRow>

        <VRow>
          <VCol cols="11" class="text-right">
            <VBtn color="primary" @click="close">確認</VBtn>
          </VCol>
        </VRow>
      </div>
    </VCard>

    <!-- 行事曆的VCard -->
    <VCard>
      <!-- `z-index: 0` Allows overlapping vertical nav on calendar -->
      <VLayout style="z-index: 0">
        <!-- 👉 Navigation drawer -->
        <VNavigationDrawer
          v-model="isLeftSidebarOpen"
          width="292"
          absolute
          touchless
          location="start"
          class="calendar-add-event-drawer"
          :temporary="$vuetify.display.mdAndDown"
        >
          <div style="margin: 1.4rem">
            <VBtn block prepend-icon="tabler-edit" @click="toggleProjectEditor">
              編輯專案初始資料
            </VBtn>
            <div style="block-size: 10px"></div>
            <VBtn
              block
              prepend-icon="tabler-plus"
              @click="isEventHandlerSidebarActive = true"
            >
              新增篩選條件
            </VBtn>
            <div style="block-size: 10px"></div>
            <VBtn
              block
              prepend-icon="tabler-plus"
              @click="openCompletionDateCard"
            >
              計算竣工完成日
            </VBtn>
          </div>
        </VNavigationDrawer>

        <VMain>
          <VCard flat>
            <FullCalendar ref="refCalendar" :options="calendarOptions" />
          </VCard>
        </VMain>
      </VLayout>
    </VCard>

    <CalendarEventHandler
      v-model:isDrawerOpen="isEventHandlerSidebarActive"
      :event="event"
      @add-event="addEvent"
      @add-events="addEvents"
      @update-event="updateEvent"
      @remove-event="removeEvent"
    />
  </div>
</template>

<style lang="scss">
@use "@core-scss/template/libs/full-calendar";

.layout-container {
  display: flex;
  align-items: start; /* Adjust alignment as needed */
}

.dates-details-card {
  inline-size: 300px; /* Adjust width as needed */
  margin-inline-end: 20px; /* Space between cards */
}

.calendars-checkbox {
  .v-label {
    color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
    opacity: var(--v-high-emphasis-opacity);
  }
}

label {
  display: flex;
  align-items: center;
  justify-content: center; /* 水平居中 */
  block-size: 100%;
}

// 新增的樣式用於創建間隔
.project-editor-card {
  margin-block-end: 20px; // 設置與下面元素的間隔
}

.calendar-add-event-drawer {
  &.v-navigation-drawer:not(.v-navigation-drawer--temporary) {
    border-end-start-radius: 0.375rem;
    border-start-start-radius: 0.375rem;
  }
}

.calendar-date-picker {
  display: none;

  + .flatpickr-input {
    + .flatpickr-calendar.inline {
      border: none;
      box-shadow: none;

      .flatpickr-months {
        border-block-end: none;
      }
    }
  }

  & ~ .flatpickr-calendar .flatpickr-weekdays {
    margin-block: 0 4px;
  }
}

.completion-date-card {
  margin-block-end: 20px; // 設置與下面元素的間隔
}
</style>

<style lang="scss" scoped>
.v-layout {
  overflow: visible !important;

  .v-card {
    overflow: visible;
  }
}
</style>
