<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 { useState } from 'src/composables/useState';
import useCardDescription from 'src/composables/useCardDescription';
import { useSession } from 'src/composables/useSession';
import { getUrl } from 'src/composables/getUrl';
import axios from 'axios';

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,
    },
});

const quasar = useQuasar();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const { getTokenMultimedia } = useSession();
const state = useState();
const user = state.getUser();

const entityId = computed(() => {
    return $props.id || route.params.id;
});
const image = ref(null);
const regularizeStockFormDialog = ref(null);
const item = ref(null);
const available = ref(null);
const visible = ref(null);
const _warehouseFk = ref(null);
const salixUrl = ref();
const warehouseFk = computed({
    get() {
        return _warehouseFk.value;
    },
    set(val) {
        _warehouseFk.value = val;
        if (val) updateStock();
    },
});

onMounted(async () => {
    await getItemAvatar();
    warehouseFk.value = user.value.warehouseFk;
    salixUrl.value = await getUrl('');
});

const getItemAvatar = async () => {
    const token = getTokenMultimedia();
    const timeStamp = `timestamp=${Date.now()}`;
    image.value = `/api/Images/catalog/200x200/${entityId.value}/download?access_token=${token}&${timeStamp}`;
};

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

const updateStock = async () => {
    try {
        available.value = null;
        visible.value = null;

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

        const { data } = await axios.get(`Items/${entityId.value}/getVisibleAvailable`, {
            params,
        });

        available.value = data.available;
        visible.value = data.visible;
    } catch (err) {
        console.error('Error updating stock');
    }
};

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 it's 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="
            (data) => {
                item = data;
                setData(data);
            }
        "
    >
        <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="visible"
                :available="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
                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 #actions="{}">
            <QCardActions class="row justify-center">
                <QBtn
                    :href="
                        salixUrl +
                        'item/' +
                        entityId +
                        '/diary?' +
                        'warehouseFk=' +
                        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 it's properties will be copied: Todas sus propiedades serán copiadas
    Do you want to clone this item?: ¿Desea clonar este artículo?
</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>
