<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnInputNumber from 'src/components/common/VnInput.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';
import { useState } from 'src/composables/useState';
import { useArrayData } from 'src/composables/useArrayData';
import axios from 'axios';
import { date } from 'quasar';

const { t } = useI18n();
const state = useState();
const user = state.getUser().fn();
const arrayData = useArrayData('ZoneControl');
const footer = computed(() => arrayData.store.data.footer[0]);
const columns = computed(() => [
    {
        align: 'left',
        label: t('warehouse'),
        name: 'warehouseFk',
        component: 'select',
        attrs: {
            url: 'Warehouses',
            fields: ['id', 'name'],
            optionValue: 'id',
            optionLabel: 'name',
            sortBy: 'name ASC',
        },
        isEditable: false,
        format: ({ warehouseName }, dashIfEmpty) => dashIfEmpty(warehouseName),
    },
    {
        label: t('date'),
        name: 'dated',
        component: 'date',
        visible: false,
        create: true,
    },
    {
        name: 'zoneFk',
        label: t('zone.params.zoneFk'),
        component: 'select',
        columnClass: 'expand',
        isEditable: false,
        attrs: {
            url: 'Zones',
            fields: ['id', 'name'],
            optionValue: 'id',
            optionLabel: 'name',
            sortBy: 'name ASC',
        },
        isId: true,
        format: ({ name }, dashIfEmpty) => dashIfEmpty(name),
    },
    {
        name: 'etd',
        label: t('zone.params.etd'),
        component: 'time',
        columnClass: 'shrink',
        columnFilter: false,
        isEditable: false,
    },
    {
        name: 'volume',
        label: t('zone.params.volume'),
        component: 'number',
        columnClass: 'shrink',
        format: ({ volume }) => Math.round(volume),
        columnFilter: false,
        isEditable: false,
    },
    {
        name: 'packingVolume',
        label: t('packingVolume'),
        component: 'number',
        visible: false,
    },
    {
        name: 'packingProgress',
        label: t('packingProgress'),
        component: 'number',
        format: ({ packingProgress }) => expressAsPercent(packingProgress),
        style: ({ packingProgress }) => progressStyle(packingProgress),
        columnFilter: false,
        isEditable: false,
    },
    {
        name: 'isLate',
        label: t('zone.params.isLate'),
        component: 'checkbox',
        cellEvent: {
            'update:modelValue': async (value, oldValue, row) => {
                const zoneEvent = await axios.get('ZoneEvents', {
                    zoneFk: row.zoneFk,
                    type: 'day',
                    dated: row.landed,
                });
                console.log('zoneEvent: ', zoneEvent);

                /* await axios.delete('ZoneEvents/1', {
                    zoneFk: row.zoneFk,
                    type: 'day',
                    dated: row.landed,
                }); */
            },
        },
    },
    {
        name: 'isFull',
        label: t('zone.params.isFull'),
        component: 'checkbox',
        isEditable: false,
    },
]);
const fetchDataRef = ref();
const productionConfigDialogRef = ref(false);
const tableRef = ref();
const productionConfig = ref();

function openDialog() {
    productionConfigDialogRef.value = true;
}

function expressAsPercent(value) {
    return value ? Math.round(value * 100) + '%' : '-';
}

function progressStyle(value) {
    if (value < 1 && value) return 'color: var(--q-negative)';
    return 'color: var(--q-positive)';
}
</script>
<template>
    <FetchData
        ref="fetchDataRef"
        url="ProductionConfigs"
        :filter="{
            fields: ['isZoneClosedByExpeditionActivated', 'minTicketsToCloseZone'],
        }"
        @on-fetch="(data) => (productionConfig = data[0])"
    />
    <QDialog v-model="productionConfigDialogRef" :class="['vn-row', 'wrap']">
        <FormModelPopup
            url-update="ProductionConfigs/1"
            :title="t('popUpTitle')"
            :form-initial-data="productionConfig"
            @on-data-saved="fetchDataRef.fetch()"
        >
            <template #form-inputs="{ data }">
                <VnRow>
                    <VnInputNumber
                        v-model="data.minTicketsToCloseZone"
                        :label="t('minTicketsInfo')"
                    />
                    <VnCheckbox
                        v-model="data.isZoneClosedByExpeditionActivated"
                        :label="t('isZoneClosedInfo')"
                    />
                </VnRow>
            </template>
        </FormModelPopup>
    </QDialog>
    <div class="table-container">
        <div class="column items-center" style="width: 80%">
            <VnTable
                ref="tableRef"
                data-key="ZoneControl"
                url="Zones/controlFilter"
                search-url="Zones/controlFilter"
                order="volume DESC"
                :disable-option="{ card: true }"
                :is-editable="true"
                @on-fetch="
                    async () => {
                        await fetchDataRef.fetch();
                    }
                "
                :columns="columns"
                :footer="true"
                table-height="80vh"
                :user-params="{ dated: Date.vnNew(), warehouseFk: user.warehouseFk }"
                auto-load
                key-data="zones"
            >
                <template #top-left>
                    <VnRow>
                        <VnLv
                            :label="t('minTicketsToCloseZone')"
                            :value="productionConfig?.minTicketsToCloseZone"
                            :info="t('minTicketsInfo')"
                        />
                        <VnLv
                            :label="t('isZoneClosedByExpeditionActivated')"
                            :value="productionConfig?.isZoneClosedByExpeditionActivated"
                            style="color: var(--vn-label-color)"
                            :info="t('isZoneClosedInfo')"
                        />
                        <QBtn
                            style="max-width: 5%"
                            flat
                            icon="edit"
                            @click="openDialog()"
                            :title="t('editProductionConfig')"
                            color="primary"
                            data-cy="edit-travel"
                        />
                    </VnRow>
                </template>
                <template #column-footer-volume>
                    <span v-text="Math.round(footer.volume)" />
                </template>
                <template #column-footer-packingProgress>
                    <span
                        v-text="expressAsPercent(footer.packingProgress)"
                        :style="progressStyle(footer.packingProgress)"
                    />
                </template>
            </VnTable>
        </div>
    </div>
</template>
<i18n>
    en:
        minTicketsToCloseZone: Min tickets 
        minTicketsInfo: Min tickets to close zone
        isZoneClosedByExpeditionActivated: By expedition
        isZoneClosedInfo: Zone closed by expedition
        popUpTitle: Edit config
        warehouse: Warehouse
        packingVolume: Pac. volume
        packingProgress: Progress
    es:
        minTicketsToCloseZone: Tickets minimos
        minTicketsInfo: Tickets minimos para cerrar zona
        isZoneClosedByExpeditionActivated: Por expedición
        isZoneClosedInfo: Zona cerrada por expedición
        popUpTitle: Editar configuración
        volume: Volumen
        packingVolume: Vol. Encajado
        packingProgress: Progreso
</i18n>
<style lang="scss" scoped>
.table-container {
    display: flex;
    justify-content: center;
}
</style>
