<script setup>
import { ref } from 'vue';
import axios from 'axios';
import VnSelect from 'src/components/common/VnSelect.vue';
import { displayResults } from 'src/pages/Ticket/Negative/composables/notifyResults';

const { notifyResults } = displayResults();
const emit = defineEmits(['update-item']);

const showChangeItemDialog = ref(false);
const newItem = ref(null);
const $props = defineProps({
    selectedRows: {
        type: Array,
        default: () => [],
    },
});

const updateItem = async () => {
    try {
        showChangeItemDialog.value = true;
        const rowsToUpdate = $props.selectedRows.map(({ saleFk, quantity }) =>
            axios.post(`Sales/replaceItem`, {
                saleFk,
                substitutionFk: newItem.value,
                quantity,
            }),
        );
        const result = await Promise.allSettled(rowsToUpdate);
        notifyResults(result, 'saleFk');
        emit('update-item', newItem.value);
    } catch (err) {
        console.error('Error updating item:', err);
        return err;
    }
};
</script>

<template>
    <QCard class="q-pa-sm">
        <QCardSection class="row items-center justify-center column items-stretch">
            <span>{{ $t('negative.detail.modal.changeItem.title') }}</span>
            <VnSelect
                url="Items/WithName"
                :fields="['id', 'name']"
                :sort-by="['id DESC']"
                :options="items"
                option-label="name"
                option-value="id"
                v-model="newItem"
                autofocus
            >
            </VnSelect>
        </QCardSection>
        <QCardActions align="right">
            <QBtn :label="$t('globals.cancel')" color="primary" flat v-close-popup />
            <QBtn
                :label="$t('globals.confirm')"
                color="primary"
                :disable="!newItem"
                @click="updateItem"
                unelevated
                autofocus
            /> </QCardActions
    ></QCard>
</template>

<style lang="scss" scoped>
.list {
    max-height: 100%;
    padding: 15px;
    width: 100%;
}

.grid-style-transition {
    transition:
        transform 0.28s,
        background-color 0.28s;
}

#true {
    background-color: $positive;
}

#false {
    background-color: $negative;
}

div.q-dialog__inner > div {
    max-width: fit-content !important;
}
</style>
