<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",
        :change-show-time="changeShowTime",
        :show-time="showTime"
        @switch-previous-month="switchPreviousMonth",
        @switch-next-month="switchNextMonth"
      )
      schedule-table(
        :schedules-employee="fetchSchedulesEmployee",
        :schedule-list="scheduleList",
        :serialized="serialized",
        :buttons="buttons",
        :start-month="startMonth",
        :clear-employee="clearEmployee",
        :show-time="showTime",
        @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 ScheduleTable from "@/pages/schedule/components/ScheduleTable.vue";
import { fetchWrapper } from "@/shared/fetchWrapper.js";

export default {
  name: "TheSchedule",
  components: { ScheduleHeader, ScheduleBar, ScheduleTable },
  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"),
      showTime: false,
      currentEmployee: {},
      schedulesDate: {},
    };
  },
  computed: {
    endMonth() {
      return this.startMonth.clone().endOf("month");
    },
  },
  methods: {
    changeShowTime() {
      this.showTime = !this.showTime;
    },
    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 ? e.end_time.slice(0, -3) : "",
                start_time: e.start_time ? e.start_time.slice(0, -3) : "",
                status: e.status,
                id: e.id,
                title: e.title,
                name: e.name,
              },
            ],
          });
        } else {
          foundedElem.schedules.push({
            date: e.date,
            end_time: e.end_time ? e.end_time.slice(0, -3) : "",
            start_time: e.start_time ? e.start_time.slice(0, -3) : "",
            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((el) => el.id !== item.id)
      );
    },
    distributeRequest(inside, outside, currentEmployee) {
      this.insideSchedules = inside;
      this.outsideSchedules = outside;
      this.currentEmployee = currentEmployee;
    },
    postCreateSchedules() {
      let data = {
        employee: this.schedulesDate.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();
        if (this.outsideSchedules)
          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: this.schedulesDate.start_date,
            end_date: this.schedulesDate.end_date,
          })
          .then(() => this.fetchSchedules());
      }
    },
    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.times.start_time,
          end_time: this.times.end_time,
          status: this.buttons.find((e) => e.active).work,
        })
        .then(() => this.fetchSchedules());
    },
    createScheduleEmployee(e, id) {
      let schedules = {
        start_date: e.start,
        end_date: e.end,
      };
      this.schedulesDate = {
        start_date: e.start,
        end_date: e.end,
        id: id,
      };
      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>
