<template lang="pug">
  .wrapper.flex.w-full.relative.mx-2
    .schedule-wrapper.relative.flex.flex-col.px-6.py-6.h-full.w-full.gap-y-5
      schedule-header(
        :start-month="startMonth",
        :times-shift="timesShift",
        @switch-previous-month="switchPreviousMonth",
        @switch-next-month="switchNextMonth"
      )
      schedule-body(
        :schedules-employee="fetchSchedulesEmployee",
        :schedule-list="scheduleList",
        :serialized="serialized",
        :buttons="buttons",
        :start-month="startMonth",
        :clear-employee="clearEmployee",
        @new-schedule-employee="createNewScheduleEmployee",
        @schedule-employee="createScheduleEmployee",
        @schedules="distributeRequest"
      )
      schedule-bar(
        :buttons="buttons",
        :times="times",
        :create-schedules="postCreateSchedules",
      )
</template>

<script>
import * as moment from "moment";
import ScheduleHeader from "@/pages/schedule/components/ScheduleHeader.vue";
import ScheduleBar from "@/pages/schedule/components/ScheduleBar.vue";
import ScheduleBody from "@/pages/schedule/components/ScheduleBody.vue";
import { fetchWrapper } from "@/shared/fetchWrapper.js";
export default {
  name: "TheSchedule",
  components: { ScheduleHeader, ScheduleBar, ScheduleBody },
  data() {
    return {
      employeeList: [],
      scheduleList: [],
      clearEmployee: [],
      serialized: [],
      times: { start_time: "", end_time: "" },
      timesShift: { start_time: "", end_time: "" },
      buttons: [
        {
          class: "button-work",
          name: "Работает",
          work: "WORKS",
          active: false,
          color: "#55CD76",
          text: "'Р'",
        },
        {
          class: "button-vacation",
          name: "Отпуск/больничный",
          work: "VACATION",
          active: false,
          color: "#D7D9FF",
          text: "'О'",
        },
        {
          class: "button-free",
          name: "Выходной",
          work: "DAY_OFF",
          active: false,
          color: "#9294A7",
          text: "'В'",
        },
      ],
      startMonth: moment().startOf("month"),
    };
  },
  computed: {
    endMonth() {
      return this.startMonth.clone().endOf("month");
    },
  },
  methods: {
    fetchSchedules() {
      fetchWrapper
        .get("general/employee/")
        .then((res) => {
          this.employeeList = res.results;
        })
        .then(() => this.fetchSchedulesEmployee());
    },
    fetchSchedulesEmployee() {
      this.scheduleList = [];
      fetchWrapper
        .get(
          `accounts/schedules/?date_after=${this.startMonth.format(
            "YYYY-MM-DD"
          )}&date_before=${this.endMonth.format("YYYY-MM-DD")}`
        )
        .then((data) => {
          this.scheduleList.push(...data.results);
        })
        .then(() => this.filterScheduleEmployee());
    },
    filterScheduleEmployee() {
      let serialized = [];
      this.scheduleList.forEach((e) => {
        let foundedElem = serialized.find((elem) => elem.id === e.employee.id);
        if (!foundedElem) {
          serialized.push({
            first_name: e.employee.first_name,
            id: e.employee.id,
            last_name: e.employee.last_name,
            patronymic: e.employee.patronymic,
            schedules: [
              {
                date: e.date,
                end_time: e.end_time,
                start_time: e.start_time,
                status: e.status,
                id: e.id,
                title: e.title,
                name: e.name,
              },
            ],
          });
        } else {
          foundedElem.schedules.push({
            date: e.date,
            end_time: e.end_time,
            start_time: e.start_time,
            status: e.status,
            id: e.id,
            title: e.title,
            name: e.name,
          });
        }
      });
      this.serialized = serialized;
      this.filterEmployee();
    },
    filterEmployee() {
      this.clearEmployee = [];
      this.clearEmployee = this.employeeList.filter((item) =>
        this.serialized.every((item2) => item2.id !== item.id)
      );
    },
    distributeRequest(inside, outside) {
      this.insideSchedules = inside;
      this.outsideSchedules = outside;
    },
    postCreateSchedules() {
      let newSchedule = null;
      if (this.clearEmployee.find((e) => e.schedules))
        newSchedule = this.clearEmployee.find((e) => e.schedules);
      else newSchedule = this.serialized.find((e) => e.schedule);
      let data = {
        employee: newSchedule.id,
        active_flg: true,
        start_time: this.times.start_time,
        end_time: this.times.end_time,
        status: this.buttons.find((e) => e.active).work,
      };
      if (this.insideSchedules.length > 0) {
        this.postUpdateSchedule();
        this.outsideSchedules.forEach((el) => {
          fetchWrapper.post("accounts/schedules/create/", {
            ...data,
            start_date: el.start_date,
            end_date: el.end_date,
          });
        });
      } else {
        fetchWrapper.post("accounts/schedules/create/", {
          ...data,
          start_date:
            newSchedule.schedules.start_date || newSchedule.schedule.start_date,
          end_date:
            newSchedule.schedules.end_date || newSchedule.schedule.end_date,
        });
      }
    },
    postUpdateSchedule() {
      let ids = "";
      this.insideSchedules.forEach((e) => (ids += e.id + ","));
      ids = ids.slice(0, -1);
      fetchWrapper.post(`accounts/schedules/${ids}/update/`, {
        employee: this.insideSchedules[0].employeeId,
        active_flg: true,
        start_time: this.insideSchedules[0].start_time,
        end_time: this.insideSchedules[0].end_time,
        status: this.buttons.find((e) => e.active).work,
      });
    },
    createNewScheduleEmployee(e) {
      let schedules = {
        start_date: e.start,
        end_date: e.end,
      };
      this.clearEmployee.find((elem) => elem.id === e.id).schedules = schedules;
    },
    createScheduleEmployee(e) {
      let schedules = {
        start_date: e.start,
        end_date: e.end,
      };
      this.serialized.find((elem) => elem.id === e.id).schedule = schedules;
    },
    switchPreviousMonth() {
      this.startMonth = this.startMonth.clone().subtract(1, "M");
    },
    switchNextMonth() {
      this.startMonth = this.startMonth.clone().add(1, "M");
    },
    setTime() {
      let now = new Date();
      let hour = now.getHours();
      let minute = now.getMinutes();
      let localDatetime =
        (hour < 10 ? "0" + hour.toString() : hour) +
        ":" +
        (minute < 10 ? "0" + minute.toString() : minute);
      this.times.start_time = localDatetime;
      this.times.end_time = localDatetime;
      this.timesShift.start_time = localDatetime;
      this.timesShift.end_time = localDatetime;
    },
  },
  watch: {
    startMonth() {
      this.fetchSchedulesEmployee();
    },
  },
  mounted() {
    this.fetchSchedules();
    this.setTime();
  },
};
</script>

<style lang="sass" scoped>
.wrapper
  overflow: auto
  border-top-left-radius: 4px
  border-top-right-radius: 4px

.schedule-wrapper
  background-color: var(--default-white)
</style>
