<script setup>
import { onBeforeMount, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

import axios from 'axios';
import VnLocation from 'src/components/common/VnLocation.vue';
import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.vue';
import VnSelectDialog from 'src/components/common/VnSelectDialog.vue';
import CustomerCreateNewPostcode from 'src/components/CreateNewPostcodeForm.vue';
import CustomsNewCustomsAgent from 'src/pages/Customer/components/CustomerNewCustomsAgent.vue';

const { t } = useI18n();
const route = useRoute();

const urlUpdate = ref('');
const postcodesOptions = ref([]);
const agencyModes = ref([]);
const incoterms = ref([]);
const customsAgents = ref([]);
const observationTypes = ref([]);
const notes = ref([]);

onBeforeMount(() => {
    urlUpdate.value = `Clients/${route.params.id}/updateAddress/${route.params.consigneeId}`;
});

const getData = async (observations) => {
    observationTypes.value = observations;

    if (observationTypes.value.length) {
        const filter = {
            fields: ['id', 'addressFk', 'observationTypeFk', 'description'],
            where: { addressFk: `${route.params.consigneeId}` },
        };
        const { data } = await axios.get('AddressObservations', {
            params: { filter: JSON.stringify(filter) },
        });

        if (data.length) {
            notes.value = data
                .map((observation) => {
                    const type = observationTypes.value.find(
                        (type) => type.id === observation.observationTypeFk
                    );
                    return type
                        ? {
                              $isNew: false,
                              $oldData: null,
                              $orgIndex: null,
                              addressFk: `${route.params.consigneeId}`,
                              description: observation.description,
                              observationTypeFk: type.id,
                          }
                        : null;
                })
                .filter((item) => item !== null);
        }
    }
};

const addNote = () => {
    notes.value.push({
        $isNew: true,
        $oldData: null,
        $orgIndex: null,
        addressFk: `${route.params.consigneeId}`,
        description: '',
        observationTypeFk: '',
    });
};

const deleteNote = (index) => {
    notes.value.splice(index, 1);
};

const onDataSaved = () => {
    const payload = {
        creates: notes.value,
    };
    axios.post('AddressObservations/crud', payload);
};
function handleLocation(data, location) {
    const { town, code, provinceFk, countryFk } = location ?? {};
    data.postalCode = code;
    data.city = town;
    data.provinceFk = provinceFk;
    data.countryFk = countryFk;
}
</script>

<template>
    <fetch-data
        @on-fetch="(data) => (agencyModes = data)"
        auto-load
        url="AgencyModes/isActive"
    />
    <fetch-data @on-fetch="(data) => (incoterms = data)" auto-load url="Incoterms" />
    <fetch-data
        @on-fetch="(data) => (customsAgents = data)"
        auto-load
        url="CustomsAgents"
    />
    <fetch-data @on-fetch="getData" auto-load url="ObservationTypes" />

    <FormModel
        :observe-form-changes="false"
        :url-update="urlUpdate"
        :url="`Addresses/${route.params.consigneeId}`"
        @on-data-saved="onDataSaved()"
        auto-load
        model="client"
    >
        <template #form="{ data, validate }">
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <QCheckbox :label="t('Enabled')" v-model="data.isActive" />
                </div>
                <div class="col">
                    <QCheckbox
                        :label="t('Is equalizated')"
                        v-model="data.isEqualizated"
                    />
                </div>
                <div class="col">
                    <QCheckbox
                        :label="t('Is Loginflora allowed')"
                        v-model="data.isLogifloraAllowed"
                    />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnInput :label="t('Consignee')" v-model="data.nickname" />
                </div>
                <div class="col">
                    <VnInput :label="t('Street address')" v-model="data.street" />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnLocation
                        :rules="validate('Worker.postcode')"
                        :roles-allowed-to-create="['deliveryAssistant']"
                        :options="postcodesOptions"
                        v-model="data.location"
                        @update:model-value="(location) => handleLocation(data, location)"
                    ></VnLocation>
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Agency')"
                        :options="agencyModes"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="data.agencyModeFk"
                    />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnInput :label="t('Phone')" v-model="data.phone" />
                </div>
                <div class="col">
                    <VnInput :label="t('Mobile')" v-model="data.mobile" />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Incoterms')"
                        :options="incoterms"
                        hide-selected
                        option-label="name"
                        option-value="code"
                        v-model="data.incotermsFk"
                    />
                </div>
                <div class="col">
                    <VnSelectDialog
                        :label="t('Customs agent')"
                        :options="customsAgents"
                        hide-selected
                        option-label="fiscalName"
                        option-value="id"
                        v-model="data.customsAgentFk"
                    >
                        <template #form>
                            <CustomsNewCustomsAgent />
                        </template>
                    </VnSelectDialog>
                </div>
            </VnRow>

            <h4 class="q-mb-xs">{{ t('Notes') }}</h4>
            <VnRow
                :key="index"
                class="row q-gutter-md q-mb-md"
                v-for="(note, index) in notes"
            >
                <div class="col">
                    <VnSelectFilter
                        :label="t('Observation type')"
                        :options="observationTypes"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="note.observationTypeFk"
                    />
                </div>
                <div class="col">
                    <VnInput :label="t('Description')" v-model="note.description" />
                </div>
                <div class="flex items-center">
                    <QIcon
                        @click.stop="deleteNote(index)"
                        class="cursor-pointer"
                        color="primary"
                        name="delete"
                        size="sm"
                    >
                        <QTooltip>
                            {{ t('Remove') }}
                        </QTooltip>
                    </QIcon>
                </div>
            </VnRow>

            <QIcon
                @click.stop="addNote()"
                class="cursor-pointer add-icon q-mt-md"
                name="add"
                size="sm"
            >
                <QTooltip>
                    {{ t('Add note') }}
                </QTooltip>
            </QIcon>
        </template>
    </FormModel>
</template>

<style lang="scss" scoped>
.add-icon {
    background-color: $primary;
    border-radius: 50px;
}
</style>

<i18n>
es:
    Enabled: Activo
    Is equalizated: Recargo de equivalencia
    Is Loginflora allowed: Compra directa en Holanda
    Consignee: Consignatario
    Street address: Dirección postal
    Postcode: Código postal
    City: Población
    Province: Provincia
    Agency: Agencia
    Phone: Teléfono
    Mobile: Movíl
    Incoterms: Incoterms
    Customs agent: Agente de aduanas
    Notes: Notas
    Observation type: Tipo de observación
    Description: Descripción
    Add note: Añadir nota
    Remove note: Eliminar nota
</i18n>
