Vue.component('subpedido-select', {
	data() {
		return {
			subpedido: null,
			subpedidosExistentes: []
		}
	},
  computed: {
    nombresDeSubpedidos: function() {
      return this.subpedidosExistentes.map(a => a.nombre.toLowerCase())
    },
    botonCrearDesabilitado : function() {
      return !this.subpedido || this.nombresDeSubpedidos.includes(this.subpedido.toLowerCase())
    }
  },
	props: ["gdcid"],
	mounted() {
		console.log("ready");
	},
	methods: {
  		onType() {
        if (!this.subpedido){
          this.subpedidosExistentes = [];
          return;
        }
	    	axios.get("/api/subpedidos", {
          params: {
            nombre: this.subpedido,
            grupo_de_compra: this.gdcid
          }
        }).then(response => {
	    		this.subpedidosExistentes = response.data
	    	});
  		},
  		submit() {
  			axios.post("/api/subpedidos", {
  				nombre: this.subpedido,
  				grupo_de_compra_id: this.gdcid
  			}).then(response => {
          //se creo el subpedido
          this.elegirSubpedido(response.data);
  			});
  		},
      elegirSubpedido(subpedido){
        //lo guardamos en sesion
        this.guardarSubpedidoEnSesion(subpedido);
      },
      guardarSubpedidoEnSesion(subpedido) {
        axios.post("/subpedidos/guardar_sesion", {
          subpedido: subpedido
        }).then(response => {
          window.location.href = 'productos';
        });
      }
  	}
});