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

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import { useVnConfirm } from 'composables/useVnConfirm';
import { useArrayData } from 'src/composables/useArrayData';
import { downloadDocuware } from 'src/composables/downloadFile';

import FetchData from 'components/FetchData.vue';
import FormModelPopup from 'src/components/FormModelPopup.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';

const { t } = useI18n();
const { notify } = useNotify();
const loadingDocuware = ref(true);
const tableRef = ref();
const dialog = ref();
const getAvailablePdaRef = ref();
const route = useRoute();
const { openConfirmationModal } = useVnConfirm();
const routeId = computed(() => route.params.id);
const worker = computed(() => useArrayData('Worker').store.data);
const initialData = computed(() => {
    return {
        userFk: routeId.value,
        deviceProductionFk: null,
        simFk: null,
    };
});

const columns = computed(() => [
    {
        align: 'center',
        label: t('globals.state'),
        name: 'state',
        format: (row) => row?.docuware?.state,
        columnFilter: false,
        chip: {
            condition: (_, row) => !!row.docuware,
            color: (row) => (isSigned(row) ? 'bg-positive' : 'bg-warning'),
        },
        visible: false,
    },
    {
        align: 'right',
        label: t('worker.pda.currentPDA'),
        name: 'deviceProductionFk',
        columnClass: 'shrink',
        cardVisible: true,
    },
    {
        align: 'left',
        label: t('Model'),
        name: 'modelFk',
        format: ({ deviceProduction }) => deviceProduction.modelFk,
        cardVisible: true,
    },
    {
        align: 'right',
        label: t('Serial number'),
        name: 'serialNumber',
        format: ({ deviceProduction }) => deviceProduction.serialNumber,
        cardVisible: true,
    },
    {
        align: 'left',
        label: t('Current SIM'),
        name: 'simFk',
        cardVisible: true,
    },
    {
        align: 'right',
        name: 'actions',
        columnFilter: false,
        cardVisible: true,
    },
]);

function reloadData() {
    initialData.value.deviceProductionFk = null;
    initialData.value.simFk = null;
    tableRef.value.reload();
    getAvailablePdaRef.value.fetch();
}

async function fetchDocuware() {
    loadingDocuware.value = true;

    const id = `${worker.value?.lastName} ${worker.value?.firstName}`;
    const rows = tableRef.value.CrudModelRef.formData;

    const promises = rows.map(async (row) => {
        const { data } = await axios.post(`Docuwares/${id}/checkFile`, {
            fileCabinet: 'hr',
            signed: false,
            mergeFilter: [
                {
                    DBName: 'TIPO_DOCUMENTO',
                    Value: ['PDA'],
                },
                {
                    DBName: 'OBSERVACIONES',
                    Value: [row.deviceProductionFk],
                },
            ],
        });
        row.docuware = data;
    });

    await Promise.allSettled(promises);
    loadingDocuware.value = false;
}

async function sendToTablet(rows) {
    const promises = rows.map(async (row) => {
        await axios.post(`Docuwares/upload-pda-pdf`, {
            ids: [row.deviceProductionFk],
        });
        row.docuware = true;
    });
    await Promise.allSettled(promises);
    notify(t('PDF sended to signed'), 'positive');
    tableRef.value.reload();
}

async function deallocatePDA(deviceProductionFk) {
    await axios.post(`Workers/${route.params.id}/deallocatePDA`, {
        pda: deviceProductionFk,
    });
    const index = tableRef.value.CrudModelRef.formData.findIndex(
        (data) => data?.deviceProductionFk == deviceProductionFk,
    );
    delete tableRef.value.CrudModelRef.formData[index];
    notify(t('PDA deallocated'), 'positive');
    await getAvailablePdaRef.value.fetch();
}

function isSigned(row) {
    return row.docuware?.state === 'Firmado';
}
</script>

<template>
    <FetchData
        ref="getAvailablePdaRef"
        url="workers/getAvailablePda"
        @on-fetch="(data) => (deviceProductions = data)"
        auto-load
    />
    <VnTable
        ref="tableRef"
        data-key="WorkerPda"
        url="DeviceProductionUsers"
        :user-filter="{ order: 'id' }"
        :filter="{ where: { userFk: routeId } }"
        search-url="pda"
        auto-load
        :columns="columns"
        @onFetch="fetchDocuware"
        :hasSubToolbar="true"
        :default-remove="false"
        :default-reset="false"
        :default-save="false"
        :table="{
            'row-key': 'deviceProductionFk',
            selection: 'multiple',
        }"
        :crud-model="{
            insertOnLoad: false,
        }"
        :table-filter="{ hiddenTags: ['userFk'] }"
    >
        <template #moreBeforeActions>
            <QBtn
                :label="t('globals.refresh')"
                icon="refresh"
                @click="tableRef.reload()"
            />
            <QBtn
                :disable="!tableRef?.selected?.length"
                :label="t('globals.send')"
                icon="install_mobile"
                @click="sendToTablet(tableRef?.selected)"
                class="bg-primary"
            />
        </template>
        <template #column-actions="{ row }">
            <QBtn
                flat
                icon="delete"
                color="primary"
                @click="
                    openConfirmationModal(
                        t(`Remove PDA`),
                        t('Do you want to remove this PDA?'),
                        () => deallocatePDA(row.deviceProductionFk),
                    )
                "
                data-cy="workerPda-remove"
            >
                <QTooltip>
                    {{ t('worker.pda.removePDA') }}
                </QTooltip>
            </QBtn>
            <QBtn
                v-if="!isSigned(row)"
                :loading="loadingDocuware"
                icon="install_mobile"
                flat
                color="primary"
                @click="
                    openConfirmationModal(
                        t('Sign PDA'),
                        t('Are you sure you want to send it?'),
                        () => sendToTablet([row]),
                    )
                "
                data-cy="workerPda-send"
            >
                <QTooltip>
                    {{ t('worker.pda.sendToTablet') }}
                </QTooltip>
            </QBtn>
            <QBtn
                v-if="isSigned(row)"
                :loading="loadingDocuware"
                icon="cloud_download"
                flat
                color="primary"
                @click="
                    downloadDocuware('Docuwares/download-pda-pdf', {
                        file: row.deviceProductionFk + '-pda',
                        worker: worker?.lastName + ' ' + worker?.firstName,
                    })
                "
                data-cy="workerPda-download"
            >
                <QTooltip>
                    {{ t('globals.downloadPdf') }}
                </QTooltip>
            </QBtn>
        </template>
    </VnTable>
    <QPageSticky :offset="[18, 18]">
        <QBtn @click.stop="dialog.show()" color="primary" fab icon="add" v-shortcut="'+'">
            <QDialog ref="dialog">
                <FormModelPopup
                    :title="t('Add new device')"
                    url-create="DeviceProductionUsers"
                    model="DeviceProductionUser"
                    :form-initial-data="initialData"
                    @on-data-saved="reloadData()"
                >
                    <template #form-inputs="{ data }">
                        <VnRow>
                            <VnSelect
                                :label="t('PDA')"
                                v-model="data.deviceProductionFk"
                                :options="deviceProductions"
                                option-label="modelFk"
                                option-value="id"
                                id="deviceProductionFk"
                                hide-selected
                                data-cy="pda-dialog-select"
                                :required="true"
                            >
                                <template #option="scope">
                                    <QItem v-bind="scope.itemProps">
                                        <QItemSection>
                                            <QItemLabel
                                                >ID: {{ scope.opt?.id }}</QItemLabel
                                            >
                                            <QItemLabel caption>
                                                {{ scope.opt?.modelFk }},
                                                {{ scope.opt?.serialNumber }}
                                            </QItemLabel>
                                        </QItemSection>
                                    </QItem>
                                </template>
                            </VnSelect>
                            <VnSelect
                                url="Sims"
                                option-label="line"
                                option-value="code"
                                v-model="data.simFk"
                                :label="t('SIM serial number')"
                                id="simSerialNumber"
                            />
                        </VnRow>
                    </template>
                </FormModelPopup>
            </QDialog>
        </QBtn>
        <QTooltip>
            {{ t('globals.new') }}
        </QTooltip>
    </QPageSticky>
</template>
<i18n>
es:
    Model: Modelo
    Serial number: Número de serie
    Current SIM: SIM actual
    Add new device: Añadir nuevo dispositivo
    PDA deallocated: PDA desasignada
    Remove PDA: Eliminar PDA
    Do you want to remove this PDA?: ¿Desea eliminar este PDA?
    You can only have one PDA: Solo puedes tener un PDA si no eres autonomo
    This PDA is already assigned to another user: Este PDA ya está asignado a otro usuario
    Are you sure you want to send it?: ¿Seguro que quieres enviarlo?
    Sign PDA: Firmar PDA
    PDF sended to signed: PDF enviado para firmar
</i18n>
