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: [],
      isFilterOpen: false,
      orderBy: '',
      filterName: '',
    };
  },
  computed: {
    schedule() {
      return store.state.schedules;
    },
    filteredSchedules() {
      let filteredList = this.filterByName();
          
      if (this.orderBy) {
        filteredList = this.OrderByAscDesc(filteredList);
      }  

      return filteredList; 
    }
  },
  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;
      }
    },
    // More Filters
    filterByName() {
      return !this.filterName 
      ? this.newSchedules 
      : this.newSchedules.filter(item => 
          item.name.toLowerCase().includes(this.filterName.toLowerCase())
        );        
    },
    OrderByAscDesc(dataList) {
      const parseCustomDate = (dateString) => {
        const [day, month, year] = dateString.split('/');
        return new Date(year, month - 1, day);
      };

      return dataList.sort((a, b) => {
          
        const dateA = parseCustomDate(a.date_start);
        const dateB = parseCustomDate(b.date_start);
  
        if (this.orderBy === 'asc') {
          return dateA - dateB; 
        } else if (this.orderBy === 'desc') {
          return dateB - dateA; 
        }
      });
    },
    //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 getScheduleWithoutOrder() {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/getScheduleWithoutOrder&token=' + this.token,
        data: param(),
      })
        .then(({ data }) => {
          if (data) {
            this.schedules = data;
            store.dispatch('getSchedules', this.schedules);
          }
        })
        .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();
    this.getScheduleWithoutOrder();    
  },
});

initVue(vm);
