<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 EditPictureForm from 'components/EditPictureForm.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 editPhotoFormDialog = ref(null);
const item = ref(null);
const available = ref(null);
const visible = ref(null);
const _warehouseFk = ref(null);
const warehouseText = ref(null);
const salixUrl = ref();
const warehouseFk = computed({
    get() {
        return _warehouseFk.value;
    },
    set(val) {
        _warehouseFk.value = val;
        if (val) {
            updateStock();
            getWarehouseName(val);
        }
    },
});
const showWarehouseIconTooltip = ref(true);
const showEditPhotoForm = ref(false);

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 getWarehouseName = async (warehouseFk) => {
    try {
        showWarehouseIconTooltip.value = false;

        const filter = {
            where: { id: warehouseFk },
        };

        const { data } = await axios.get('Warehouses/findOne', { filter });

        warehouseText.value = t('item.descriptor.warehouseText', {
            warehouseName: data.name,
        });

        showWarehouseIconTooltip.value = true;
    } catch (err) {
        console.error('Error finding warehouse');
    }
};

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 toggleEditPictureForm = () => {
    showEditPhotoForm.value = !showEditPhotoForm.value;
};

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('Clone') }}
                </QItemSection>
            </QItem>
        </template>
        <template #before>
            <div class="relative-position">
                <QImg :src="image" spinner-color="primary" class="photo">
                    <template #error>
                        <div
                            class="absolute-full picture text-center q-pa-md flex flex-center"
                        >
                            <div>
                                <div
                                    class="text-grey-5"
                                    style="opacity: 0.4; font-size: 5vh"
                                >
                                    <QIcon name="vn:item" />
                                </div>
                                <div class="text-grey-5" style="opacity: 0.4">
                                    {{ t('item.descriptor.item') }}
                                </div>
                            </div>
                        </div>
                    </template>
                </QImg>
                <QBtn
                    color="primary"
                    size="lg"
                    round
                    class="edit-photo-btn"
                    @click="toggleEditPictureForm()"
                >
                    <QIcon name="edit" size="sm" />
                    <QDialog ref="editPhotoFormDialog" v-model="showEditPhotoForm">
                        <EditPictureForm
                            collection="catalog"
                            :id="entityId"
                            @close-form="toggleEditPictureForm()"
                            @on-photo-uploaded="getItemAvatar()"
                        />
                    </QDialog>
                </QBtn>
            </div>

            <div
                class="row justify-between items-center full-width bg-primary"
                style="height: 54px"
            >
                <div class="col column items-center">
                    <span class="text-uppercase color-vn-white" style="font-size: 11px">
                        {{ t('item.descriptor.visible') }}
                    </span>
                    <span class="text-weight-bold text-h5 color-vn-white">{{
                        visible
                    }}</span>
                </div>
                <div
                    class="col column items-center separation-borders"
                    style="font-size: 11px"
                >
                    <span class="text-uppercase color-vn-white">
                        {{ t('item.descriptor.available') }}
                    </span>
                    <span class="text-weight-bold text-h5 color-vn-white">{{
                        available
                    }}</span>
                </div>
                <div class="col column items-center justify-center">
                    <QIcon name="info" class="cursor-pointer color-vn-white" size="md">
                        <QTooltip>{{ warehouseText }}</QTooltip>
                    </QIcon>
                </div>
            </div>
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('item.descriptor.buyer')">
                <template #value>
                    <span class="link">
                        {{ t('item.descriptor.buyer') }}
                        <WorkerDescriptorProxy :id="entity.itemType?.worker?.id" />
                    </span>
                </template>
            </VnLv>
            <VnLv :label="t('item.descriptor.color')" :value="entity.value5"> </VnLv>
            <VnLv :label="t('item.descriptor.color')" :value="entity.value6" />
            <VnLv :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
    Clone: Clonar
    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>
