<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import VnImg from 'src/components/ui/VnImg.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import { toDate } from 'src/filters';
import axios from 'axios';
import FetchedTags from 'src/components/ui/FetchedTags.vue';
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';
import ItemDescriptorProxy from './Card/ItemDescriptorProxy.vue';
import VnConfirm from 'src/components/ui/VnConfirm.vue';
import { useQuasar } from 'quasar';
const entityId = computed(() => route.params.id);

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

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: ({ row }) => {
                return {
                    id: row?.id,
                    zoomResolution: '1600x900',
                    zoom: true,
                    class: 'rounded',
                };
            },
        },
        columnFilter: false,
        cardVisible: true,
    },
    {
        label: t('item.list.id'),
        name: 'id',
        align: 'left',
        isId: true,
        chip: {
            condition: () => true,
        },
        cardVisible: true,
    },
    {
        label: t('item.list.grouping'),
        name: 'grouping',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
    },
    {
        label: t('item.list.packing'),
        name: 'packing',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
    },
    {
        label: t('globals.description'),
        name: 'description',
        align: 'left',
        create: true,
        columnFilter: {
            name: 'search',
        },
        cardVisible: true,
    },
    {
        label: t('item.list.stems'),
        name: 'stems',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
        cardVisible: true,
    },
    {
        label: t('item.list.size'),
        name: 'size',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
        cardVisible: true,
    },
    {
        label: t('item.list.typeName'),
        name: 'typeFk',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'ItemTypes',
            fields: ['id', 'name'],
        },
        columnFilter: {
            name: 'typeFk',
            attrs: {
                url: 'ItemTypes',
                fields: ['id', 'name'],
            },
        },
        columnField: {
            component: null,
        },
        create: true,
    },
    {
        label: t('item.list.category'),
        name: 'category',
        align: 'left',
        component: 'select',
        columnFilter: {
            name: 'categoryFk',
            attrs: {
                url: 'ItemCategories',
                fields: ['id', 'name'],
            },
        },
        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.intrastat'),
        name: 'intrastat',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Intrastats',
            optionValue: 'description',
            optionLabel: 'description',
        },
        columnFilter: {
            name: 'description',
            attrs: {
                url: 'Intrastats',
                optionValue: 'description',
                optionLabel: 'description',
            },
            alias: 'intr',
        },
        columnField: {
            component: null,
        },
        create: true,
        cardVisible: true,
    },
    {
        label: t('item.list.origin'),
        name: 'origin',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Origins',
            optionValue: 'id',
            optionLabel: 'code',
        },
        columnFilter: {
            name: 'id',
            attrs: {
                url: 'Origins',
                optionValue: 'id',
                optionLabel: 'code',
            },
            inWhere: true,
            alias: 'ori',
        },
        columnField: {
            component: null,
        },
        create: true,
        cardVisible: true,
    },
    {
        label: t('item.list.userName'),
        name: 'userName',
        align: 'left',
        columnFilter: {
            name: 'workerFk',
            attrs: {
                url: 'Users',
                optionValue: 'id',
                optionLabel: 'userName',
            },
        },
    },
    {
        label: t('item.list.weightByPiece'),
        name: 'weightByPiece',
        align: 'left',
        component: 'input',
        columnField: {
            component: null,
        },
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('item.list.stemMultiplier'),
        name: 'stemMultiplier',
        align: 'left',
        component: 'input',
        columnField: {
            component: null,
        },
        columnFilter: {
            inWhere: true,
        },
    },
    {
        label: t('item.list.isActive'),
        name: 'isActive',
        align: 'center',
        component: 'checkbox',
    },
    {
        label: t('item.list.producer'),
        name: 'producer',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Producers',
            fields: ['id', 'name'],
        },
        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.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('globals.clone'),

                icon: 'vn:clone',
                action: openCloneDialog,
                isPrimary: true,
            },
            {
                title: t('components.smartCard.viewSummary'),
                icon: 'preview',
                action: (row) => viewSummary(row.id, ItemSummary),
                isPrimary: true,
            },
        ],
    },
]);

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

const openCloneDialog = async () => {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                title: t('All its properties will be copied'),
                message: t('Do you want to clone this item?'),
            },
        })
        .onOk(async () => {
            await cloneItem();
        });
};
</script>

<template>
    <VnSearchbar
        data-key="ItemList"
        :label="t('item.searchbar.label')"
        :info="t('You can search by id')"
    />
    <VnTable
        ref="tableRef"
        data-key="ItemList"
        url="Items/filter"
        url-create="Items"
        :create="{
            urlCreate: 'Items',
            title: t('Create Item'),
            onDataSaved: () => tableRef.redirect(),
            formInitialData: {
                editorFk: entityId,
            },
        }"
        :order="['isActive DESC', 'name', 'id']"
        :columns="columns"
        auto-load
        redirect="Item"
        :is-editable="false"
        :filer="itemFilter"
    >
        <template #column-id="{ row }">
            <span class="link" @click.stop>
                {{ row.id }}
                <ItemDescriptorProxy :id="row.id" />
            </span>
        </template>
        <template #column-userName="{ row }">
            <span class="link" @click.stop>
                {{ row.userName }}
                <WorkerDescriptorProxy :id="row.buyerFk" />
            </span>
        </template>
        <template #column-description="{ row }">
            <div class="row column full-width justify-between items-start">
                {{ row?.name }}
                <div v-if="row?.subName" class="subName">
                    {{ row?.subName.toUpperCase() }}
                </div>
            </div>
            <FetchedTags :item="row" :max-length="6" />
        </template>
    </VnTable>
</template>

<style lang="scss" scoped>
.subName {
    text-transform: uppercase;
    color: var(--vn-label-color);
}
</style>
<i18n>
es:
    New item: Nuevo artículo
    All its 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
    Regularize stock: Regularizar stock
</i18n>
