<template lang="pug">
  .flex.flex-col.gap-y-6.pt-6.pb-7.px-8.event-form.absolute.right-2.bottom-14
    .flex.flex-col.gap-y-2
      .flex.justify-between.pt-2
        span.text-xs.opacity-40.font-bold.leading-3 Ответственный
        .icon-cancel.close-icon.text-xs.cursor-pointer(@click="clearForm")
      base-select.select(
        v-if="!selectedEventData.employees",
        :items="ownersList",
        v-model="employees.employee",
        placeholder="Выберите ответственного",
        separator
        border-none
      )  
      base-input(
        v-if="selectedEventData.employees",
        v-model:value="employeeName",
        :width-input="72",
        disabled,
        border-none
      )
    .flex.flex-col.gap-y-2
      span.text-xs.opacity-40.font-bold.leading-3 Основная информация
      .flex.gap-x-4.items-center
        .flex.gap-x-2.items-center
          base-input-date(v-model:value="eventDate")
      .flex.items-center
        .flex.gap-x-2.items-center
          base-input-time.item-input.text-base.cursor-text(
            v-model:value="startTime",
            :width-input="72"
          )
          span —
          base-input-time.item-input.text-base.cursor-text(
            v-model:value="endTime",
            :width-input="72"
          )
      .flex.gap-x-4.items-center
        .icon-person.text-xl.icon
        base-select.select(
          v-if="!selectedEventData.members",
          :items="membersList",
          v-model="members.person",
          placeholder="Выберите ответственного",
          separator
          border-none
        )
        base-input(
          v-if="selectedEventData.members",
          v-model:value="memberName",
          disabled,
          :width-input="346"
          border-none
       )
    .flex.flex-col.gap-y-2
      span.text-xs.opacity-40.font-bold.leading-3 Вид события
      base-select.select(
        v-model="kind"
        :items="kindEvents"
        placeholder="Вид события"
        separator
        border-none
        :style="kindSelectWidth"
      )
    .flex.flex-col.gap-y-2
      .flex.gap-x-4.items-center
        span.text-xs.opacity-40.font-bold.leading-3 Контакты
        base-button(
          left-icon="icon-plus"
          rounded secondary
          :size="24"
          :icon-left-size="10"
          id="addContact"
          @click="(e)=>addContact(e)"
        )
      .flex.gap-x-4.items-center(
        v-for="(contact, index) in listContacts"
        :key="index"
      )
        .icon-mail.text-xl.icon
        .form-item.flex.gap-x-2.items-center
          base-input(
            border-none
            v-model="contacts"
            placeholder="E-mail"
            :width-input="72"
          )
    base-button.styled-button.text-base.font-semibold(
      :size="40"
      :disabled="disabledButton"
      @click="sendEventData"
    ) Создать событие
</template>

<script>
import BaseInputTime from "@/components/base/BaseInputTime.vue";
import BaseInput from "@/components/base/BaseInput.vue";
import BaseInputDate from "@/components/base/BaseInputDate.vue";
import BaseSelect from "@/components/base/BaseSelect.vue";
import BaseButton from "@/components/base/BaseButton";
import * as moment from "moment/moment";
export default {
  name: "FormChangeEvent",
  components: {
    BaseSelect,
    BaseButton,
    BaseInput,
    BaseInputDate,
    BaseInputTime,
  },
  props: {
    closeForm: Function,
    ownersData: {
      type: Array,
      default() {
        return [];
      },
    },
    membersData: {
      type: Array,
      default() {
        return [];
      },
    },
    selectedEventData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      listContacts: [1],
      kindEvents: [
        {
          id: 1,
          label: "Встреча",
        },
        {
          id: 2,
          label: "Планерка",
        },
        {
          id: 3,
          label: "Интервью",
        },
        {
          id: 4,
          label: "Важная работа",
        },
      ],
      EMPLOYEE_TYPE: "owner",
      MEMBER_TYPE: "primary",
      eventData: {},
      contacts: [],
      startTime: "",
      endTime: "",
      members: {},
      employees: {},
      eventDate: "",
      kind: "",
      id: null,
      ifClearedForm: true,
    };
  },
  computed: {
    ownersList() {
      if (this.ownersData) {
        let filteredArray = [];
        this.ownersData.forEach((elem) => {
          filteredArray.push({
            id: elem.id,
            label: this.trimOwnerName(
              elem.last_name,
              elem.first_name,
              elem.patronymic
            ),
          });
        });
        return filteredArray;
      }
      return [];
    },
    membersList() {
      if (this.membersData) {
        let filteredArray = [];
        this.membersData.forEach((elem) => {
          filteredArray.push({
            id: elem.id,
            label: this.trimMemberName(
              elem.last_name,
              elem.first_name,
              elem.patronymic
            ),
            contacts: elem.contacts,
          });
        });
        console.log(filteredArray);
        return filteredArray;
      }
      return [];
    },
    memberName() {
      if (this.selectedEventData.members) {
        let foundMember = {};
        if (this.selectedEventData.members.length > 1) {
          foundMember = this.selectedEventData.members.find(
            ({ role }) => role === this.MEMBER_TYPE
          );
        } else foundMember = this.selectedEventData.members[0];
        let {
          person: { last_name, first_name, patronymic },
        } = foundMember;
        return this.trimMemberName(last_name, first_name, patronymic);
      }
      return "";
    },
    employeeName() {
      if (this.selectedEventData.employees) {
        let foundEmployee = this.selectedEventData.employees.find(
          ({ role }) => role === this.EMPLOYEE_TYPE
        );
        let {
          employee: { last_name, first_name, patronymic },
        } = foundEmployee;
        return this.trimOwnerName(last_name, first_name, patronymic);
      }
      return "";
    },
    disabledButton() {
      if (
        this.eventDate &&
        this.startTime &&
        this.endTime &&
        this.members &&
        this.employees &&
        this.kind
      ) {
        return false;
      }
      return true;
    },
    startDate() {
      return this.selectedEventData.start
        ? moment.parseZone(this.selectedEventData.start)
        : moment();
    },
    endDate() {
      return this.selectedEventData.end
        ? moment.parseZone(this.selectedEventData.end)
        : moment();
    },
    eventEmployee() {
      if (this.selectedEventData.employees) {
        return this.selectedEventData.employees;
      }
      return {
        id: null,
        employee: null,
        role: this.EMPLOYEE_TYPE,
      };
    },
    eventKind() {
      return this.selectedEventData.kind ? this.selectedEventData.kind : "";
    },
    eventId() {
      return this.selectedEventData.id ? this.selectedEventData.id : "";
    },
    eventMember() {
      return this.selectedEventData.members
        ? this.selectedEventData.members
        : {
            id: null,
            person: null,
            role: this.MEMBER_TYPE,
          };
    },
    kindSelectWidth() {
      return {
        width: this.kind ? `${this.kind.length * 9 + 65}px` : "164px",
      };
    },
  },
  methods: {
    addContact(e) {
      if (e.currentTarget.id === "addContact") {
        this.listContacts.push(
          this.listContacts[this.listContacts.length - 1] + 1
        );
      }
    },
    trimOwnerName(lastName, firsName, patronymic) {
      return `${lastName} ${firsName[0]}.${patronymic[0]}.`;
    },
    trimMemberName(lastName, firsName, patronymic) {
      return `${lastName} ${firsName} ${patronymic}`;
    },
    sendEventData() {
      this.eventData = {
        id: this.id,
        start: this.mergeDate(this.eventDate, this.startTime),
        end: this.mergeDate(this.eventDate, this.endTime),
        kind: this.kind,
        employees: this.selectedEventData.employees
          ? this.employees
          : this.findEmployee(
              this.ownersData,
              this.ownersList,
              this.employees.employee
            ),
        members: this.selectedEventData.members
          ? this.members
          : this.findMember(
              this.membersData,
              this.membersList,
              this.members.person
            ),
      };
      this.clearForm();
      this.eventData = {};
    },
    clearForm() {
      this.$emit("clear-selected-event-data");
      this.closeForm();
    },
    mergeDate(eventDate, time) {
      return moment(`${eventDate} ${time}`).format();
    },
    findEmployee(requestedList, serializedList, employee) {
      let foundId = serializedList.find(({ label }) => label === employee).id;
      let foundPerson = requestedList.find(({ id }) => id === foundId);
      return {
        id: this.employees.id,
        employee: {
          id: foundPerson.id,
          last_name: foundPerson.last_name,
          first_name: foundPerson.first_name,
          patronymic: foundPerson.patronymic,
          color: foundPerson.color,
        },
        role: this.employees.role,
      };
    },
    findMember(requestedList, serializedList, member) {
      let foundId = serializedList.find(({ label }) => label === member).id;
      let foundPerson = requestedList.find(({ id }) => id === foundId);
      return {
        id: this.members.id,
        person: {
          id: foundPerson.id,
          last_name: foundPerson.last_name,
          first_name: foundPerson.first_name,
          patronymic: foundPerson.patronymic,
          color: foundPerson.color,
        },
        role: this.members.role,
      };
    },
  },
  watch: {
    startDate: {
      immediate: true,
      handler(newDate) {
        if (newDate) {
          this.eventDate = newDate.format("YYYY-MM-DD");
          this.startTime = newDate.format("HH:mm");
        }
      },
    },
    endDate: {
      immediate: true,
      handler(newDate) {
        if (newDate) {
          this.endTime = newDate.format("HH:mm");
        }
      },
    },
    selectedEventData: {
      immediate: true,
      handler(newDate) {
        if (newDate) {
          this.id = this.eventId;
          this.kind = this.eventKind;
          this.employees = this.eventEmployee;
          this.members = this.eventMember;
        }
      },
    },
  },
};
</script>

<style lang="sass" scoped>
.event-form
  height: fit-content
  min-width: 448px
  background-color: var(--bg-ligth-blue-color)
  box-shadow: -4px -4px 16px rgba(9, 10, 21, 0.25), 4px 4px 16px rgba(9, 10, 21, 0.25)
  border-radius: 4px
  z-index: 5

.form-item
  border-radius: 4px
  width: 344px
  background-color: var(--default-white)

.item-input
  appearance: none
  border: none
  outline: none
  height: 40px
  &::-webkit-calendar-picker-indicator
    display: none
    -webkit-appearance: none
  &::placeholder
    color: var(--font-black-color-1)

.time-input
  width: 72px
  border-radius: 4px
  background-color: var(--default-white)

.date-input
  width: 174px
  border-radius: 4px
  background-color: var(--default-white)

.icon
  width: 24px
  height: 24px
  color: var(--font-dark-blue-color)

.close-icon
  color: var(--font-dark-blue-color)
  &:hover
    color: var(--btn-blue-color)
.styled-button
  width: 183px
.select
  height: 40px
</style>
