<template>
    <Teleport :to="$actions">
        <div class="balance">
            <span class="label">{{ $t('balance') }}</span>
            <span class="amount" :class="{ negative: debt < 0 }">
                {{ currency(debt || 0) }}
            </span>
            <QIcon
                name="info"
                :title="$t('paymentInfo')"
                class="info"
                size="24px"
            />
        </div>
        <QBtn
            icon="payments"
            :label="$t('makePayment')"
            @click="onPayClick()"
            rounded
            no-caps
        />
        <QBtn
            to="/ecomerce/basket"
            icon="shopping_cart"
            :label="$t('shoppingCart')"
            rounded
            no-caps
        />
    </Teleport>
    <div class="vn-w-sm">
        <div
            v-if="!orders?.length"
            class="text-subtitle1 text-center text-grey-7 q-pa-md"
        >
            {{ $t('noOrdersFound') }}
        </div>
        <QCard v-if="orders?.length">
            <QList bordered separator padding>
                <QItem
                    v-for="order in orders"
                    :key="order.id"
                    :to="`ticket/${order.id}`"
                    clickable
                    v-ripple
                >
                    <QItemSection>
                        <QItemLabel>
                            {{ date(order.landed, 'ddd, MMMM Do') }}
                        </QItemLabel>
                        <QItemLabel caption>#{{ order.id }}</QItemLabel>
                        <QItemLabel caption>{{ order.nickname }}</QItemLabel>
                        <QItemLabel caption>{{ order.agency }}</QItemLabel>
                    </QItemSection>
                    <QItemSection side top> {{ order.total }}€ </QItemSection>
                </QItem>
            </QList>
        </QCard>
        <QPageSticky>
            <QBtn
                fab
                icon="add_shopping_cart"
                color="accent"
                to="/ecomerce/catalog"
                :title="$t('startOrder')"
            />
        </QPageSticky>
    </div>
</template>

<style lang="scss" scoped>
.balance {
    margin-right: 8px;
    white-space: nowrap;
    display: inline-block;

    & > * {
        vertical-align: middle;
    }
    & > .amount {
        padding: 4px;
        margin: 0 4px;

        &.negative {
            background-color: #e55;
            border-radius: 2px;
            box-shadow: 0 0 5px #333;
        }
    }
    & > .info {
        cursor: pointer;
    }
}
</style>

<script>
import { date, currency } from 'src/lib/filters.js';
import { tpvStore } from 'stores/tpv';

export default {
    name: 'OrdersPendingIndex',
    data() {
        return {
            orders: null,
            debt: 0,
            tpv: tpvStore()
        };
    },

    async mounted() {
        await this.tpv.check(this.$route);

        this.orders = await this.$jApi.query('CALL myTicket_list(NULL, NULL)');
        this.debt = await this.$jApi.getValue('SELECT -myClient_getDebt(NULL)');
    },

    methods: {
        date,
        currency,

        async onPayClick() {
            let amount = -this.debt;
            amount = amount <= 0 ? null : amount;

            let defaultAmountStr = '';
            if (amount !== null) {
                defaultAmountStr = amount;
            }
            amount = prompt(this.$t('amountToPay'), defaultAmountStr);

            if (amount != null) {
                amount = parseFloat(amount.replace(',', '.'));
                await this.tpv.pay(amount);
            }
        }
    }
};
</script>

<i18n lang="yaml">
en-US:
    startOrder: Start order
    noOrdersFound: No orders found
    makePayment: Make payment
    shoppingCart: Shopping cart
    balance: 'Balance:'
    paymentInfo: >-
        The amount shown is your slope (negative) or favorable balance today, it
        disregards future orders. For get your order shipped, this amount must be
        equal to or greater than 0. If you want to make a down payment, click the
        payment button, delete the suggested amount and enter the amount you want.
es-ES:
    startOrder: Empezar pedido
    noOrdersFound: No se encontrado pedidos
    makePayment: Realizar pago
    shoppingCart: Cesta de la compra
    balance: 'Saldo:'
    paymentInfo: >-
        La cantidad mostrada es tu saldo pendiente (negativa) o favorable a día de
        hoy, no tiene en cuenta pedidos del futuro. Para que tu pedido sea enviado,
        esta cantidad debe ser igual o mayor que 0. Si quieres realizar una entrega a
        cuenta, pulsa el botón de pago, borra la cantidad sugerida e introduce la
        cantidad que desees.
ca-ES:
    startOrder: Començar encàrrec
    noOrdersFound: No s'han trobat comandes
    makePayment: Realitzar pagament
    shoppingCart: Cistella de la compra
    balance: 'Saldo:'
    paymentInfo: >-
        La quantitat mostrada és el teu saldo pendent (negatiu) o favorable a dia
        d'avui, no té en compte comandes del futur. Perquè la teva comanda sigui
        enviat, aquesta quantitat ha de ser igual o més gran que 0. Si vols fer un
        lliurament a compte, prem el botó de pagament, esborra la quantitat suggerida
        e introdueix la quantitat que vulguis.
fr-FR:
    startOrder: Acheter
    noOrdersFound: Aucune commande trouvée
    makePayment: Effectuer un paiement
    shoppingCart: Panier
    balance: 'Balance:'
    paymentInfo: >-
        Le montant indiqué est votre pente (négative) ou balance favorable
        aujourd'hui, ne tient pas compte pour les commandes futures. Obtenir votre
        commande est expédiée, ce montant doit être égal ou supérieur à 0. Si vous
        voulez faire un versement, le montant suggéré effacé et entrez le montant que
        vous souhaitez.
pt-PT:
    startOrder: Iniciar encomenda
    noOrdersFound: Nenhum pedido encontrado
    makePayment: Realizar pagamento
    shoppingCart: Cesta da compra
    balance: 'Saldo:'
    paymentInfo: >-
        A quantidade mostrada é seu saldo pendente (negativo) ou favorável a dia de
        hoje, não se vincula a pedidos futuros. Para que seu pedido seja enviado, esta
        quantidade deve ser igual ou superior a 0. Se queres realizar um depósito à
        conta, clique no botão de pagamento, apague a quantidade sugerida e introduza
        a quantidade que deseje.
</i18n>
