import AdmVue from '@assets/js/adm-vue';
import initVue from '@assets/js/initVue';

import axiosApi, { param } from '@assets/js/axios-api';
import store from '@components/Schedule/storeSchedule.js';

const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;

const vm = new AdmVue({
  components: {
    BaseRadio: () => import(/* webpackChunkName: "BaseRadio" */ '@elements/BaseRadio/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "Basebutton" */ '@elements/BaseButton/index.vue'),
    ScheduleItem: () => import(/* webpackChunkName: "ScheduleItem" */ '@components/Schedule/ScheduleItem/index.vue'),
    ScheduleForm: () => import(/* webpackChunkName: "ScheduleForm" */ '@components/Schedule/ScheduleForm/index.vue'),
    ScheduleTable: () => import(/* webpackChunkName: "ScheduleTable" */ '@components/Schedule/ScheduleTable/index.vue'),
  },
  data() {
    return {
      tabs: [
        { text: 'Cadastro de Agendas', active: true },
        { text: 'Listagem de Agendamentos', active: false },
      ],
      token: '',
      scheduleId: '',
      showForm: false,
      schedules: [],
      newSchedules: [],
      loader: true,
      status: 1,
      activeStatusSchedule: [],
      inactiveStatusSchedule: [],
    };
  },
  computed: {
    schedule() {
      return store.state.schedules;
    },
  },
  watch: {
    schedules(newValue, oldValue) {
      const storeSchedules = newValue;
      const arrayFormat = storeSchedules.map(objeto => ({
        ...objeto,
        status: parseInt(objeto.status),
        date_start: this.dateFormat(objeto.date_start),
        date_end: this.dateFormat(objeto.date_end),
      }));
      const arrayOrdered = arrayFormat.sort(this.comperObjects);

      this.activeStatusSchedule = arrayOrdered.filter(schedule => schedule.status === 1);
      this.inactiveStatusSchedule = arrayOrdered.filter(schedule => schedule.status === 0);
      this.newSchedules = this.activeStatusSchedule;
    },
    schedule(newValue, oldValue) {
      this.schedules = newValue;
    },
    status(newValue, oldValue) {
      if (newValue) this.newSchedules = this.activeStatusSchedule;
      else this.newSchedules = this.inactiveStatusSchedule;
      if (this.newSchedules.length) this.scheduleId = this.newSchedules[0].schedule_id;
    },
  },
  methods: {
    handleShowForm() {
      this.showForm = true;
    },
    callbackCreateForm(propValue) {
      this.showForm = propValue;
    },
    scheduleChoice(scheduleId) {
      this.scheduleId = scheduleId;

      const addFocus = document.querySelectorAll('.addFocus');
      addFocus.forEach(item => {
        item.classList.remove('addFocus');
      });

      if (this.newSchedules) {
        this.newSchedules.map(item => {
          var item = document.getElementById(scheduleId);
          item.classList.add('addFocus');
        });
      }
    },
    dateFormat(dateString) {
      if (dateString.includes('/')) {
        return dateString;
      } else {
        const [year, month, day] = dateString.split('-');
        return `${day}/${month}/${year}`;
      }
    },
    comperObjects(a, b) {
      if (a.status > b.status) return -1;
      if (a.status < b.status) return 1;

      const dateA = new Date(
        a.date_start
          .split('/')
          .reverse()
          .join('/')
      );
      const dateB = new Date(
        b.date_start
          .split('/')
          .reverse()
          .join('/')
      );
      return dateA - dateB;
    },
    load(value) {
      if (value && this.newSchedules.length) {
        this.scheduleChoice(this.newSchedules[0].schedule_id);
      }
    },
    unLoad(value) {
      if (value) this.scheduleId = '';
    },
    limitText(text, maxLength) {
      if (text) {
        if (text.length > maxLength) {
          return text.substring(0, maxLength) + '...';
        }
        return text;
      }
    },
    checkExpireDate(data) {
      var expiredDateIds = [];
      var actualDate = new Date();
      var actualDateFormat = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate());

      data.map(schedule => {
        var partsDate = schedule.date_end.split('-');
        var dateCompare = new Date(partsDate[0], partsDate[1] - 1, partsDate[2]);

        if (dateCompare < actualDateFormat && schedule.status === '1') {
          expiredDateIds.push(schedule.schedule_id);
        }
      });

      if (expiredDateIds.length) {
        this.updateScheduleStatus(expiredDateIds);
      } else {
        this.loader = false;
        this.schedules = data;
        store.dispatch('getSchedules', this.schedules);
      }
    },
    //requests
    async getSchedule() {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/getSchedule&token=' + this.token,
        data: param(),
      })
        .then(({ data }) => {
          if (data) {
            this.checkExpireDate(data);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    async updateScheduleStatus(value) {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/updateScheduleStatus&token=' + this.token,
        data: param({ status: value }),
      })
        .then(({ data }) => {
          if (data) {
            this.getSchedule();
          }
        })
        .catch(err => console.log(err, err.response));
    },
  },
  mounted() {
    this.getSchedule();
  },
});

initVue(vm);
