<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import moment from "moment";

import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import allLocales from "@fullcalendar/core/locales-all";
import listPlugin from "@fullcalendar/list";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useLeavelistDataStore } from "@/modules/09_leave/stores/LeaveStore";
import { checkPermission } from "@/utils/permissions";

/** importType*/
import type { CalendarOptions } from "@fullcalendar/core";
import type {
  DataDateMonthObject,
  ResCalendar,
} from "@/modules/09_leave/interface/response/leave";
import { tokenParsed } from "@/plugins/auth";

/** use*/
const leaveStore = useLeavelistDataStore();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const $q = useQuasar();
const router = useRouter();

const { showLoader, hideLoader, messageError, monthYear2Thai } = mixin;

const keycloakId = ref<string>("");
/**
 * Option ของปฏิทิน
 */
const fullCalendar = ref<any>(); //ref calendar
const calendarOptions = ref<CalendarOptions>({
  plugins: [
    dayGridPlugin,
    timeGridPlugin,
    interactionPlugin, // needed for dateClick
    listPlugin,
  ],
  buttonText: {
    listYear: "รายการ",
    dayGridMonth: "ปฏิทิน",
    test: "เพิ่มวันหยุด",
  },
  headerToolbar: false,
  initialView: "dayGridMonth",
  initialEvents: [],
  selectable: true,
  dayMaxEvents: true,
  weekends: true,
  locale: "th",
  locales: allLocales,
  expandRows: true,
  nowIndicator: true,
  height: "100%",
  eventColor: "#fff",
  eventTextColor: "#4A5568",
  eventBorderColor: "#50a5fc",
  displayEventTime: false,
  editable: true,
  events: [],
});

const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});
const mainData = ref<ResCalendar[]>([]);

/** function เรียกข้อมูล Calendar*/
async function fetchDataCalendar(type: string) {
  showLoader();
  await http
    .post(config.API.leaveCalendar(), {
      year: dateMonth.value.year,
    })
    .then(async (res) => {
      mainData.value = res.data.result;
      const double_name = [
        ...new Set(mainData.value.map((item: ResCalendar) => item.keycloakId)),
      ];

      filterLists.value = [];
      for (let i = 1; i <= double_name.length; i++) {
        const name = double_name[i - 1];
        const filterName = {
          id: name,
          name: convertKeycloakId(name),
          color: "green",
        };

        filterLists.value.push(filterName);
        type === "onMounted" && filterVal.value.push(name);
      }
      const eventData = filterVal.value.map((item: any) => {
        return mainData.value
          .filter((e: ResCalendar) => e.keycloakId === item)
          .map((e: ResCalendar) => ({
            id: e.id,
            title: `${e.fullName} (${e.leaveTypeName}) `,
            start: e.leaveStartDate,
            end: moment(e.leaveEndDate).format("YYYY-MM-DD") + " 23:59:59",
            color: leaveStore.colorType(e.leaveTypeId),
            textColor: "black",
            allDay: false,
          }));
      });
      const allEventData = [].concat(...eventData);
      calendarOptions.value.events = allEventData;
      await fetchDataHoliday(calendarOptions.value.events);
    })

    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      const calen = fullCalendar.value.getApi();
      const date = new Date(dateMonth.value.year, dateMonth.value.month);
      calen.gotoDate(date);
      hideLoader();
    });
}

/**
 * fetch วันหยุดในปฏิทิน
 */
async function fetchDataHoliday(optionsCalendaMain: any) {
  await http
    .get(
      config.API.listHolidayHistoryYearMonth(
        dateMonth.value.year,
        dateMonth.value.month + 1
      )
    )
    .then((res) => {
      console.log(res);

      const dataNormal = res.data.result.normal;
      const data = dataNormal;
      const event = data.map((e: any) => ({
        id: e.id,
        title: `${e.name} `,
        start: e.holidayDate,
        end: new Date(
          new Date(e.holidayDate).setHours(23, 59, 59)
        ).toISOString(),
        allDay: e.holidayDate === e.holidayDate ? true : false,
        color: " #CCE5FF",
        textColor: "#0080FF",
      }));
      calendarOptions.value.events = [...optionsCalendaMain, ...event];
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * function convert ชื่อ
 * @param id profile
 */
function convertKeycloakId(id: any) {
  const filterName = mainData.value.find(
    (e: ResCalendar) => e.keycloakId === id
  );
  return filterName?.fullName;
}

// filter calendar left
const filterLists = ref<any[]>([]);
const filterVal = ref<any>([]);

function redirectToDetail(id: string) {
  router.push(`leave/detail/${id}`);
}

/** function เปลี่ยน calendar*/
async function changCalendar() {
  await fetchDataCalendar("chang");
}

function monthYearThai(val: DataDateMonthObject) {
  if (val == null) return "";
  else return monthYear2Thai(val.month, val.year);
}

watch(
  () => filterVal.value,
  async () => {
    const eventData = filterVal.value.map((item: any) => {
      return mainData.value
        .filter((e: ResCalendar) => e.keycloakId === item)
        .map((e: ResCalendar) => ({
          id: e.id,
          title: `${e.fullName} (${e.leaveTypeName}) `,
          start: e.leaveStartDate,
          end: moment(e.leaveEndDate).format("YYYY-MM-DD") + " 23:59:59",
          color: leaveStore.colorType(e.leaveTypeId),
          textColor: "black",
          allDay: false,
        }));
    });
    const allEventData = [].concat(...eventData);
    calendarOptions.value.events = allEventData;
    await fetchDataHoliday(calendarOptions.value.events);
  }
);

/**
 * เรียกฟังก์ชันทั้งหมดตอนเรียกใช้ไฟล์นี้
 */
onMounted(async () => {
  const user = await tokenParsed();
  keycloakId.value = user?.sub;
  await fetchDataCalendar("onMounted");
});
</script>
<template>
  <div class="q-mt-sm">
    <div class="row q-gutter-sm">
      <div class="col-3">
        <q-list bordered class="rounded-borders">
          <q-item
            v-for="(item, i) in filterLists"
            :key="i"
            tag="label"
            v-ripple
          >
            <q-checkbox
              size="sm"
              v-model="filterVal"
              :val="item.id"
              :color="item.color"
            />
            <q-item-section>
              <q-item-label>{{ item.name }}</q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </div>

      <div class="col">
        <div class="row q-gutter-sm q-pb-sm main-content">
          <div class="demo-app-main">
            <div class="row col-12 q-col-gutter-sm q-mb-sm">
              <div class="col-xs-12 col-sm-3 col-md-2">
                <datepicker
                  v-model="dateMonth"
                  :locale="'th'"
                  autoApply
                  month-picker
                  :enableTimePicker="false"
                  @update:modelValue="changCalendar"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      :model-value="monthYearThai(dateMonth)"
                      dense
                      outlined
                      style="width: 130px"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
            <FullCalendar
              ref="fullCalendar"
              class="demo-app-calendar"
              :options="calendarOptions"
            >
              <template v-slot:eventContent="arg">
                <div
                  class="row col-12 items-center no-wrap"
                  :style="
                    checkPermission($route)?.attrIsGet
                      ? `background: + ${arg.event.color}`
                      : `background: + ${arg.event.color};pointer-events: none;cursor: auto;`
                  "
                >
                  <div
                    class="textHover col-10"
                    @click="
                      checkPermission($route)?.attrIsGet
                        ? redirectToDetail(arg.event.id)
                        : ''
                    "
                  >
                    {{ arg.event.title }}
                  </div>
                  <q-tooltip>{{ arg.event.title }} </q-tooltip>
                </div>
              </template>
            </FullCalendar>
            <div class="row q-col-gutter-sm">
              <div
                v-for="(item, index) in leaveStore.leaveType"
                :key="index"
                class="items-center col-3"
              >
                <q-icon
                  size="10px"
                  name="mdi-circle"
                  class="q-mr-xs"
                  :style="`color: ${leaveStore.colorType(item.id)}`"
                />
                <span class="text-caption">{{ item.name }}</span>
              </div>
              <div class="items-center col-3">
                <q-icon
                  size="10px"
                  name="mdi-circle"
                  class="q-mr-xs"
                  style="color: #cce5ff"
                />
                <span class="text-caption">วันหยุดในปฏิทิน</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scope lang="scss">
.main-content {
  height: 65vh;
}

.color-main {
  color: #18a259;
}

.padding-content {
  padding: 10px;
}

.demo-app-main {
  flex-grow: 1;
  /* padding: 3em; */
}

.fc {
  /* the calendar root */
  max-width: 1100px;
  margin: 0 auto;
  background-color: white;
  border-radius: 10px;
}

.fc-day-today {
  background-color: #f8f8f8 !important;
}

.fc-day-today .fc-daygrid-day-number {
  display: flex;
  justify-content: center;
  align-items: center;
}

.fc-day-today .fc-daygrid-day-frame {
  padding: 5%;
}

.fc .fc-button-group > .fc-button {
  color: black;
  background-color: #fafafa;
  border: none;
}

.fc .fc-button-group > .fc-button:active {
  color: white;
  background-color: #22a15e;
  border: none;
}

.fc .fc-button-group > .fc-button.fc-button-active {
  color: white;
  background-color: #22a15e;
  border: none;
}

.fc-header-toolbar {
  background-color: white;
  padding: 0px 10px 0px 10px;
  border-radius: 10px 10px 0px 0px;
}

.fc .fc-scrollgrid-liquid > thead {
  background-color: white;
}

.dp-custom-cell {
  border-radius: 50%;
}

.dp__today {
  border: 1px solid var(--q-primary);
}

.dp__range_end,
.dp__range_start,
.dp__active_date {
  background: var(--q-primary);
  color: var(--dp-primary-text-color);
}

.datepicker .q-field__label {
  padding-left: 5px;
}

.datepicker .q-field__messages {
  padding-left: 20px;
}

.datepicker .q-field__native {
  padding-left: 5px;
  color: var(--q-primary) !important;
}

.datepicker .q-field__prepend {
  padding-left: 6px;
}

.datepicker .q-field__append {
  padding-right: 6px;
}

.datepicker .q-field__after {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-weight: 500;
}

.fc .fc-popover {
  z-index: 6000;
}

.fc-direction-ltr .fc-daygrid-event.fc-event-end,
.fc-direction-rtl .fc-daygrid-event.fc-event-start {
  cursor: pointer;
}

.subName {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-weight: 500;
}

.subInput {
  display: flex;
  align-items: center;
}

.fc-event {
  overflow: hidden;
  border-color: transparent !important;
  font-weight: 500;
}

.fc-event-main {
  text-align: left;
  padding: 0px 5px;
}

.fc-direction-ltr .fc-daygrid-event.fc-event-end,
.fc-direction-rtl .fc-daygrid-event.fc-event-start {
  padding-left: 0px;
}

.fc-theme-standard td,
.fc-theme-standard th {
  border: 1px solid #ebe9f1;
}

.textHover:hover {
  color: #f3faf6;
}
</style>
