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

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

const travelFilterRef = ref();
onMounted(async () => {
    stateStore.rightDrawer = true;
});

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(() => [
    {
        align: 'left',
        name: 'id',
        label: t('travel.travelList.tableVisibleColumns.id'),
        isId: true,
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'ref',
        label: t('travel.travelList.tableVisibleColumns.ref'),
        component: 'input',
        columnField: {
            component: null,
        },
        cardVisible: true,
        create: true,
    },
    {
        align: 'left',
        name: 'agencyModeFk',
        label: t('travel.travelList.tableVisibleColumns.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('travel.travelList.tableVisibleColumns.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',
        name: 'shipped',
        label: t('travel.travelList.tableVisibleColumns.shipped'),
        component: 'date',
        columnField: {
            component: null,
        },
        cardVisible: true,
        create: true,
        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('travel.travelList.tableVisibleColumns.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('travel.travelList.tableVisibleColumns.landed'),
        component: 'date',
        columnField: {
            component: null,
        },
        cardVisible: true,
        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>
    <VnSearchbar
        :info="t('You can search by travel id or name')"
        :label="t('Search travel')"
        data-key="TravelList"
    />
    <RightMenu>
        <template #right-panel>
            <TravelFilter data-key="TravelList" ref="travelFilterRef" />
        </template>
    </RightMenu>
    <VnTable
        ref="tableRef"
        data-key="TravelList"
        url="Travels/filter"
        :create="{
            urlCreate: 'Travels',
            title: t('Create Travels'),
            onDataSaved: ({ id }) => tableRef.redirect(id),
            formInitialData: {
                editorFk: entityId,
            },
        }"
        :right-search="false"
        :user-params="{ daysOnward: 7 }"
        order="landed DESC"
        :columns="columns"
        auto-load
        redirect="travel"
        :is-editable="false"
        :use-model="true"
    >
        <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>

<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>
