<script setup>
import { ref, computed, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';
import { 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 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 ItemTypeDescriptorProxy from './ItemType/Card/ItemTypeDescriptorProxy.vue';
import { cloneItem } from 'src/pages/Item/composables/cloneItem';
import RightMenu from 'src/components/common/RightMenu.vue';
import ItemListFilter from './ItemListFilter.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import axios from 'axios';

const entityId = computed(() => route.params.id);
const { openCloneDialog } = cloneItem();
const { viewSummary } = useSummaryDialog();
const { t } = useI18n();
const tableRef = ref();
const route = useRoute();
const validPriorities = ref([]);
const defaultTag = ref();
const defaultPriority = ref();
const itemFilter = {
    include: [
        {
            relation: 'itemType',
            scope: {
                fields: ['id', 'name'],
            },
        },
        {
            relation: 'intrastat',
            scope: {
                fields: ['id', 'description'],
            },
        },
        {
            relation: 'origin',
            scope: {
                fields: ['id', 'name'],
            },
        },
        {
            relation: 'production',
            scope: {
                fields: ['id', 'name'],
            },
        },
    ],
};
const columns = computed(() => [
    {
        label: '',
        name: 'image',
        align: 'left',
        columnFilter: false,
    },
    {
        label: t('item.list.id'),
        name: 'id',
        align: 'left',
        isId: true,
        chip: {
            condition: () => true,
        },
        cardVisible: true,
    },
    {
        label: t('entry.summary.grouping'),
        name: 'grouping',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
    },
    {
        label: t('entry.summary.packing'),
        name: 'packing',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
    },
    {
        label: t('globals.description'),
        name: 'description',
        align: 'left',
        columnFilter: {
            name: 'search',
        },
        columnClass: 'expand',
    },
    {
        label: t('item.list.stems'),
        name: 'stems',
        align: 'left',
        columnFilter: {
            component: 'number',
            inWhere: true,
        },
        cardVisible: true,
    },
    {
        label: t('globals.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'],
            },
        },
        visible: false,
    },
    {
        label: t('item.list.typeName'),
        name: 'typeName',
        align: 'left',
        component: 'select',
        columnFilter: {
            name: 'typeFk',
            attrs: {
                url: 'ItemTypes',
                fields: ['id', 'name'],
            },
        },
        columnField: {
            component: null,
        },
    },
    {
        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('globals.intrastat'),
        name: 'intrastat',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'Intrastats',
            optionValue: 'description',
            optionLabel: 'description',
        },
        columnFilter: {
            name: 'intrastat',
            attrs: {
                url: 'Intrastats',
                optionValue: 'description',
                optionLabel: 'description',
            },
        },
        columnField: {
            component: null,
        },
        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,
        },
        cardVisible: true,
    },
    {
        label: t('item.list.userName'),
        name: 'userName',
        align: 'left',
        component: 'select',
        columnFilter: {
            name: 'workerFk',
            attrs: {
                url: 'TicketRequests/getItemTypeWorker',
                optionValue: 'id',
                optionLabel: 'nickname',
            },
        },

        columnField: {
            component: null,
        },
    },
    {
        label: t('item.list.weight'),
        toolTip: t('item.list.weightByPiece'),
        name: 'weightByPiece',
        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('globals.producer'),
        name: 'producer',
        align: 'left',
        component: 'select',
        columnFilter: {
            name: 'producerFk',
            attrs: {
                url: 'Producers',
                optionValue: 'id',
                optionLabel: 'name',
            },
        },
        columnField: {
            component: null,
        },
    },
    {
        label: t('globals.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,
            },
        ],
    },
]);

onBeforeMount(async () => {
    const { data } = await axios.get('ItemConfigs');
    defaultTag.value = data[0].defaultTag;
    defaultPriority.value = data[0].defaultPriority;
    data.forEach((priority) => {
        validPriorities.value = priority.validPriorities;
    });
});
</script>
<template>
    <VnSearchbar
        data-key="ItemList"
        :label="t('item.searchbar.label')"
        :info="t('item.searchbar.info')"
    />
    <RightMenu>
        <template #right-panel>
            <ItemListFilter data-key="ItemList" />
        </template>
    </RightMenu>
    <VnTable
        v-if="defaultTag"
        ref="tableRef"
        data-key="ItemList"
        url="Items/filter"
        :create="{
            urlCreate: 'Items/new',
            title: t('item.list.newItem'),
            onDataSaved: ({ id }) => tableRef.redirect(`${id}/basic-data`),
            formInitialData: {
                editorFk: entityId,
                tag: defaultTag,
                priority: defaultPriority,
            },
        }"
        :order="['isActive DESC', 'name', 'id']"
        :columns="columns"
        redirect="Item"
        :is-editable="false"
        :right-search="false"
        :filter="itemFilter"
    >
        <template #column-image="{ row }">
            <VnImg
                :id="row?.id"
                zoom-resolution="1600x900"
                :zoom="true"
                class="rounded"
            />
        </template>
        <template #column-id="{ row }">
            <span class="link" @click.stop>
                {{ row.id }}
                <ItemDescriptorProxy :id="row.id" />
            </span>
        </template>
        <template #column-typeName="{ row }">
            <span class="link" @click.stop>
                {{ row.typeName }}
                {{ row.typeFk }}
                <ItemTypeDescriptorProxy :id="row.typeFk" />
            </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" :columns="3" />
        </template>
        <template #more-create-dialog="{ data }">
            <VnInput
                v-model="data.provisionalName"
                :label="t('globals.description')"
                :is-required="true"
            />
            <VnSelect
                url="Tags"
                v-model="data.tag"
                :label="t('globals.tag')"
                :fields="['id', 'name']"
                option-label="name"
                option-value="id"
                :is-required="true"
                :sort-by="['name ASC']"
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>{{ scope.opt?.name }}</QItemLabel>
                            <QItemLabel caption> #{{ scope.opt?.id }} </QItemLabel>
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                :options="validPriorities"
                v-model="data.priority"
                :label="t('item.create.priority')"
                :is-required="true"
            />
            <VnSelect
                url="ItemTypes"
                v-model="data.typeFk"
                :label="t('item.list.typeName')"
                :fields="['id', 'code', 'name']"
                option-label="name"
                option-value="id"
                :is-required="true"
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>{{ scope.opt?.name }}</QItemLabel>
                            <QItemLabel caption>
                                {{ scope.opt?.code }} #{{ scope.opt?.id }}
                            </QItemLabel>
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                url="Intrastats"
                v-model="data.intrastatFk"
                :label="t('globals.intrastat')"
                :fields="['id', 'description']"
                option-label="description"
                option-value="id"
                :is-required="true"
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>{{ scope.opt?.description }}</QItemLabel>
                            <QItemLabel caption> #{{ scope.opt?.id }} </QItemLabel>
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                url="Origins"
                v-model="data.originFk"
                :label="t('globals.origin')"
                :fields="['id', 'code', 'name']"
                option-label="code"
                option-value="id"
                :is-required="true"
            >
                <template #option="scope">
                    <QItem v-bind="scope.itemProps">
                        <QItemSection>
                            <QItemLabel>{{ scope.opt?.name }}</QItemLabel>
                            <QItemLabel caption>
                                {{ scope.opt?.code }} #{{ scope.opt?.id }}
                            </QItemLabel>
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
        </template>
    </VnTable>
</template>
<style lang="scss" scoped>
.subName {
    text-transform: uppercase;
    color: var(--vn-label-color);
    font-size: small;
}
</style>
<i18n>
es:
    New item: Nuevo artículo
    Create Item: Crear artículo
    You can search by id: Puedes buscar por id
    Preview: Vista previa
</i18n>
