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

const vm = new Vue({
  data() {
    return {
      heading: 'Devolução do Produto',
      orderId: '',
      urlSearchOrder: '',
      lastOrders: [],
      orderProducts: [],
      back: '',
      section: '',
      searchValue: '',
      site_key: '',
      google_captcha: '',
      showKit: [],
      quantityProduct: '',
      error: [],
      product_id: [],
      quantity: [],
      opened: [],
      showNotificationMessage: false,
      return_reasons: [],
      return_reason_id: '',
      agree: '',
      comment: '',
      selectKit: [{}],
      updateSelect: 0,
      productIdSelected: [],
      showMobile: false,
      showDesktop: false,
      selectAllProduct: false,
      valid: []
    }
  },
  components: {
    BaseContent: () => import(/* webpackChunkName: "BaseContent" */ '@elements/BaseContent/index.vue'),
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
  },
  methods: {
    setData({ last_orders, url_search_order, back, site_key, google_captcha, error, product_id, quantity, showKit, opened, return_reasons, return_reason_id, agree, comment, selectAllProduct }) {
      this.lastOrders = last_orders ? last_orders : [];
      this.urlSearchOrder = url_search_order;
      this.back = back;
      this.site_key = site_key;
      this.google_captcha = google_captcha;
      this.error = error;
      this.product_id = product_id;
      this.quantity = quantity;
      this.showKit = showKit;
      this.opened = opened;
      this.return_reasons = return_reasons;
      this.return_reason_id = return_reason_id;
      this.agree = agree;
      this.comment = comment;
      this.selectAllProduct = selectAllProduct;

      if (product_id) {
        this.productIdSelected = product_id
      }

      Object.keys(this.error).map(key => {
        if (this.error[key] != "") {
          return this.showNotificationMessage = true;
        }
      });

      if (this.showNotificationMessage) {
        notificationMsg("Alguns campos estão incorretos. Corrija os campos em vermelho.", "error");
      }
    },
    handleButtonReturnOrder(orderId) {
      this.returnOrder(orderId);
    },
    handleProductName(productName, maxLength) {
      if (productName.length > maxLength) {
        return productName.substring(0, maxLength) + '...'
      }
      return productName;
    },
    handleSelectAllProduct() {
      this.selectAllProduct = !this.selectAllProduct ? true : false;
      
      this.productIdSelected = []

      if (this.selectAllProduct) {
        this.orderProducts.map((item, index) => {
          this.productIdSelected[index] = item.product_id
        })
      } else {
        this.orderProducts.map((item, index) => {
          this.productIdSelected[index] = ''
        })
      }

      this.updateSelect += 1
    },
    hiddenError() {
      if (this.error.error_product_not_selected) {
        this.error.error_product_not_selected = ""
      }
    },
    handleProductRadio(index, key, isKit, event) {
      this.hiddenError();

      if (isKit) {
        this.$refs['radio_produto'][index].getAttribute('index') == index ? this.$refs['radio_produto'][index].checked = false : null;

        if (!Array.isArray(this.productIdSelected[index])) {
          this.productIdSelected[index] = []
        }

        if (this.productIdSelected[index][key] && this.productIdSelected[index][key] == event.target.value) {
          this.$refs['radio_kit'].forEach((item) => {
            if (item.getAttribute('index') == index && item.getAttribute('kit') == key) {
              item.checked = false
            }
          })
          this.productIdSelected[index][key] = '';
        } else {
          this.$refs['radio_kit'].forEach((item) => {
            if (item.getAttribute('index') == index && item.getAttribute('kit') == key) {
              item.checked = true
            }
          })
          this.productIdSelected[index][key] = event.target.value;
        }
      } else {
        this.$refs['radio_kit'] && this.$refs['radio_kit'].forEach(item => {
          item.getAttribute('index') == index ? item.checked = false : null;
        });

        if (Array.isArray(this.productIdSelected[index])) {
          this.productIdSelected[index] = ""
        }

        if (this.productIdSelected[index] && this.productIdSelected[index] == event.target.value) {
          this.$refs['radio_produto'][index].checked = false;
          this.productIdSelected[index] = '';
        } else {
          this.$refs['radio_produto'][index].checked = true;
          this.productIdSelected[index] = event.target.value;
        }
      }
    },
    handleReturnReason() {
      this.error.error_reason = "";
    },
    orderNotFound(show = false) {
      const divNotFound = document.querySelector('.js-order-not-found');
      if (!show) {
        divNotFound.classList.add('hidden');
      } else {
        divNotFound.classList.remove('hidden');
      }
    },
    orderCanceled(show = false) {
      const divCanceled = document.querySelector('.js-order-canceled');
      if (!show) {
        divCanceled.classList.add('hidden');
      } else {
        divCanceled.classList.remove('hidden');
      }
    },
    OnInputSearch(event) {
      this.searchValue = event.target.value;
    },
    handleSearchOrder() {
      this.returnOrder(this.searchValue);
    },
    handleError(nameInput, index, product_id, event){
      if(this.error.error_quantity[index] && this.error.error_quantity[index][product_id] && this.quantity[index][product_id] != ""){
        this.error.error_quantity[index][product_id] = ''
        this.quantity[index][product_id] = event.target.value
      }
    },
    showSearchOrders(show = true) {
      const divSearchOrders = document.querySelector('.js-container-search');
      const divReturn = document.querySelector('.js-container-return');
      if (!show) {
        divSearchOrders.classList.add('hidden');
        divReturn.classList.remove('hidden');
      } else {
        divSearchOrders.classList.remove('hidden');
        divReturn.classList.add('hidden');
      }
    },
    renderProducts(orderProducts) {
      this.orderProducts = [];

      orderProducts.map(product => {
        let {
          id,
          product_id,
          name,
          quantity,
          quantidade,
          thumb,
          color_description,
          color_template_description,
          size_description,
          size_template_description,
          specification_template_description,
          specification_description,
          model_value_on_screen,
          itens_kit,
        } = product;

        color_description = color_description || '';
        size_description = size_description || '';
        specification_description = specification_description || '';
        itens_kit = itens_kit || '';

        this.orderProducts.push({
          product_id: product_id || id,
          name,
          quantity,
          quantidade,
          thumb,
          itens_kit,
          color_description,
          color_template_description,
          size_description,
          size_template_description,
          specification_template_description,
          specification_description,
          model_value_on_screen
        });
      });
    },
    handleBackButton() {
      const divSearchOrders = document.querySelector('.js-container-search');

      if (divSearchOrders.classList.contains('hidden')) {
        event.preventDefault();
      }

      this.orderId = '';

      this.orderNotFound();
      this.showSearchOrders(true);
    },
    reCaptchaRender() {
      if (!this.session_captcha) {
        if (this.google_captcha && typeof grecaptcha.render != 'undefined') {
          let grecaptchaDiv = document.querySelector('#grecaptcha');
          grecaptcha.render(grecaptchaDiv, {
            sitekey: this.site_key,
          });
        } else {
          setTimeout(() => {
            this.reCaptchaRender();
          }, 400);
        }
      }
    },
    handleCookieAgree() {
      this.error.error_agree = "";
    },
    resizeWindow(event) {
      if (event.target.innerWidth <= 700) {
        this.showMobile = true;
        this.showDesktop = false
      }

      if (event.target.innerWidth > 700) {
        this.showMobile = false;
        this.showDesktop = true;
      }
    },
    returnOrder(searchValue) {
      if (this.section.dataset.orderId != searchValue) {
        this.product_id = [];
        this.quantity = [];
        this.showKit = [];
        this.opened = [];
        this.return_reason_id = '';
        this.agree = '';
        this.comment = '';

        Object.keys(this.error).map(key => {
          if (this.error[key] != "") {
            this.error[key] = "";
          }
        });
      }

      axiosApi({
        method: 'get',
        url: this.urlSearchOrder,
        params: { search: searchValue },
      })
        .then(({ data }) => {
          const { order, orderProducts } = data;

          if (order && orderProducts) {
            this.orderId = order.order_id;

            if (order.status_futuraserver == Type_PedidoStatus.TpPSt_Cancelado) {
              this.orderNotFound();
              this.orderCanceled(true);
            } else {
              this.orderCanceled();
              this.renderProducts(orderProducts);
              this.orderNotFound();
              this.showSearchOrders(false);
            }
          } else {
            this.orderCanceled();
            this.orderNotFound(true);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  mounted() {
    const section = document.querySelector('#root');
    this.section = section;

    if (this.section.dataset.orderId) {
      this.returnOrder(this.section.dataset.orderId);
    }
  },
  created() {
    this.reCaptchaRender();

    if (window.innerWidth <= 700) {
      this.showMobile = true;
      this.showDesktop = false
    }

    if (window.innerWidth > 700) {
      this.showMobile = false;
      this.showDesktop = true;
    }

    window.addEventListener('resize', this.resizeWindow);
  }
})

initVue(vm);



