<script setup>
import { onMounted, ref, computed, reactive, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import VnImg from 'src/components/ui/VnImg.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import { useStateStore } from 'stores/useStateStore';
import { toDate } from 'src/filters';
import axios from 'axios';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import ItemSummary from '../Item/Card/ItemSummary.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
const entityId = computed(() => route.params.id);

const { viewSummary } = useSummaryDialog();
const router = useRouter();
const stateStore = useStateStore();
const { t } = useI18n();
const tableRef = ref();
const route = useRoute();

const itemFilter = {
    include: [
        {
            relation: 'itemType',
            scope: {
                fields: ['id', 'name'],
            },
        },
        {
            relation: 'intrastat',
            scope: {
                fields: ['id', 'description'],
            },
        },
        {
            relation: 'origin',
            scope: {
                fields: ['id', 'name'],
            },
        },
    ],
};
const columns = computed(() => [
    {
        label: '',
        name: 'image',
        align: 'left',
        columnField: {
            component: VnImg,
            attrs: (id) => {
                return {
                    id,
                    width: '50px',
                };
            },
        },
        columnFilter: false,
    },
    {
        label: t('item.list.id'),
        name: 'id',
        field: 'id',
        align: 'left',
        isId: true,
        chip: {
            condition: () => true,
        },
    },
    {
        label: t('item.list.grouping'),
        field: 'grouping',
        name: 'grouping',
        align: 'left',
    },
    {
        label: t('item.list.packing'),
        field: 'packing',
        name: 'packing',
        align: 'left',
    },
    {
        label: t('globals.description'),
        field: 'name',
        name: 'description',
        align: 'left',
        create: true,
    },
    {
        label: t('item.list.stems'),
        field: 'stems',
        name: 'stems',
        align: 'left',
    },
    {
        label: t('item.list.size'),
        field: 'size',
        name: 'size',
        align: 'left',
    },
    {
        label: t('item.list.typeName'),
        field: 'typeName',
        name: 'typeName',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'ItemTypes',
            fields: ['id', 'name'],
        },
        columnField: {
            component: null,
        },
        create: true,
    },
    {
        label: t('item.list.category'),
        field: 'category',
        name: 'category',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'ItemCategories',
            fields: ['id', 'name'],
        },
        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.intrastat'),
        field: 'intrastat',
        name: 'intrastat',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Intrastats',
            fields: ['id', 'description'],
        },
        columnField: {
            component: null,
        },
        create: true,
    },
    {
        label: t('item.list.origin'),
        field: 'origin',
        name: 'origin',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Origins',
            fields: ['id', 'name'],
        },
        columnField: {
            component: null,
        },
        create: true,
    },
    {
        label: t('item.list.userName'),
        field: 'userName',
        name: 'userName',
        align: 'left',
    },
    {
        label: t('item.list.weightByPiece'),
        field: 'weightByPiece',
        name: 'weightByPiece',
        align: 'left',
        component: 'input',
        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.stemMultiplier'),
        field: 'stemMultiplier',
        name: 'stemMultiplier',
        align: 'left',
        component: 'input',
        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.isActive'),
        field: 'isActive',
        name: 'isActive',
        align: 'left',
        component: 'checkbox',
    },
    {
        label: t('item.list.producer'),
        field: 'producer',
        name: 'producer',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Producers',
            fields: ['id', 'name'],
        },
        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.landed'),
        field: 'landed',
        name: 'landed',
        align: 'left',
        component: 'date',
        columnField: {
            component: null,
        },
        format: (row, dashIfEmpty) => dashIfEmpty(toDate(row.landed)),
    },
    {
        align: 'right',
        label: '',
        name: 'tableActions',
        actions: [
            {
                title: t('Clone item'),
                icon: 'vn:clone',
                action: cloneItem,
            },
            {
                title: t('view Summary'),
                icon: 'preview',
                action: (row) => viewSummary(row.id, ItemSummary),
            },
        ],
    },
]);

const cloneItem = async (itemFk) => {
    try {
        const { data } = await axios.post(`Items/${itemFk.id}/clone`);
        if (!data) return;
        router.push({ name: 'ItemTags', params: { id: data.id } });
    } catch (err) {
        console.error('Error cloning item', err);
    }
};

onUnmounted(() => (stateStore.rightDrawer = false));
</script>

<template>
    <VnSearchbar
        data-key="ItemList"
        :label="t('Search Item')"
        :info="t('You can search by id')"
    />
    <VnTable
        ref="tableRef"
        data-key="ItemList"
        url="Items/filter"
        url-create="Items"
        save-url="Items/crud"
        :filter="itemFilter"
        :create="{
            urlCreate: 'Items',
            title: 'Create Item',
            onDataSaved: () => tableRef.redirect(),
            formInitialData: {
                editorFk: entityId,
            },
        }"
        order="id ASC"
        :columns="columns"
        auto-load
        redirect="Item"
        :right-search="true"
        :is-editable="false"
        :use-model="true"
    >
        <template #column-userName="{ row }">
            <span class="link" @click.stop>
                {{ row.userName }}
                <WorkerDescriptorProxy :id="row.buyerFk" />
            </span>
        </template>
    </VnTable>
</template>

<i18n>
es:
    New item: Nuevo artículo
    All it's properties will be copied: Todas sus propiedades serán copiadas
    Do you want to clone this item?: ¿Desea clonar este artículo?
    Preview: Vista previa
</i18n>
