<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",
        @switch-previous-month="switchPreviousMonth",
        @switch-next-month="switchNextMonth"
      )
      schedule-body(
        :employee-list="employeeList",
        :schedules-employee="fetchSchedulesEmployee",
        :schedule-list="scheduleList",
        :serialized="serialized",
        :data-schedule="dataSchedule",
        :buttons="buttons",
        :start-month="startMonth",
        :clear-employee="clearEmployee",
        @new-date="createNewDate"
      )
      schedule-bar(
        :data-schedule="dataSchedule",
        :buttons="buttons",
        :clear-employee="clearEmployee",
        :times="times",
        :create-schedule="postCreateSchedule"
      )
</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: [],
      dataSchedule: {
        status: "",
        date: null,
        startTime: "",
        endTime: "",
      },
      times: { start_time: "", end_time: "" },
      buttons: [
        {
          class: "button-work",
          name: "Работает",
          work: "WORKS",
          active: false,
          color: "#55CD76",
          text: "'Р'",
        },
        {
          class: "button-status",
          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)
      );
    },
    postCreateSchedule() {
      let currentEmployee = this.clearEmployee.find((e) => e.schedules);
      fetchWrapper
        .post("accounts/schedules/create/", {
          employee: currentEmployee.id,
          active_flg: true,
          start_date: currentEmployee.schedules.start_date,
          end_date: currentEmployee.schedules.end_date,
          start_time: this.times.start_time,
          end_time: this.times.end_time,
          status: this.buttons.find((e) => e.active).work,
        })
        .then(() => this.fetchSchedules());
    },
    createNewDate(e) {
      let schedules = {
        start_date: e.start,
        end_date: e.end,
      };
      this.clearEmployee.find((elem) => elem.id === e.id).schedules = schedules;
    },
    switchPreviousMonth() {
      this.startMonth = this.startMonth.clone().subtract(1, "M");
    },
    switchNextMonth() {
      this.startMonth = this.startMonth.clone().add(1, "M");
    },
  },
  watch: {
    startMonth() {
      this.fetchSchedulesEmployee();
    },
  },
  mounted() {
    this.fetchSchedules();
  },
};
</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)
  height: calc(100vh - 64px)
</style>
