<script setup>
import { onBeforeMount, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { useUserConfig } from 'src/composables/useUserConfig';
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';

const { t } = useI18n();

const companiesOptions = ref([]);
const workersOptions = ref([]);
const payMethodsOptions = ref([]);
const bankEntitiesOptions = ref([]);
const postcodesOptions = ref([]);
const formData = ref({ isFreelance: false });
const defaultPayMethod = ref(0);

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

onBeforeMount(async () => {
    const userInfo = await useUserConfig().fetch();
    formData.value.companyFk = userInfo.companyFk;

    const { data } = await axios.get('WorkerConfigs/findOne', {
        params: { field: ['payMethodFk'] },
    });
    defaultPayMethod.value = data.payMethodFk;
    formData.value.payMethodFk = defaultPayMethod.value;
});
</script>
<template>
    <FetchData
        url="Companies"
        @on-fetch="(data) => (companiesOptions = data)"
        auto-load
    />
    <FetchData
        url="Workers/search"
        @on-fetch="(data) => (workersOptions = 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')"
                    />
                    <VnInput
                        v-model="data.lastNames"
                        :label="t('worker.create.lastName')"
                        :rules="validate('Worker.lastNames')"
                    />
                    <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"
                        :options="workersOptions"
                        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']"
                        :options="postcodesOptions"
                        v-model="data.location"
                        @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"
                    >
                        <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"
                    >
                        <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>
