import Vue from 'vue';
import initVue from '@assets/js/initVue';
import axiosApi from '@assets/js/axios-api';
import param from '@assets/js/param';

const vm = new Vue({
  components: {
    BaseListing: () => import(/* webpackChunkName: "BaseListing" */ '@elements/BaseListing/index.vue'),
    BaseContent: () => import(/* webpackChunkName: "BaseContent" */ '@elements/BaseContent/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "Basebutton" */ '@elements/BaseButton/index.vue'),
    BaseSelect: () => import(/* webpackChunkName: "BaseSelect" */ '@elements/BaseSelect/index.vue'),
    BaseSearchOrder: () => import(/* webpackChunkName: "BaseSearchOrder" */ '@elements/BaseSearchOrder/index.vue'),
    listPagination: () => import(/* webpackChunkName: "listPagination" */ '@components/ThePagination/index.vue'),
  },
  data() {
    return {
      orders: {},
      showIcon: false,
      searchBar: true,
      pagination: [],
      currentPage: 1,
      limit: 10,
      inputValue: '',
      newPagination: false,
      data: true,
      loader: false,
      allResults: 0,
      textResults: true,
      dateValue: 0,
      onLoad: false,
      dateZero: '0000-00-00 00:00:00',
      dates: [
        {
          id: 0,
          name: 'Todos os períodos',
        },
        {
          id: 1,
          name: 'Somente este mês',
        },
        {
          id: 3,
          name: 'Últimos 3 meses',
        },
        {
          id: 6,
          name: 'Últimos 6 meses',
        },
        {
          id: 9,
          name: 'Últimos 9 meses',
        },
        {
          id: 12,
          name: 'Útimos 12 meses',
        },
      ],    
    };
  },
  methods: {
    setData({ orders, order_totals }) {
      this.orders = orders;
      this.transformPrice(this.orders);
      this.allResults = order_totals;
    },
    setDate(id) {
      var mounths = id;
      var days = 1;
      var date = new Date();
      if (id == 1) mounths = 0;
      if (id > 1) days = date.getDate();
      var oldDate = new Date(date.getFullYear(), date.getMonth() - mounths, days);
      var year = oldDate.getFullYear();
      var mounth = ('0' + (oldDate.getMonth() + 1)).slice(-2);
      var day = ('0' + oldDate.getDate()).slice(-2);
      var hours = ('0' + date.getHours()).slice(-2);
      var minuts = ('0' + date.getMinutes()).slice(-2);
      var seconds = ('0' + date.getSeconds()).slice(-2);
      if (id == 1) hours = '00', minuts = '00', seconds = '00';
      var formattedDate = year + '-' + mounth + '-' + day + ' ' + hours + ':' + minuts + ':' + seconds;
      this.dateValue = formattedDate;
      if (id == 0) this.dateValue = this.dateZero;
      if (this.onLoad) this.setFilter(this.inputValue, true, false);
    },
    transformPrice(orders) {
      if (orders) {
        orders.map(item => {
          item.products_slice.map(product => {
            if (product.total_price) {
              const price = parseFloat(product.total_price).toFixed(2);
              const formattedNumber = price.toString().replace('.', ',');
              return (product.price = formattedNumber);
            } else {
              const price = parseFloat(product.price).toFixed(2);
              const formattedNumber = price.toString().replace('.', ',');
              return (product.price = formattedNumber);
            }
          });
        });
      }
    },
    limitText(text, maxLength) {
      if (text) {
        if (text.length > maxLength) {
          return text.substring(0, maxLength) + '...';
        }
        return text;
      }
    },
    orderStatus(orders) {
      if (orders === 'top-border-gray') return 'default';
      if (orders === 'top-border-success') return 'success';
      if (orders === 'top-border-error') return 'error';
    },
    changeSearch() {
      this.searchBar = !this.searchBar;
    },
    clearSearch() {
      this.inputValue = '';
      this.dateValue = this.dateZero;
      this.$refs.search.clearInput();
      this.$refs.search2.clearInput();
      this.textResults = true;
      this.setDate(0);
      this.$refs.date.value = 0;
    },
    page(value) {
      this.currentPage = value;
      this.filter(this.inputValue, false, this.dateValue);
    },
    setFilter(value, bool, bool2) {
      if(bool2) this.$refs.date.value = 0, this.dateValue = this.dateZero;
      this.filter(value, bool, this.dateValue);
    },
    filter(value, isSearchBar, dateFilter) {
      if (isSearchBar) {
        this.currentPage = 1;
      }

      this.newPagination = true;
      this.loader = true;
      this.$refs.search.loaderInput(this.loader);
      this.$refs.search2.loaderInput(this.loader);

      axiosApi({
        method: 'POST',
        url: 'index.php?route=account/order/searchOrder',
        data: param({ filters: value, page: this.currentPage, date_value: dateFilter }),
      })
        .then(({ data }) => {
          this.data = data;
          this.orders = data.orders;
          this.transformPrice(data.orders);
          this.orderStatus(data.orders);

          if (data.pagination) {
            this.pagination = data.pagination;
          }
          if (data.limit) {
            this.limit = parseInt(data.limit);
          }
          if (data.allResults) {
            this.allResults = data.allResults;
          }
          if (!data) {
            this.allResults = 0;
          }

          this.loader = false;
          this.$refs.search.loaderInput(this.loader);
          this.$refs.search2.loaderInput(this.loader);
          this.textResults = false;

          if (!value) {
            this.textResults = true;
          }
        })
        .catch(err => console.log(err, err.response));
    },
  },
  watch: {},
  mounted() {
    this.setDate(0);
    this.onLoad = true;
  },
});

initVue(vm);
