<script setup lang="ts">
import { ref, watch, type PropType } from "vue";
import { useQuasar } from "quasar";
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 moment from "moment";

import type { CalendarOptions } from "@fullcalendar/core";
import type { DataDateMonthObject } from "@/modules/09_leave/interface/response/leave";
import type { ExtendHistoryObject } from "@/modules/11_discipline/interface/response/Main";

import { useCounterMixin } from "@/stores/mixin";

const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const { monthYear2Thai, showLoader, hideLoader, messageError, dateToISO } =
  mixin;

const $q = useQuasar();

const title = ref("");
const fullCalendar = ref<any>(); //ref calendar
const modalCancel = ref(false);
const modeCancel = ref(true);

const props = defineProps({
  lists: {
    type: Array as PropType<ExtendHistoryObject[]>,
    default: [],
  },
  modal: {
    type: Boolean,
    default: false,
  },
  close: {
    type: Boolean,
    default: true,
  },
});

const calendarOptions = ref<CalendarOptions>({
  plugins: [
    dayGridPlugin,
    timeGridPlugin,
    interactionPlugin, // needed for dateClick
    listPlugin,
  ],
  buttonText: {
    listYear: "รายการ",
    dayGridMonth: "ปฏิทิน",
    test: "เพิ่มวันหยุด",
  },
  headerToolbar: false,
  initialView: "dayGridMonth",
  initialEvents: [], // alternatively, use the `events` setting to fetch from a feed
  selectable: true,
  dayMaxEvents: true,
  weekends: true,
  locale: "th",
  locales: allLocales,
  expandRows: true,
  nowIndicator: true,
  height: "100%",
  eventColor: "#E3FDDA",
  eventTextColor: "#000000",
  eventBorderColor: "#50a5fc",
  displayEventTime: false,
  editable: true,
  events: [],
});

/** ตัวแปร filter*/
const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});

async function fetchCalendar() {
  showLoader();
  const defaultColor = "#e3fdda";
  const gradientColors = "#f7d0dd";

  const events = await props.lists.map(
    (e: ExtendHistoryObject, index: number) => ({
      id: index.toString(),
      title: e.name,
      start: e.dateStart,
      end: moment(e.dateEnd).format("YYYY-MM-DD") + " 23:59:59",
      allDay: false,
      color:
        props.lists.length > 1 && index > 0 ? gradientColors : defaultColor,
    })
  );
  calendarOptions.value.events = events;

  setTimeout(() => {
    if (fullCalendar !== undefined) {
      const calen = fullCalendar.value.getApi();
      const date = new Date(dateMonth.value.year, dateMonth.value.month);
      calen.gotoDate(date);
    }
    hideLoader();
  }, 1000);
}

/**
 * function convert เดือนปี
 * @param val เดือนปี
 */
function monthYearThai(val: DataDateMonthObject) {
  if (val == null) return "";
  else return monthYear2Thai(val.month, val.year);
}

/**
 * function openModalDetail
 * @param text เรื่อง
 */
async function view(text: string) {
  title.value = text;
  modalCancel.value = true;
  modeCancel.value = false;
}

function gotoPrevMonth() {
  const calen = fullCalendar.value.getApi();
  calen.prev();
  updateDateMonth(calen.getDate());
}

function gotoNextMonth() {
  const calen = fullCalendar.value.getApi();
  calen.next();
  updateDateMonth(calen.getDate());
}

function updateDateMonth(date: Date) {
  dateMonth.value.year = date.getFullYear();
  dateMonth.value.month = date.getMonth();
  fetchCalendar();
}

watch(
  () => props.modal,
  async () => {
    props.modal && (await fetchCalendar());
  }
);
</script>

<template>
  <q-dialog v-model="props.modal">
    <q-card style="min-width: 60vw">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle2 text-bold">
          ปฎิทินแสดงวันที่สืบสวน
        </q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="props.close"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>

      <q-separator />

      <q-card-section class="q-pa-md bg-grey-1 scroll">
        <div class="q-ma-sm">
          <div class="row q-gutter-sm">
            <div class="col-12">
              <div class="row q-gutter-sm q-pb-sm main-content">
                <div class="demo-app-main q-mb-xl">
                  <div class="row q-mb-sm justify-between">
                    <q-btn
                      size="12px"
                      dense
                      icon="mdi-chevron-left"
                      class="self-center items-center"
                      color="primary"
                      @click="gotoPrevMonth"
                    >
                      <q-tooltip>เดือนก่อนหน้า</q-tooltip>
                    </q-btn>

                    <p class="q-ma-none text-center">
                      {{ monthYearThai(dateMonth) }}
                    </p>

                    <q-btn
                      size="12px"
                      dense
                      icon="mdi-chevron-right"
                      class="self-center items-center"
                      color="primary"
                      @click="gotoNextMonth"
                    >
                      <q-tooltip>เดือนถัดไป</q-tooltip>
                    </q-btn>
                  </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="`background: + ${arg.event.color}`"
                      >
                        <div
                          class="textHover col-10"
                          @click="view(arg.event.title)"
                        >
                          {{ arg.event.title }}
                        </div>
                      </div>
                    </template>
                  </FullCalendar>
                </div>
              </div>
            </div>
          </div>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
<style scope lang="scss">
.main-content {
  height: 85vh;
}

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

.padding-content {
  padding: 10px;
}

.demo-app-main {
  flex-grow: 1;
}

.fc {
  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: #1d18a2;
}
</style>
