<template>
	<section class="relative pt-16 pb-32 flex content-center items-center justify-center">
		<div class="container mx-auto px-1 lg:px-4">
			<div class="flex flex-wrap justify-center text-center pt-4">
				<div class="w-full lg:w-6/12 px-4">
					<h2 class="text-2xl font-semibold uppercase">Appointment</h2>
				</div>
			</div>
			<div class="card flex flex-wrap items-center pt-8">
				<div class="w-full md:w-12/12 px-4 mr-auto ml-auto">
                    <div id="calendar-container">
					<FullCalendar
                        id="calendar"
                        class='w-full lg:min-w-[940px]'
                        ref="calendarRef"
                        :options='calendarOptions'
                    >
                        <template v-slot:eventContent='arg'>
                            <!-- <div class="flex flex-wrap w-full" :id="arg.event.id">
                                <div class="badge badge-secondary">{{ arg.timeText }}</div>
                                <div class="flex">
                                    <p class="ml-2">{{ arg.event.title }}</p>
                                </div>
                            </div> -->

                            <div class="flex w-full" :id="arg.event.id">
                                <p class="font-bold">
                                    {{ arg.timeText }}
                                </p>
                                <p class="ml-2 font-bold">
                                    {{ arg.event.title }}
                                </p>
                            </div>
                        </template>
                    </FullCalendar>
                    </div>
				</div>
			</div>
		</div>
		<bgOverlay data-no-dragscroll />
		<div class="absolute top-16 z-10 max-w-max w-11/12 lg:w-8/12">
			<AppointmentForm v-if="systemStore.appointmentForm.visible" />
		</div>
	</section>

	<!-- toast alert 메세지 -->
	<Toast ref="toastRef" :content="content"></Toast>
</template>

<script>
import { ref, isProxy, toRaw } from 'vue'
import FullCalendar, { CalendarOptions, EventApi, DateSelectArg, EventClickArg } from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import { INITIAL_EVENTS, createEventId } from '@/services/utils/calendar-utils'
import moment from 'moment'

import bgOverlay from '@/components/utils/bgOverlay.vue';
import AppointmentForm from "@/components/appointment/AppointmentForm.vue";

import Toast from "@/components/utils/Toast.vue";
import { mapState } from "vuex";


import { usePatientsStore } from '@/store/patients.js';
import { useBoardsStore } from '@/store/boards.js';
import { useSystemStore } from '@/store/system.js';


export default {
    name: "Appointment",
    data() {
        return {
            content: "",
            boardsStore: useBoardsStore(),
            patientsStore: usePatientsStore(),
            systemStore: useSystemStore(),
            
            calendarOptions: {
                plugins: [
                    dayGridPlugin,
                    timeGridPlugin,
                    interactionPlugin // needed for dateClick
                ],
                //  timeZone: 'local',
                //  timeZone: 'utc',
			    // timeZone: 'America/Los_Angeles',
                // initialDate: this.changeTimeZone(new Date(), 'America/Los_Angeles'),
                slotMinTime: "09:00",
			    slotMaxTime: "19:00",
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
                },
                initialView: 'timeGridDay',
                // initialEvents: [], // alternatively, use the `events` setting to fetch from a feed
                // slotDuration: '01:00:00',
                // aspectRatio: 2.0,
                height: 880,
                editable: true,
                selectable: true,
                selectMirror: true,
                dayMaxEvents: true,
                weekends: true,
                select: this.handleDateSelect,
                eventClick: this.handleEventClick,
                eventChange: this.handleEventChange,
                eventsSet: this.handleEvents,
                /* you can update a remote database when these fire:
                eventAdd:
                eventRemove:
                */
                // events:[],
                // events: function(info, successCallback, failureCallback) {
	            //     successCallback(eventsData)
	            // },
            },
            currentEvents: []

        };
    },
    // watch: {
    //     eventsData: function (newValue, oldValue) {
    //         console.log(newValue)
    //         this.calendarOptions.events = newValue;
    //     },
    // },
    async mounted() {
        // this.$refs.calendarRef.calendar.setOption('height', 900);
        this.boardsStore.calendar = this.$refs.calendarRef.calendar;
        // console.log(this.$refs.calendarRef);
        await this.boardsStore.todayLoad();
        await this.boardsStore.loadByAppointment();

        this.$nextTick(function () {
            this.$refs.target?.scrollIntoView();
        });

        this.patientsStore.load();
        
    },
    unmounted(){
        this.systemStore.hideOverlay();
    },
    methods: {
        yyyymmdd(date) {
            return moment(date).format('YYYY-MM-DD');
        },
        click: function () {
			this.systemStore.overlay = true
			this.systemStore.appointmentForm = { visible: true, edit: false }
		},
        handleWeekendsToggle() {
            this.calendarOptions.weekends = !this.calendarOptions.weekends // update a property
        },
        handleDateSelect(selectInfo) {
            this.boardsStore.selectedDate = selectInfo;
            this.systemStore.overlay = true;
            this.systemStore.appointmentForm = { visible: true, edit: false }
        },
        handleEventClick(clickInfo) {
            // this.boardsStore.selectedEvent = this.boardsStore.transCalendarEventToJson(clickInfo.event);
            this.boardsStore.selectedEvent = clickInfo;
            this.systemStore.overlay = true;
            this.systemStore.appointmentForm = { visible: true, edit: true }
            // if (confirm(`Are you sure you want to delete the event '${clickInfo.event.title}'`)) {
            //     clickInfo.event.remove()
            // }
        },
        handleEventChange(clickInfo) {
            this.boardsStore.updateByEvent(clickInfo);

        },
        handleEvents(events) {
            this.currentEvents = events
        }

    },
    components: {
        Toast,
        AppointmentForm,
        bgOverlay,
        FullCalendar
    },
    computed: {
        ...mapState(["isRTL", "isAbsolute"]),

        currentUser() {
            return this.$store.state.auth.user.user;
        },
    },

};
</script>

<style>
#calendar-container {
    width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
}

  /* // 캘린더 전체 사이즈 조정 */
  .fc {
    width: 100%;
  }

  /* // toolbar container */
  .fc .fc-toolbar.fc-header-toolbar {
    margin: 0;
    padding: 0 40px;
    background-color: #356eff;
    height: 63px;
    font-weight: 600;
    font-size: 12px;
    line-height: 29px;
    color: white;
    border-radius: 20px 20px 0px 0px;
  }

  /* // toolbar 버튼 */
  .fc .fc-button-primary {
    background-color: transparent;
    border: none;

    span {
      font-weight: 500;
      font-size: 28px;
    }

    :hover {
      background-color: transparent;
    }
  }

  /* // 요일 부분 */
  .fc-theme-standard th {
    height: 32px;
    padding-top: 3.5px;
    background: #e5edff;
    border: 1px solid #dddee0;
    font-weight: 500;
    font-size: 16px;
    line-height: 19px;
    color: #7b7b7b;
  }

  /* // 오늘 날짜 배경색 */
  .fc .fc-daygrid-day.fc-day-today {
    background-color: #fff8bd;
    color: #356eff;
  }

  /* // 날짜별 그리드 */
  .fc .fc-daygrid-day-frame {
    padding: 10px;
    
  }

  /* // 날짜  ex) 2일 */
  .fc .fc-daygrid-day-top {
    flex-direction: row;
    margin-bottom: 3px;
    
  }

  /* // 각 이벤트 요소 */
  .fc-event {
    cursor: pointer;
    padding: 5px 8px;
    margin-bottom: 5px;
    border-radius: 4px;
    font-weight: 500;
    font-size: 14px;
  }

  .fc-timegrid-slot {
    height: 35px !important;
    border-bottom: 0 !important;
}
  /* .fc .fc-col-header-cell-cushion {
  display: inline-block;
  padding: 2px 4px;
} */
</style>