<template>
    <form @submit.prevent="validate">
        <div class="grid grid-cols-2 gap-x-40 gap-y-8 mb-16">
            <UiNumberInput
                label="Pesée à vide"
                v-model="form.weights[0].weight"
                :min="0"
            />

            <UiNumberInput
                label="Pesée à plein"
                v-model="form.weights[1].weight"
                :min="0"
            />
        </div>

        <button
            type="submit"
            class="bg-primary-500 text-white px-6 py-3 rounded-md"
        >
            Enregistrer
        </button>
    </form>
</template>

<script setup lang="ts">
import type {ReceptionFormWeight, ReceptionUpdatePayload} from '~/services/dto/reception-data'
import { getReception } from '~/services/reception'
import { useReceptionStore } from '~/stores/reception'
import {updateWeight} from "~/services/weight";

const props = defineProps<{
    idReception: number
}>()

const receptionStore = useReceptionStore()
const router = useRouter()

const form = reactive({
    weights: [
        { id: 0, type: 'tare' as const, weight: 0 },
        { id: 0, type: 'gross' as const, weight: 0 }
    ]
})

const hydrateFromReception = (reception: ReceptionFormWeight) => {
    const tare = reception.weights.find(weight => weight.type === 'tare')
    const gross = reception.weights.find(weight => weight.type === 'gross')

    if (tare) form.weights[0] = { ...tare }
    if (gross) form.weights[1] = { ...gross }
}

onMounted(async () => {
    const reception = await getReception(props.idReception)
    hydrateFromReception(reception)
})

async function validate() {

    for (const weight of form.weights) {
        if (weight.id) {
            await updateWeight(weight.id, {weight: weight.weight})
        }
    }
}
</script>
