import { defineStore } from "pinia";
import ManagementService from "@/services/management.service";

export const STATE = Object.freeze({ 0: 'Appointment', 1: 'Diagnosis', 2: 'Prescription', 3: 'Completion' });
// export default STATE;

export const STATE_REVERSE = Object.freeze({ 'Appointment': 0, 'Diagnosis': '1', 'Prescription': 2, Completion: 3 });

export const useBoardsStore = defineStore({
  id: "boards",
  state: () => ({
    boards: [],
    // selectedBoard: 0,
    selectedColumn: 0,
    selectedTask: 0,
    draggedTask: 0,


    //  appointment
    // idleAppointments: [],

    calendar: {},
    selectedDate: {},
    selectedEvent: {}
  }),
  getters: {
    // getColumns: (state) => state.boards,
    getCurrentBoard: (state) => state.boards,
    getCurrentColumn: (state) => state.boards[state.selectedColumn],
    getTask: (state) => state.boards[state.selectedColumn].tasks[state.selectedTask],
    getColumnsNames: (state) => state.boards.map((c) => c.name),

    //  appointment
    // getIdleAppointments: (state) => state.idleAppointments,

    getCalendar: (state) => state.calendar,
    getSelectedDate: (state) => state.selectedDate,
    getSelectedEvent: (state) => state.selectedEvent,
  },
  actions: {
    // changeTaskColumn(index) {
    //   console.log(this.selectedColumn);
    //   console.log(index);
    //   if (!(index === this.selectedColumn)) {
    //     this.getCurrentBoard[index].tasks.push(this.getTask);
    //     this.getCurrentColumn.tasks.splice(this.selectedTask, 1);
    //     this.selectedColumn = index;
    //     this.selectedTask = this.getCurrentColumn.tasks.length - 1;

    //     console.log(this.getTask);
    //     ManagementService.update(this.getTask).then(
    //       (response) => {
    //         console.log(response);
    //       },
    //       (error) => {
    //         this.content =
    //           (error.response &&
    //             error.response.data &&
    //             error.response.data.message) ||
    //           error.message ||
    //           error.toString();
    //       }
    //     );

    //   }
    // },
    //  같은 열 내에서 이동
    // async changeTaskRow(columnIndex, removedIndex, addedIndex) {
    //   const moveData = this.boards[columnIndex].tasks[removedIndex];
    //   this.boards[columnIndex].tasks.splice(removedIndex, 1);
    //   this.boards[columnIndex].tasks.splice(addedIndex, 0, moveData);
    // },
    //  다른 열로 이동
    async changeTaskColumn(columnIndex, rowIndex, data) {
      data.loading = true;
      const oldStatus = STATE_REVERSE[data.status];

      //  0. 날짜포맷 Long으로 변경
      data.startdt = new Date(data.startdt).valueOf();
      data.enddt = new Date(data.enddt).valueOf();

      
      //  1. 데이터베이스에서 새로운 열로 업데이트
      data.status = STATE[columnIndex];
      await ManagementService.update(data).then(
        (response) => {

          //  2. 이전 열에 있는 데이터부터 캐시에서 삭제
          const findindex = this.boards[oldStatus].tasks.findIndex((e) => e.id === data.id);
          this.boards[oldStatus].tasks.splice(findindex, 1);

          //  3. 새로운 열로 데이터를 캐시에 추가
          this.boards[columnIndex].tasks.splice(rowIndex, 0, response)
          console.log(columnIndex);
          //  4. Appointment 라면 날짜순으로 정렬
          // if(columnIndex == 0) {
          //   this.boards[columnIndex].tasks.sort(
          //     (objA, objB) => new Date(objA.startdt).getTime() - new Date(objB.startdt).getTime(),
          //   );
          //   console.log(this.boards[columnIndex].tasks);
          // }
          data.loading = false;
        },
        (error) => {
          console.log(error);
        }
      );

    },
    saveTaskChanges({ task, column }) {
      this.getCurrentColumn.tasks[this.selectedTask] = task;
      if (this.selectedColumn !== column) {
        this.changeTaskColumn(column);
      }
    },


    //  appointment
    transCalendarEventToJson(data) {
      return {
        id: data.id,
        title: data.title,
        startdt: new Date(data.start).valueOf(),
        enddt: new Date(data.end).valueOf(),
        // birthDate: data.extendedProps.birthDate,
        // cellPhone: data.extendedProps.cellPhone,
        description: data.extendedProps.description,
        status: data.extendedProps.status,
        patient: data.extendedProps.patient,
      }
    },
    transJsonToCalendarEvent(data) {
      console.log(data);
      return {
        id: data.id,
        title: data.patient.lastName+" "+data.patient.firstName,
        start: new Date(data.startdt),
        end: new Date(data.enddt),
        allDay: false,
        extendedProps: {
          // cellPhone: data.cellPhone, 
          // birthDate: data.birthDate, 
          description: data.description, 
          status: data.status,
          patient: data.patient
        }
      }
    },
    addCalendarEvent(response) {
      this.calendar.unselect() // clear date selection
      this.calendar.addEvent(this.transJsonToCalendarEvent(response));
    },
    

    async todayLoad() {
      const userId = JSON.parse(sessionStorage.getItem('user')).id;
      await ManagementService.todayLoad(userId).then(
        (response) => {
          console.log(response);
          this.boards = response;
        },
        (error) => {
          console.log(error);
        }
      );
    },
    async loadByAppointment() {
      const userId = JSON.parse(sessionStorage.getItem('user')).id;
      await ManagementService.loadByStatus(userId, STATE[0]).then(
        (response) => {
          console.log(response);
          for (var value in response) {
            this.addCalendarEvent(response[value]);
          }
          // this.calendar.refetchEvents();
        },
        (error) => {
          console.log(error);
        }
      );
    },
    //  ONLY APPOINTMENT
    save(data) {
      console.log(data);
      data['user_id'] = JSON.parse(sessionStorage.getItem('user')).id;
      ManagementService.save(data).then(
        (response) => {
          console.log(this.boards);
          console.log(response);
          this.boards[STATE_REVERSE[response.status]].tasks.push(response);
          this.boards[STATE_REVERSE[response.status]].tasks.sort((a, b) => new Date(a.startdt) - new Date(b.startdt));
          //  APPOINTMENT
          if(STATE_REVERSE[response.status] === 0) {
            this.addCalendarEvent(response);
          }
        },
        (error) => {
          console.log(error);
        }
		  );
    },
    //  ONLY APPOINTMENT
    updateByEvent(event) {
      const findindex = this.boards[0].tasks.findIndex((e) => e.id === event.event.id);
      const data = this.transCalendarEventToJson(event.event);
      console.log(data);
      ManagementService.update(data).then(
        (response) => {
          //  APPOINTMENT
          if(STATE_REVERSE[response.status] === 0) {
            this.boards[0].tasks.splice(findindex, 1, response);
            this.boards[0].tasks.sort((a, b) => new Date(a.startdt) - new Date(b.startdt));
            this.addCalendarEvent(response);
            event.event.remove();
            // this.calendar.refetchEvents();
          }
        },
        (error) => {
          event.revert();
          console.log(error);
        }
		  );
    },
    //  ONLY APPOINTMENT
    updateByDataEvent(data, event) {
      console.log(data);
      const findindex = this.boards[0].tasks.findIndex((e) => e.id === event.event.id);
      ManagementService.update(data).then(
        (response) => {
          console.log(response);
          //  APPOINTMENT
          if(STATE_REVERSE[response.status] === 0) {
            this.boards[0].tasks.splice(findindex, 1, response);
            this.boards[0].tasks.sort((a, b) => new Date(a.startdt) - new Date(b.startdt));
            this.addCalendarEvent(response);
            event.event.remove();
            // this.calendar.refetchEvents();
          }
        },
        (error) => {
          event.revert();
        }
		  );
    },
    //  ONLY APPOINTMENT
    deleteByEvent(data, event) {
      const findindex = this.boards[0].tasks.findIndex((e) => e.id === data.id);
      ManagementService.delete(data.id).then(
        (response) => {
          this.boards[0].tasks.splice(findindex, 1);
          this.boards[0].tasks.sort((a, b) => new Date(a.startdt) - new Date(b.startdt));
          event.event.remove();
        },
        (error) => {
          event.revert();
          console.log(error);
        }
      );
    },

    //  DASHBOARD
    // async allLoad() {
    //   const userId = JSON.parse(sessionStorage.getItem('user')).id;
    //   await ManagementService.allLoad(userId).then(
    //     (response) => {
    //       console.log(response);
    //     },
    //     (error) => {
    //       console.log(error);
    //     }
    //   );
    // }
  },
});
