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

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 VnSelect from 'src/components/common/VnSelect.vue';
import VnSelectWorker from 'src/components/common/VnSelectWorker.vue';
import { getDifferences, getUpdatedValues } from 'src/filters';

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

const businessTypes = ref([]);
const contactChannels = ref([]);
const handleSalesModelValue = (val) => {
    if (!val) val = '';
    return {
        or: [
            { id: val },
            { name: val },
            { nickname: { like: '%' + val + '%' } },
            { code: { like: `${val}%` } },
        ],
    };
};

const exprBuilder = (param, value) => {
    return {
        and: [{ active: { neq: false } }, handleSalesModelValue(value)],
    };
};

function onBeforeSave(formData, originalData) {
    return getUpdatedValues(
        Object.keys(getDifferences(formData, originalData)),
        formData
    );
}
</script>
<template>
    <FetchData
        url="ContactChannels"
        @on-fetch="(data) => (contactChannels = data)"
        auto-load
    />
    <FetchData
        url="BusinessTypes"
        :filter="{ fields: ['code', 'description'], order: 'description ASC ' }"
        @on-fetch="(data) => (businessTypes = data)"
        auto-load
    />
    <FormModel
        :url="`Clients/${route.params.id}`"
        auto-load
        model="customer"
        :mapper="onBeforeSave"
    >
        <template #form="{ data, validate }">
            <VnRow>
                <VnInput
                    :label="t('globals.name')"
                    :rules="validate('client.name')"
                    autofocus
                    clearable
                    v-model="data.name"
                />
                <VnSelect
                    :input-debounce="0"
                    :label="t('customer.summary.businessType')"
                    :options="businessTypes"
                    :rules="validate('client.businessTypeFk')"
                    emit-value
                    map-options
                    option-label="description"
                    option-value="code"
                    v-model="data.businessTypeFk"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    :label="t('customer.summary.contact')"
                    :rules="validate('client.contact')"
                    clearable
                    v-model="data.contact"
                />
                <VnInput
                    :label="t('globals.params.email')"
                    :rules="validate('client.email')"
                    clearable
                    type="email"
                    v-model="data.email"
                >
                    <template #append>
                        <QIcon name="info" class="cursor-info">
                            <QTooltip>{{
                                t('customer.basicData.youCanSaveMultipleEmails')
                            }}</QTooltip>
                        </QIcon>
                    </template>
                </VnInput>
            </VnRow>
            <VnRow>
                <VnInput
                    :label="t('customer.extendedList.tableVisibleColumns.phone')"
                    :rules="validate('client.phone')"
                    clearable
                    v-model="data.phone"
                    data-cy="customerPhone"
                />
                <VnInput
                    :label="t('customer.summary.mobile')"
                    :rules="validate('client.mobile')"
                    clearable
                    v-model="data.mobile"
                />
            </VnRow>
            <VnRow>
                <VnSelectWorker
                    :label="t('customer.summary.salesPerson')"
                    v-model="data.salesPersonFk"
                    :params="{
                        departmentCodes: ['VT', 'shopping'],
                    }"
                    :has-avatar="true"
                    :rules="validate('client.salesPersonFk')"
                    :expr-builder="exprBuilder"
                    emit-value
                />
                <VnSelect
                    v-model="data.contactChannelFk"
                    :options="contactChannels"
                    option-value="id"
                    option-label="name"
                    emit-value
                    :label="t('customer.summary.contactChannel')"
                    map-options
                    :rules="validate('client.contactChannelFk')"
                    :input-debounce="0"
                />
            </VnRow>
            <VnRow>
                <VnSelect
                    url="Clients"
                    :input-debounce="0"
                    :label="t('customer.basicData.previousClient')"
                    :rules="validate('client.transferorFk')"
                    emit-value
                    map-options
                    option-label="name"
                    option-value="id"
                    sort-by="name ASC"
                    v-model="data.transferorFk"
                    :fields="['id', 'name']"
                >
                    <template #append>
                        <QIcon name="info" class="cursor-pointer">
                            <QTooltip>{{
                                t(
                                    'In case of a company succession, specify the grantor company'
                                )
                            }}</QTooltip>
                        </QIcon>
                    </template>
                </VnSelect>
            </VnRow>
        </template>
    </FormModel>
</template>

<i18n>
es:
    In case of a company succession, specify the grantor company: En el caso de que haya habido una sucesión de empresa, indicar la empresa cedente
    Comercial name: Nombre comercial
</i18n>
