<script setup>
import { computed, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';

import CardDescriptor from 'src/components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import RegularizeStockForm from 'components/RegularizeStockForm.vue';
import ItemDescriptorImage from 'src/pages/Item/Card/ItemDescriptorImage.vue';
import useCardDescription from 'src/composables/useCardDescription';
import axios from 'axios';
import { getUrl } from 'src/composables/getUrl';
import { dashIfEmpty } from 'src/filters';
import { useArrayData } from 'src/composables/useArrayData';

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
    summary: {
        type: Object,
        default: null,
    },
    dated: {
        type: String,
        default: null,
    },
    saleFk: {
        type: Number,
        default: null,
    },
    warehouseFk: {
        type: Number,
        default: null,
    },
});

const quasar = useQuasar();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const warehouseConfig = ref(null);
const entityId = computed(() => {
    return $props.id || route.params.id;
});

const regularizeStockFormDialog = ref(null);
const salixUrl = ref();
const mounted = ref();

const arrayDataStock = useArrayData('descriptorStock', {
    url: `Items/${entityId.value}/getVisibleAvailable`,
});

onMounted(async () => {
    salixUrl.value = await getUrl('getVisibleAvailable');
    await getItemConfigs();
    mounted.value = true;
});

const data = ref(useCardDescription());
const setData = async (entity) => {
    if (!entity) return;
    data.value = useCardDescription(entity.name, entity.id);
    await updateStock();
};

const getItemConfigs = async () => {
    const { data } = await axios.get('ItemConfigs/findOne');
    if (!data) return;
    return (warehouseConfig.value = data.warehouseFk);
};
const updateStock = async () => {
    if (!mounted.value) return;
    await getItemConfigs();

    const params = {
        warehouseFk: $props.warehouseFk ?? warehouseConfig.value,
        dated: $props.dated,
    };

    if (!params.warehouseFk) return;

    const stock = useArrayData('descriptorStock', {
        url: `Items/${entityId.value}/getVisibleAvailable`,
        userParams: params,
    });
    const storeData = stock.store.data;
    if (storeData?.itemFk == entityId.value) return;
    await stock.fetch({});
};

const openRegularizeStockForm = () => {
    regularizeStockFormDialog.value.show();
};

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>
    <CardDescriptor
        data-key="ItemData"
        module="Item"
        :title="data.title"
        :subtitle="data.subtitle"
        :summary="$props.summary"
        :url="`Items/${entityId}/getCard`"
        @on-fetch="setData"
    >
        <template #menu="{}">
            <QItem v-ripple clickable @click="openRegularizeStockForm()">
                <QItemSection>
                    {{ t('Regularize stock') }}
                    <QDialog ref="regularizeStockFormDialog">
                        <RegularizeStockForm
                            :item-fk="entityId"
                            :warehouse-fk="warehouseFk"
                            @on-data-saved="updateStock()"
                        />
                    </QDialog>
                </QItemSection>
            </QItem>
            <QItem v-ripple clickable @click="openCloneDialog()">
                <QItemSection>
                    {{ t('globals.clone') }}
                </QItemSection>
            </QItem>
        </template>
        <template #before>
            <ItemDescriptorImage
                :entity-id="entityId"
                :visible="arrayDataStock.store.data?.visible"
                :available="arrayDataStock.store.data?.available"
            />
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('item.descriptor.buyer')">
                <template #value>
                    <span class="link">
                        {{ entity.itemType?.worker?.user?.name }}
                        <WorkerDescriptorProxy :id="entity.itemType?.worker?.id" />
                    </span>
                </template>
            </VnLv>
            <VnLv
                :label="t('item.descriptor.producer')"
                :value="dashIfEmpty(entity.subName)"
            />
            <VnLv
                v-if="entity.value5"
                :label="t('item.descriptor.color')"
                :value="entity.value5"
            >
            </VnLv>
            <VnLv
                v-if="entity.value6"
                :label="t('item.descriptor.category')"
                :value="entity.value6"
            />
            <VnLv
                v-if="entity.value7"
                :label="t('item.descriptor.stems')"
                :value="entity.value7"
            />
        </template>
        <template #icons="{ entity }">
            <QCardActions v-if="entity" class="q-gutter-x-md">
                <QIcon
                    v-if="!entity.isActive"
                    name="vn:unavailable"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>{{ t('Inactive article') }}</QTooltip>
                </QIcon>
            </QCardActions>
        </template>
        <template #actions="{}">
            <QCardActions class="row justify-center">
                <QBtn
                    :to="{
                        name: 'ItemDiary',
                        params: { id: entityId },
                        query: { warehouseFk, lineFk: $props.saleFk },
                    }"
                    size="md"
                    icon="vn:transaction"
                    color="primary"
                >
                    <QTooltip>{{ t('item.descriptor.itemDiary') }}</QTooltip>
                </QBtn>
            </QCardActions>
        </template>
    </CardDescriptor>
</template>

<i18n>
es:
    Regularize stock: Regularizar stock
    All its properties will be copied: Todas sus propiedades serán copiadas
    Do you want to clone this item?: ¿Desea clonar este artículo?
    Inactive article: Artículo inactivo
</i18n>

<style lang="scss" scoped>
.photo {
    height: 256px;
}

.edit-photo-btn {
    position: absolute;
    right: 12px;
    bottom: 12px;
    z-index: 1;
    cursor: pointer;
}

.separation-borders {
    border-left: 1px solid $white;
    border-right: 1px solid $white;
}
</style>
