<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import VnTable from 'components/VnTable/VnTable.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import TravelSummary from './Card/TravelSummary.vue';
import { toDate } from 'src/filters';
import { getDateQBadgeColor } from 'src/composables/getDateQBadgeColor.js';
import TravelFilter from './TravelFilter.vue';
import VnInputNumber from 'src/components/common/VnInputNumber.vue';
import VnSection from 'src/components/common/VnSection.vue';

const { viewSummary } = useSummaryDialog();
const router = useRouter();
const { t } = useI18n();
const route = useRoute();
const tableRef = ref();
const dataKey = 'TravelList';
const $props = defineProps({
    id: {
        type: Number,
        default: 0,
    },
});
const entityId = computed(() => $props.id || route.params.id);

const cloneTravel = (travelData) => {
    const stringifiedTravelData = JSON.stringify(travelData);
    redirectToCreateView(stringifiedTravelData);
};

const redirectToCreateView = (queryParams) => {
    router.push({ name: 'TravelCreate', query: { travelData: queryParams } });
};

const redirectCreateEntryView = (travelData) => {
    router.push({ name: 'EntryCreate', query: { travelFk: travelData.id } });
};

const columns = computed(() => [
    {
        name: 'status',
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'id',
        label: 'Id',
        chip: {
            condition: () => true,
        },
        isId: true,
    },
    {
        align: 'left',
        name: 'ref',
        label: t('travel.travelList.tableVisibleColumns.ref'),
        component: 'input',
        columnField: {
            component: null,
        },
        isTitle: true,
        create: true,
    },
    {
        align: 'left',
        name: 'agencyModeFk',
        label: t('globals.agency'),
        component: 'select',
        attrs: {
            url: 'agencyModes',
            fields: ['id', 'name'],
        },
        format: (row) => row.agencyModeName,
        columnField: {
            component: null,
        },
        cardVisible: true,
        create: true,
    },
    {
        align: 'left',
        name: 'warehouseInFk',
        label: t('globals.warehouseIn'),
        component: 'select',
        attrs: {
            url: 'warehouses',
            fields: ['id', 'name'],
            optionLabel: 'name',
            optionValue: 'id',
        },
        format: (row) => row.warehouseInName,
        columnField: {
            component: null,
        },
        cardVisible: true,
        create: true,
    },
    {
        align: 'left',
        label: t('globals.shipped'),
        name: 'shipped',
        create: true,
        cardVisible: true,
        component: 'date',
        columnField: {
            component: null,
        },
        format: (row, dashIfEmpty) => dashIfEmpty(toDate(row.shipped)),
    },
    {
        align: 'left',
        name: 'shipmentHour',
        label: t('travel.travelList.tableVisibleColumns.shipHour'),
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'warehouseOutFk',
        label: t('globals.warehouseOut'),
        component: 'select',
        attrs: {
            url: 'warehouses',
            fields: ['id', 'name'],
        },
        format: (row) => row.warehouseOutName,
        columnField: {
            component: null,
        },
        cardVisible: true,
        create: true,
    },
    {
        align: 'left',
        name: 'landed',
        label: t('globals.landed'),
        component: 'date',
        columnField: {
            component: null,
        },
        create: true,
        format: (row, dashIfEmpty) => dashIfEmpty(toDate(row.landed)),
    },
    {
        align: 'left',
        name: 'landingHour',
        label: t('travel.travelList.tableVisibleColumns.landHour'),
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'totalEntries',
        label: t('travel.travelList.tableVisibleColumns.totalEntries'),
        component: 'input',
        toolTip: t('travel.travelList.tableVisibleColumns.totalEntriesTooltip'),
        columnField: {
            component: null,
        },
        cardVisible: true,
        create: true,
    },
    {
        align: 'right',
        label: '',
        name: 'tableActions',
        actions: [
            {
                title: t('Clone'),
                icon: 'vn:clone',
                action: cloneTravel,
                isPrimary: true,
            },
            {
                title: t('Add entry'),
                icon: 'vn:ticket',
                action: redirectCreateEntryView,
                isPrimary: true,
            },
            {
                title: t('components.smartCard.viewSummary'),
                icon: 'preview',
                action: (row) => viewSummary(row.id, TravelSummary),
                isPrimary: true,
            },
        ],
    },
]);
</script>

<template>
    <VnSection
        :data-key="dataKey"
        :columns="columns"
        prefix="travel"
        :array-data-props="{
            url: 'Travels/filter',
            order: ['landed DESC'],
        }"
    >
        <template #rightMenu>
            <TravelFilter data-key="TravelList" />
        </template>
        <template #body>
            <VnTable
                ref="tableRef"
                :data-key="dataKey"
                :create="{
                    urlCreate: 'Travels',
                    title: t('Create Travels'),
                    onDataSaved: ({ id }) => tableRef.redirect(id),
                    formInitialData: {
                        editorFk: entityId,
                    },
                }"
                :right-search="false"
                :user-params="{ daysOnward: 7 }"

                redirect="travel"
                :columns="columns"
                :is-editable="false"
            >
                <template #column-status="{ row }">
                    <div class="row">
                        <QIcon v-if="!!row.isRaid" name="vn:net" color="primary">
                            <QTooltip>
                                {{
                                    t('globals.raid', {
                                        daysInForward: row.daysInForward,
                                    })
                                }}</QTooltip
                            >
                        </QIcon>
                    </div>
                </template>
                <template #column-shipped="{ row }">
                    <QBadge
                        text-color="black"
                        v-if="getDateQBadgeColor(row.shipped)"
                        :color="getDateQBadgeColor(row.shipped)"
                    >
                        {{ toDate(row.shipped) }}
                    </QBadge>
                    <span v-else>{{ toDate(row.shipped) }}</span>
                    <QIcon
                        name="flight_takeoff"
                        size="sm"
                        :class="{ 'is-active': row.isDelivered }"
                    />
                </template>
                <template #column-landed="{ row }">
                    <QBadge
                        text-color="black"
                        v-if="getDateQBadgeColor(row.landed)"
                        :color="getDateQBadgeColor(row.landed)"
                    >
                        {{ toDate(row.landed) }}
                    </QBadge>
                    <span v-else>{{ toDate(row.landed) }}</span>
                    <QIcon
                        name="flight_land"
                        size="sm"
                        :class="{ 'is-active': row.isReceived }"
                    />
                </template>
                <template #moreFilterPanel="{ params }">
                    <VnInputNumber
                        :label="t('params.scopeDays')"
                        v-model.number="params.scopeDays"
                        @keyup.enter="(evt) => handleScopeDays(evt.target.value)"
                        @remove="handleScopeDays()"
                        class="q-px-xs q-pr-lg"
                        filled
                        dense
                    />
                </template>
            </VnTable>
        </template>
    </VnSection>
</template>
<i18n>
en:
    Add entry: Add entry
    searchByIdOrReference: Search by ID or reference

es:
    addEntry: Añadir entrada
    searchByIdOrReference: Buscar por ID o por referencia
    You can search by travel id or name: Buscar por envio por id o nombre
    Search travel: Buscar envio
    Clone: Clonar
    Add entry: Añadir Entrada
</i18n>
<style lang="scss" scoped>
.is-active {
    color: #c8e484;
}
</style>
