<script setup>
import toCurrency from '../../../filters/toCurrency';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { useRoute } from 'vue-router';
import useNotify from 'composables/useNotify';

const { t } = useI18n();
const route = useRoute();
const { notify } = useNotify();
const props = defineProps({
    prices: {
        type: Array,
        required: true,
    },
});

const emit = defineEmits(['added']);

const fields = ref((props.prices || []).map((item) => ({ ...item, quantity: 0 })));

const addToOrder = async () => {
    const items = (fields.value || []).filter((item) => Number(item.quantity) > 0);
    await axios.post('/OrderRows/addToOrder', {
        items,
        orderFk: Number(route.params.id),
    });
    notify(t('globals.dataSaved'), 'positive');
    emit('added');
};
</script>

<template>
    <div class="container order-catalog-item q-pb-md">
        <QForm @submit.prevent="addToOrder">
            <QMarkupTable class="shadow-0">
                <tbody>
                    <tr v-for="item in fields" :key="item.warehouse">
                        <td class="text-bold q-py-lg">
                            {{ item.warehouse }}
                        </td>
                        <td class="text-right">
                            <span
                                class="link"
                                @click="
                                    () => {
                                        item.quantity += item.grouping;
                                    }
                                "
                            >
                                {{ item.grouping }}
                            </span>
                            x {{ toCurrency(item.price) }}
                        </td>
                        <td class="text-right">
                            <QInput
                                v-model.number="item.quantity"
                                type="number"
                                :step="item.grouping"
                                min="0"
                                dense
                            />
                        </td>
                    </tr>
                </tbody>
            </QMarkupTable>
            <div class="flex justify-center q-mt-lg">
                <QBtn color="primary" type="submit">
                    {{ t('globals.add') }}
                </QBtn>
            </div>
        </QForm>
    </div>
</template>

<style lang="scss" scoped>
.container {
    max-width: 448px;
    width: 100%;
}
</style>
