<script setup>
import { onMounted, ref, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { toDate, toCurrency } from 'src/filters';
import CardSummary from 'components/ui/CardSummary.vue';
import FetchData from 'components/FetchData.vue';
import { getUrl } from 'src/composables/getUrl';
import { useSession } from 'src/composables/useSession';
import VnLv from 'src/components/ui/VnLv.vue';
import ClaimNotes from 'src/pages/Claim/Card/ClaimNotes.vue';
import VnUserLink from 'src/components/ui/VnUserLink.vue';

const route = useRoute();
const { t } = useI18n();
const session = useSession();
const token = session.getToken();

const $props = defineProps({
    id: {
        type: Number,
        default: 0,
    },
});

const entityId = computed(() => $props.id || route.params.id);

const claimUrl = ref();
const salixUrl = ref();
const claimDmsRef = ref();
const claimDmsFilter = ref({
    include: [
        {
            relation: 'dms',
        },
    ],
    where: { claimFk: entityId.value },
});

onMounted(async () => {
    salixUrl.value = await getUrl('');
    claimUrl.value = salixUrl.value + `claim/${entityId.value}/`;
});

watch(entityId, async (id) => {
    claimDmsFilter.value.where = { claimFk: id };
    await claimDmsRef.value.fetch();
});

const detailsColumns = ref([
    {
        name: 'item',
        label: 'claim.summary.item',
        field: (row) => row.sale.itemFk,
        sortable: true,
    },
    {
        name: 'landed',
        label: 'claim.summary.landed',
        field: (row) => row.sale.ticket.landed,
        format: (value) => toDate(value),
        sortable: true,
    },
    {
        name: 'quantity',
        label: 'claim.summary.quantity',
        field: (row) => row.sale.quantity,
        sortable: true,
    },
    {
        name: 'claimed',
        label: 'claim.summary.claimed',
        field: (row) => row.quantity,
        sortable: true,
    },
    {
        name: 'description',
        label: 'claim.summary.description',
        field: (row) => row.sale.concept,
    },
    {
        name: 'price',
        label: 'claim.summary.price',
        field: (row) => row.sale.price,
        sortable: true,
    },
    {
        name: 'discount',
        label: 'claim.summary.discount',
        field: (row) => row.sale.discount,
        format: (value) => `${value} %`,
        sortable: true,
    },
    {
        name: 'total',
        label: 'claim.summary.total',
        field: ({ sale }) =>
            toCurrency(sale.quantity * sale.price * ((100 - sale.discount) / 100)),
        sortable: true,
    },
]);

const STATE_COLOR = {
    pending: 'positive',

    managed: 'warning',

    resolved: 'negative',
};
function stateColor(code) {
    return STATE_COLOR[code];
}

const developmentColumns = ref([
    {
        name: 'claimReason',
        label: 'claim.summary.reason',
        field: (row) => row.claimReason.description,
        sortable: true,
    },
    {
        name: 'claimResult',
        label: 'claim.summary.result',
        field: (row) => row.claimResult.description,
        sortable: true,
    },
    {
        name: 'claimResponsible',
        label: 'claim.summary.responsible',
        field: (row) => row.claimResponsible.description,
        sortable: true,
    },
    {
        name: 'worker',
        label: 'claim.summary.worker',
        field: (row) => row.worker?.user.nickname,
        sortable: true,
    },
    {
        name: 'claimRedelivery',
        label: 'claim.summary.redelivery',
        field: (row) => row.claimRedelivery.description,
        sortable: true,
    },
]);
const claimDms = ref([]);
const multimediaDialog = ref();
const multimediaSlide = ref();

function setClaimDms(data) {
    claimDms.value = [];
    data.forEach((media) => {
        claimDms.value.push({
            isVideo: media.dms.contentType == 'video/mp4',
            url: `/api/Claims/${media.dmsFk}/downloadFile?access_token=${token}`,
            dmsFk: media.dmsFk,
        });
    });
}

function openDialog(dmsId) {
    multimediaSlide.value = dmsId;
    multimediaDialog.value = true;
}
</script>

<template>
    <FetchData
        url="ClaimDms"
        :filter="claimDmsFilter"
        @on-fetch="(data) => setClaimDms(data)"
        limit="20"
        auto-load
        ref="claimDmsRef"
    />
    <CardSummary ref="summary" :url="`Claims/${entityId}/getSummary`">
        <template #header="{ entity: { claim } }">
            {{ claim.id }} - {{ claim.client.name }}
        </template>
        <template #body="{ entity: { claim, salesClaimed, developments } }">
            <QCard class="vn-one">
                <a class="header" :href="`#/claim/${entityId}/basic-data`">
                    {{ t('claim.pageTitles.basicData') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <VnLv
                    :label="t('claim.summary.created')"
                    :value="toDate(claim.created)"
                />
                <VnLv :label="t('claim.summary.state')">
                    <template #value>
                        <QChip :color="stateColor(claim.claimState.code)" dense>
                            {{ claim.claimState.description }}
                        </QChip>
                    </template>
                </VnLv>
                <VnLv :label="t('claim.summary.assignedTo')">
                    <template #value>
                        <VnUserLink
                            :name="claim.worker?.user?.nickname"
                            :worker-id="claim.workerFk"
                        />
                    </template>
                </VnLv>
                <VnLv :label="t('claim.summary.attendedBy')">
                    <template #value>
                        <VnUserLink
                            :name="claim.client?.salesPersonUser?.name"
                            :worker-id="claim.client?.salesPersonFk"
                        />
                    </template>
                </VnLv>
            </QCard>
            <QCard class="vn-max claimVnNotes">
                <a class="header" :href="`#/claim/${entityId}/notes`">
                    {{ t('claim.summary.notes') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <ClaimNotes :add-note="false" style="height: 350px" order="created ASC" />
            </QCard>
            <QCard class="vn-max" v-if="salesClaimed.length > 0">
                <a class="header" :href="`#/claim/${entityId}/lines`">
                    {{ t('claim.summary.details') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <QTable :columns="detailsColumns" :rows="salesClaimed" flat>
                    <template #header="props">
                        <QTr :props="props">
                            <QTh v-for="col in props.cols" :key="col.name" :props="props">
                                {{ t(col.label) }}
                            </QTh>
                        </QTr>
                    </template>
                </QTable>
            </QCard>
            <QCard class="vn-max" v-if="claimDms.length > 0">
                <a class="header" :href="`#/claim/${entityId}/photos`">
                    {{ t('claim.summary.photos') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <div class="container">
                    <div
                        class="multimedia-container"
                        v-for="(media, index) of claimDms"
                        :key="index"
                    >
                        <div class="relative-position">
                            <QIcon
                                name="play_circle"
                                color="primary"
                                size="xl"
                                class="absolute-center zindex"
                                v-if="media.isVideo"
                                @click.stop="openDialog(media.dmsFk)"
                            >
                                <QTooltip>Video</QTooltip>
                            </QIcon>
                            <QCard class="multimedia relative-position">
                                <QImg
                                    :src="media.url"
                                    class="rounded-borders cursor-pointer fit"
                                    @click="openDialog(media.dmsFk)"
                                    v-if="!media.isVideo"
                                >
                                </QImg>
                                <video
                                    :src="media.url"
                                    class="rounded-borders cursor-pointer fit"
                                    muted="muted"
                                    v-if="media.isVideo"
                                    @click="openDialog(media.dmsFk)"
                                />
                            </QCard>
                        </div>
                    </div>
                </div>
            </QCard>
            <QCard class="vn-two" v-if="developments.length > 0">
                <a class="header" :href="claimUrl + 'development'">
                    {{ t('claim.summary.development') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <QTable :columns="developmentColumns" :rows="developments" flat>
                    <template #header="props">
                        <QTr :props="props">
                            <QTh v-for="col in props.cols" :key="col.name" :props="props">
                                {{ t(col.label) }}
                            </QTh>
                        </QTr>
                    </template>
                </QTable>
            </QCard>
            <QCard class="vn-max" v-if="developments.length > 0">
                <a class="header" :href="claimUrl + 'action'">
                    {{ t('claim.summary.actions') }}
                    <QIcon name="open_in_new" color="primary" />
                </a>
                <div id="slider-container" class="q-px-xl q-py-md">
                    <QSlider
                        v-model="claim.responsibility"
                        label
                        :label-value="t('claim.summary.responsibility')"
                        label-always
                        color="primary"
                        markers
                        :marker-labels="[
                            { value: 1, label: t('claim.summary.company') },
                            { value: 5, label: t('claim.summary.person') },
                        ]"
                        :min="1"
                        :max="5"
                        readonly
                    />
                </div>
            </QCard>
            <QDialog
                v-model="multimediaDialog"
                transition-show="slide-up"
                transition-hide="slide-down"
            >
                <QToolbar class="absolute zindex close-button">
                    <QSpace />
                    <QBtn icon="close" color="primary" round dense v-close-popup />
                </QToolbar>
                <QCarousel
                    swipeable
                    animated
                    v-model="multimediaSlide"
                    arrows
                    class="fit"
                >
                    <QCarouselSlide
                        v-for="media of claimDms"
                        :key="media.dmsFk"
                        :name="media.dmsFk"
                    >
                        <QImg
                            :src="media.url"
                            class="fit"
                            fit="scale-down"
                            v-if="!media.isVideo"
                        />
                        <video
                            class="q-ma-none fit"
                            v-if="media.isVideo"
                            controls
                            muted
                            autoplay
                        >
                            <source :src="media.url" type="video/mp4" />
                        </video>
                    </QCarouselSlide>
                </QCarousel>
            </QDialog>
        </template>
    </CardSummary>
</template>
<style lang="scss">
.claimVnNotes {
    .q-card {
        max-width: 100%;
    }
}
</style>
<style lang="scss" scoped>
.q-dialog__inner--minimized > div {
    max-width: 80%;
}
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 15px;
    flex-basis: 30%;
}
.multimedia-container {
    flex: 1 0 21%;
}
.multimedia {
    transition: all 0.5s;
    opacity: 1;
    height: 250px;

    .q-img {
        object-fit: cover;
        background-color: black;
    }
    video {
        object-fit: cover;
        background-color: black;
    }
}

.multimedia:hover {
    opacity: 0.5;
}

.close-button {
    top: 1%;
    right: 10%;
}

.zindex {
    z-index: 1;
}
</style>
