<script setup>
import { onBeforeMount, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import VnRow from 'components/ui/VnRow.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnLocation from 'src/components/common/VnLocation.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelectDialog from 'src/components/common/VnSelectDialog.vue';
import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import CreateBankEntityForm from 'src/components/CreateBankEntityForm.vue';
import VnRadio from 'src/components/common/VnRadio.vue';
import { useState } from 'src/composables/useState';

const { t } = useI18n();
const user = useState().getUser();

const companiesOptions = ref([]);
const payMethodsOptions = ref([]);
const bankEntitiesOptions = ref([]);
const formData = ref({ companyFk: user.value.companyFk, isFreelance: false });
const defaultPayMethod = ref();

onBeforeMount(async () => {
    defaultPayMethod.value = (
        await axios.get('WorkerConfigs/findOne', {
            params: { field: ['payMethodFk'] },
        })
    ).data.payMethodFk;
    formData.value.payMethodFk = defaultPayMethod.value;
});

function handleLocation(data, location) {
    const { town, code, provinceFk, countryFk } = location ?? {};
    data.postcode = code;
    data.city = town;
    data.provinceFk = provinceFk;
    data.countryFk = countryFk;
}

function generateCodeUser(worker) {
    if (!worker.firstName || !worker.lastNames) return;

    const totalName = worker.firstName.concat(' ' + worker.lastNames).toLowerCase();
    const totalNameArray = totalName.split(' ');
    let newCode = '';

    for (let part of totalNameArray) newCode += part.charAt(0);

    worker.code = newCode.toUpperCase().slice(0, 3);
    worker.name = totalNameArray[0] + newCode.slice(1);

    if (!worker.companyFk) worker.companyFk = user.companyFk;
}

async function autofillBic(worker) {
    if (!worker || !worker.iban) return;

    let bankEntityId = parseInt(worker.iban.substr(4, 4));
    let filter = { where: { id: bankEntityId } };

    const { data } = await axios.get(`BankEntities`, { params: { filter } });
    const hasData = data && data[0];
    if (hasData) worker.bankEntityFk = data[0].id;
    else if (!hasData) worker.bankEntityFk = undefined;
}
</script>
<template>
    <FetchData
        url="Companies"
        @on-fetch="(data) => (companiesOptions = data)"
        auto-load
    />
    <FetchData
        url="Paymethods"
        @on-fetch="(data) => (payMethodsOptions = data)"
        auto-load
    />
    <FetchData
        url="BankEntities"
        @on-fetch="(data) => (bankEntitiesOptions = data)"
        auto-load
    />
    <QPage>
        <VnSubToolbar>
            <template #st-data>
                <VnRadio
                    v-model="formData.isFreelance"
                    :val="false"
                    :label="`${t('Internal')}`"
                    @update:model-value="formData.payMethodFk = defaultPayMethod"
                />
                <VnRadio
                    v-model="formData.isFreelance"
                    :val="true"
                    :label="`${t('External')}`"
                    @update:model-value="delete formData.payMethodFk"
                />
            </template>
        </VnSubToolbar>
        <FormModel
            url-create="Workers/new"
            model="worker"
            :form-initial-data="formData"
            @on-data-saved="(__, { id }) => $router.push({ path: `/worker/${id}` })"
        >
            <template #form="{ data, validate }">
                <VnRow>
                    <VnInput
                        v-model="data.firstName"
                        :label="t('worker.create.name')"
                        :rules="validate('Worker.firstName')"
                        @update:model-value="generateCodeUser(data)"
                    />
                    <VnInput
                        v-model="data.lastNames"
                        :label="t('worker.create.lastName')"
                        :rules="validate('Worker.lastNames')"
                        @update:model-value="generateCodeUser(data)"
                    />
                    <VnInput
                        v-model="data.code"
                        :label="t('worker.create.code')"
                        :rules="validate('Worker.code')"
                    />
                </VnRow>
                <VnRow>
                    <VnInput
                        v-model="data.name"
                        :label="t('worker.create.webUser')"
                        :rules="validate('Worker.name')"
                    />
                    <VnInput
                        v-model="data.email"
                        :label="t('worker.create.personalEmail')"
                        :rules="validate('Worker.email')"
                    />
                </VnRow>
                <VnRow>
                    <VnSelect
                        :label="t('worker.create.company')"
                        v-model="data.companyFk"
                        :options="companiesOptions"
                        option-value="id"
                        option-label="code"
                        hide-selected
                        :rules="validate('Worker.company')"
                    />
                    <VnSelect
                        :label="t('worker.create.boss')"
                        v-model="data.bossFk"
                        url="Workers/search"
                        option-value="id"
                        option-label="name"
                        hide-selected
                        :rules="validate('Worker.boss')"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel>{{ scope.opt.name }}</QItemLabel>
                                    <QItemLabel caption
                                        >{{ scope.opt.nickname }},
                                        {{ scope.opt.code }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelect>
                </VnRow>
                <VnRow>
                    <VnInput
                        v-model="data.fi"
                        :label="t('worker.create.fi')"
                        :rules="validate('Worker.fi')"
                    />
                    <VnInputDate
                        v-model="data.birth"
                        :label="t('worker.create.birth')"
                        :rules="validate('Worker.birth')"
                        :disable="formData.isFreelance"
                    />
                    <VnInput
                        v-model="data.phone"
                        :label="t('worker.create.phone')"
                        :rules="validate('Worker.phone')"
                        :disable="formData.isFreelance"
                    />
                </VnRow>
                <VnRow>
                    <VnLocation
                        :rules="validate('Worker.postcode')"
                        :roles-allowed-to-create="['deliveryAssistant']"
                        @update:model-value="(location) => handleLocation(data, location)"
                        :disable="formData.isFreelance"
                    >
                    </VnLocation>
                </VnRow>
                <VnRow>
                    <VnInput
                        :label="t('worker.create.street')"
                        v-model="data.street"
                        :rules="validate('Worker.street')"
                        :disable="formData.isFreelance"
                    />
                </VnRow>
                <VnRow>
                    <VnSelect
                        :label="t('worker.create.payMethods')"
                        v-model="data.payMethodFk"
                        :options="payMethodsOptions"
                        option-value="id"
                        option-label="name"
                        map-options
                        hide-selected
                        :rules="validate('Worker.payMethodFk')"
                        :disable="formData.isFreelance"
                        @update:model-value="(val) => !val && delete formData.payMethodFk"
                    />
                    <VnInput
                        v-model="data.iban"
                        :label="t('worker.create.iban')"
                        :rules="validate('Worker.iban')"
                        :disable="formData.isFreelance"
                        @update:model-value="autofillBic(data)"
                    >
                        <template #append>
                            <QIcon name="info" class="cursor-info">
                                <QTooltip>{{ t('components.iban_tooltip') }}</QTooltip>
                            </QIcon>
                        </template>
                    </VnInput>
                    <VnSelectDialog
                        :label="t('worker.create.bankEntity')"
                        v-model="data.bankEntityFk"
                        :options="bankEntitiesOptions"
                        option-label="name"
                        option-value="id"
                        hide-selected
                        :roles-allowed-to-create="['salesAssistant', 'hr']"
                        :rules="validate('Worker.bankEntity')"
                        :disable="formData.isFreelance"
                        @update:model-value="autofillBic(data)"
                        :filter-options="['bic', 'name']"
                    >
                        <template #form>
                            <CreateBankEntityForm
                                @on-data-saved="(data) => bankEntitiesOptions.push(data)"
                            />
                        </template>
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection v-if="scope.opt">
                                    <QItemLabel
                                        >{{ scope.opt.bic }}
                                        {{ scope.opt.name }}</QItemLabel
                                    >
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelectDialog>
                </VnRow>
            </template>
        </FormModel>
    </QPage>
</template>
