<template>
    <section class="section">
        <div id="root" class="container">
            <h1 class="title">
                Pedidos MPS
            </h1>
            <p class="subtitle">
                Bienvenidx a la aplicación de pedidos del <strong>Mercado Popular de Subsistencia</strong>
            </p>

            <div>
                <label class="label">Escribí el nombre de tu familia o grupo de convivencia</label>
                <div class="columns">
                    <div class="column is-two-thirds">
                        <div class="field">
                            <div class="control">
                                <input class="input" @input="onType" v-model="searchString"/>
                            </div>
                            <p class="help">Debe ser claro para que tus compas del barrio te identifiquen.</p>
                        </div>
                    </div>
                    <div class="column is-one-third buttons">
                        <button class="button is-danger" v-if="!deshabilitado" @click="submit(undefined)">
                            Crear nuevo pedido
                        </button>
                    </div>
                </div>
                <div v-if="pedidos.length" class="block">
                    <label class="label">
                        Si ya comenzaste a hacer tu pedido este mes, elegilo en esta lista:
                    </label>
                    <p class="help">
                        Podés seguir escribiendo en el campo de arriba para refinar la búsqueda.
                    </p>
                    <div class="columns is-mobile"
                         v-for="(subpedidoExistente, index) in pedidos"
                         :class="{'has-background-grey-lighter': index % 2}"
                         :key="index">
                        <div class="column is-half-mobile is-two-thirds-desktop is-two-thirds-tablet">
                            <p class="nombre">
                                {{ subpedidoExistente.nombre }}
                            </p>
                        </div>
                        <div class="buttons column is-half-mobile is-one-third-desktop is-one-third-tablet">
                            <button class="button is-danger" @click="submit(subpedidoExistente)">
                                Continuar pedido
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template><script>
import { mapActions, mapMutations, mapState } from "vuex";
import axios from "axios";

export default {
    name: 'PedidoSelect',
    async mounted() {
        await this.getGrupoDeCompra();
        const sesion = await axios.get("/pedido/sesion");
        if (sesion.data.id) {
            await this.elegirPedido({ pedido_id: sesion.data.id });
        }
    },
    data() {
        return {
            pedidos: [],
            searchString: null,
        }
    },
    computed: {
        ...mapState('pedido', ["grupo_de_compra"]),
        deshabilitado: function () {
            return !this.searchString?.trim()
                || this.pedidos.some(p => p.nombre.toLowerCase() === this.searchString.toLowerCase())
        }
    },
    methods: {
        ...mapActions('pedido', ["getGrupoDeCompra", "crearPedido", "elegirPedido"]),
        async getPedidos(nombre) {
            const response = await axios.get('/api/subpedidos/',{
                params: {
                    nombre: nombre,
                    grupo_de_compra: this.grupo_de_compra.id
                }
            });
            this.pedidos = response.data;
        },
        onType() {
            if (!this.searchString) {
                this.setPedidos([]);
                return;
            }
            this.getPedidos(this.searchString);
        },
        async submit(pedido) {
            if (pedido)
                await this.elegirPedido({ pedido_id: pedido.id });
            else
                await this.crearPedido({ nombre: this.searchString, grupo_de_compra_id: this.grupo_de_compra.id });
        },
    }
}
</script>

<style>
.nombre {
    padding-top: calc(.5em - 1px);
    margin-bottom: .5rem
}
</style>