/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */
import axios from 'axios';
import Vue from 'vue';
window.Vue = require('vue');
window.Event = new Vue();
window.axios = axios;
window.bulmaToast = require('bulma-toast');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */
import './components';

/**
 * Constants
 */
Vue.prototype.$rootMiga = {
  nombre: "Categorías",
  href: "/productos"
}
/**
 * Global methods
 */
Vue.prototype.$settearProducto = function(cantidad, id) {
  Event.$emit("sync-subpedido", this.cant, this.producto.id)
}
Vue.prototype.$toast = function(mensaje, duration = 2000) {
  return window.bulmaToast.toast({
    message: mensaje,
    duration: duration,
    type: 'is-danger',
    position: 'bottom-center',
  });
}
Vue.prototype.$limpiarFloat = function(unFloat) {
  return parseFloat(unFloat.replace(/,/g, ''))
}
Vue.prototype.$limpiarInt = function(unInt) {
  return parseInt(unInt.replace(/,/g, ''))
}

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
const app = new Vue({
    el: '#root',
    data() {
      return {
        gdc: null,
        pedido: null,
        devoluciones: null,
      }
    },
    computed: {
      productos: function() {
        return this.pedido.productos
      }
    },
    methods: {
      cantidad(producto) {
        let pedido = this.productos.some(p => p.id == producto.id)
        return pedido ? this.productos.find(p => p.id == producto.id).pivot.cantidad : 0
      },
      notas(producto) {
        let pedido = this.productos.some(p => p.id == producto.id);
        return pedido ? this.productos.find(p => p.id == producto.id).pivot.notas : "";
      },
        settearDevoluciones() {
            axios.get(`/api/grupos-de-compra/${this.gdc}/devoluciones`)
                .then(response => {
                    this.devoluciones = response.data.devoluciones;
                });
        }
    },
    mounted() {
        Event.$on('obtener-sesion', () => {
            axios.get('/subpedidos/obtener_sesion')
                .then(response => {
                    if (response.data.subpedido.id) {
                        this.gdc = response.data.gdc;
                        this.settearDevoluciones();
                        this.pedido = response.data.subpedido.id;
                        axios.get('/api/subpedidos/' + this.pedido)
                            .then(response => {
                                this.pedido = response.data.data;
                                Event.$emit("pedido-actualizado");
                            });
                    } else {
                        axios.get('/admin/obtener_sesion')
                            .then(response => {
                                this.gdc = response.data.gdc
                            });
                    }
                })
        })
      Event.$on('sync-subpedido', (cantidad, id, notas) => {
          if (this.pedido.aprobado) {
            this.$toast('No se puede modificar un pedido ya aprobado', 2000);
            return;
          }
          axios.post("/api/subpedidos/" + this.pedido.id + "/sync", {
            cantidad: cantidad,
            producto_id: id,
            notas: notas,
          }).then((response) => {
            this.pedido = response.data.data
            this.$toast('Pedido actualizado exitosamente')
            Event.$emit("pedido-actualizado");
          });
        });
      // Actualizar monto y notas de devoluciones
      Event.$on('sync-devoluciones', (total, notas) => {
        if (this.pedido.aprobado) {
          this.$toast('No se puede modificar un pedido ya aprobado', 2000);
          return;
        }

        axios.post("api/subpedidos/" + this.pedido.id + "/sync_devoluciones", {
          total: total,
          notas: notas,
        }).then((response) => {
          this.pedido = response.data.data;
          this.$toast('Pedido actualizado');
          Event.$emit("pedido-actualizado");
        });
      });

      Event.$on('aprobacion-subpedido', (subpedidoId, aprobado) => {
        axios.post("/api/admin/subpedidos/" + subpedidoId + "/aprobacion", {
          aprobacion: aprobado
        }).then((response) => {
          Event.$emit('sync-aprobacion', response.data.data);
          this.$toast('Pedido ' + (aprobado ? 'aprobado' : 'desaprobado') + ' exitosamente')
        })
      })
      Event.$emit('obtener-sesion')
    },
});