<template lang="pug">
  .schedule.flex-col(:style="themeCell")
    schedule-table-header(:result="result")
    schedule-table-body(
      :serialized="serialized",
      :trim-owner-name="trimOwnerName",
      :result="result",
      :choice-cell="choiceCell",
      :clear-select="clearSelect",
      :select-employee="selectEmployee",
      :choice-state="choiceState",
      :buttons="buttons",
      :show-time="showTime",
      :schedule-list="scheduleList"
    )
    schedule-table-select(
      v-if="clearEmployee.length > 0",
      :select-employee="selectEmployee",
      :clear-employee="clearEmployee",
      :result="result",
      :choice-cell="choiceCell",
      :choice-state="choiceState",
      :trim-owner-name="trimOwnerName",
    )
</template>

<script>
import * as moment from "moment";
import BaseModal from "@/components/base/BaseModal.vue";
import BaseButton from "@/components/base/BaseButton.vue";
import ScheduleTableHeader from "@/pages/schedule/components/ScheduleTableHeader.vue";
import ScheduleTableBody from "@/pages/schedule/components/ScheduleTableBody.vue";
import ScheduleTableSelect from "@/pages/schedule/components/ScheduleTableSelect.vue";

export default {
  name: "ScheduleTable",
  components: {
    BaseModal,
    BaseButton,
    ScheduleTableHeader,
    ScheduleTableBody,
    ScheduleTableSelect,
  },
  props: {
    scheduleList: Array,
    serialized: Array,
    buttons: Array,
    template: Object,
    clearEmployee: Array,
    showTime: Boolean,
    clearSelect: Function,
    selectEmployee: Object,
    startMonth: Object,
  },
  data() {
    return {
      days: "",
      result: [],
      employee: [],
      dateInterval: {
        id: "",
        start: "",
        end: "",
        text: "",
      },
      activeButton: null,
      choiceMonth: null,
    };
  },
  computed: {
    themeCell() {
      this.setActiveButton();
      return {
        "--bg-color-status": this.activeButton?.color,
        "--text-status": this.activeButton?.text,
      };
    },
  },
  methods: {
    setActiveButton() {
      this.activeButton = this.buttons.find((e) => e.active);
    },
    choiceCell(day, id, schedule) {
      if (this.showTime) return;
      let formatTime = day.format("YYYY-MM-DD");
      let insideSchedules = schedule?.schedules.filter(
        (el) =>
          (el.date > this.dateInterval.start &&
            el.date < this.dateInterval.end) ||
          el.date === this.dateInterval.start ||
          el.date === this.dateInterval.end
      );

      if (this.dateInterval.id !== id) {
        this.dateInterval.start = "";
        this.dateInterval.end = "";
        this.dateInterval.id = "";
      }

      if (!this.dateInterval.start) {
        this.dateInterval.start = formatTime;
        this.dateInterval.id = id;
      } else if (day.isAfter(this.dateInterval.start)) {
        this.dateInterval.end = formatTime;
      } else this.dateInterval.start = formatTime;
      this.$emit("schedule-employee", this.dateInterval, id);
      if (
        !this.selectEmployee.label &&
        this.dateInterval.start &&
        this.dateInterval.end &&
        insideSchedules
      )
        this.rangeSchdedules(schedule, insideSchedules, id);
    },
    rangeSchdedules(schedule, insideSchedules, id) {
      insideSchedules = schedule.schedules.filter(
        (el) =>
          (el.date > this.dateInterval.start &&
            el.date < this.dateInterval.end) ||
          el.date === this.dateInterval.start ||
          el.date === this.dateInterval.end
      );
      if (insideSchedules.length > 0) insideSchedules[0].employeeId = id;

      let keys = Object.keys(insideSchedules);
      let outsideSchedules = [];
      let firstDate = insideSchedules[keys[0]]?.date;
      let lastDate = insideSchedules[keys.length - 1]?.date;

      if (this.dateInterval.start < firstDate) {
        outsideSchedules.push({
          start_date: this.dateInterval.start,
          end_date: moment(firstDate).subtract(1, "d").format("YYYY-MM-DD"),
        });
      }
      if (this.dateInterval.end > lastDate)
        outsideSchedules.push({
          start_date: moment(lastDate).add(1, "d").format("YYYY-MM-DD"),
          end_date: this.dateInterval.end,
        });
      this.$emit("schedules", insideSchedules, outsideSchedules);
    },
    choiceState(day, id) {
      let formatDay = day.format("YYYY-MM-DD");
      let resStart =
        this.dateInterval.start &&
        formatDay === this.dateInterval.start &&
        this.dateInterval.id === id;

      let resEnd =
        this.dateInterval.end &&
        formatDay === this.dateInterval.end &&
        this.dateInterval.id === id;

      let resMiddle =
        day.isBefore(this.dateInterval.end) &&
        this.dateInterval.id === id &&
        day.isAfter(this.dateInterval.start);

      if (resStart || resMiddle || resEnd)
        return {
          status: !!this.activeButton,
          "set-date": !this.activeButton,
        };
    },
    changeDays() {
      this.days = moment(this.choiceMonth, "YYYY-MM-DD").daysInMonth();
    },
    pushMonth() {
      this.result = [];
      this.result.push(this.startMonth);
      for (let i = 2; i <= this.days; i++) {
        this.result.push(this.startMonth.clone().add(i - 1, "d"));
      }
    },
    trimOwnerName(lastName, firstName, patronymic) {
      let checkedFirstName = firstName !== null ? firstName[0] + "." : "";
      let checkedPatronymic = patronymic !== null ? patronymic[0] + "." : "";
      return `${lastName} ${checkedFirstName}${checkedPatronymic}`;
    },
  },
  watch: {
    startMonth: {
      immediate: true,
      handler(newMonth) {
        if (newMonth) {
          this.choiceMonth = newMonth.format("YYYY-MM-DD");
          this.changeDays();
          this.pushMonth();
        }
      },
    },
  },
  mounted() {
    this.changeDays();
    this.pushMonth();
  },
};
</script>

<style lang="sass" scoped>
.schedule
  border-top: 1.5px solid var(--border-light-grey-color-1)
  border-radius: 4px
  min-height: 87px
  width: calc(100vw - 136px)

.show-time
  text-align: center
  font-size: 12px

.modal-wrapper
  border: 1.5px solid var(--border-light-grey-color-1)
  border-radius: 4px
  width: 400px
  height: 500px

.status
  background-color: var(--bg-color-status) !important

.status::after
  content: var(--text-status)

.set-date
  background-color: var(--btn-blue-color-4) !important
</style>
