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

import { useQuasar } from 'quasar';

import VnPaginate from 'src/components/ui/VnPaginate.vue';
import ModalCloseContract from 'src/pages/Customer/components/ModalCloseContract.vue';
import { toDate } from 'src/filters';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const quasar = useQuasar();

const vnPaginateRef = ref(null);
const showQPageSticky = ref(true);

const filter = {
    order: 'finished ASC, started DESC',
    include: [
        {
            relation: 'insurances',
            scope: {
                fields: ['id', 'credit', 'created', 'grade'],
                order: 'created DESC',
                limit: 2,
            },
        },
    ],
    where: { client: `${route.params.id}` },
};

const fetch = (data) => {
    data.forEach((element) => {
        if (!element.finished) {
            showQPageSticky.value = false;
            return;
        }
    });
};

const toCustomerCreditContractsCreate = () => {
    router.push({ name: 'CustomerCreditContractsCreate' });
};

const openDialog = (item) => {
    quasar.dialog({
        component: ModalCloseContract,
        componentProps: {
            id: item.id,
            promise: updateData,
        },
    });
    updateData();
    showQPageSticky.value = true;
};

const openViewCredit = (credit) => {
    router.push({
        name: 'CustomerCreditContractsInsurance',
        params: {
            creditId: credit.id,
        },
    });
};

const updateData = () => {
    vnPaginateRef.value?.fetch();
};
</script>

<template>
    <div class="full-width flex justify-center">
        <QCard class="card-width q-pa-lg">
            <VnPaginate
                :filter="filter"
                @on-fetch="fetch"
                auto-load
                data-key="CustomerCreditContracts"
                order="id DESC"
                ref="vnPaginateRef"
                url="CreditClassifications"
            >
                <template #body="{ rows }">
                    <div v-if="rows.length">
                        <QCard
                            v-for="(item, index) in rows"
                            :key="index"
                            :class="{
                                'customer-card': true,
                                'q-mb-md': index < rows.length - 1,
                                'is-active': !item.finished,
                            }"
                        >
                            <QCardSection
                                class="full-width flex justify-between q-py-none"
                            >
                                <div class="width-state flex">
                                    <div
                                        class="flex items-center cursor-pointer q-mr-md"
                                        v-if="!item.finished"
                                    >
                                        <QIcon
                                            @click.stop="openDialog(item)"
                                            color="primary"
                                            name="lock"
                                            size="md"
                                            class="fill-icon"
                                        >
                                            <QTooltip>{{ t('Close contract') }}</QTooltip>
                                        </QIcon>
                                    </div>

                                    <div>
                                        <div class="flex q-mb-xs">
                                            <div class="q-mr-sm color-vn-label">
                                                {{ t('Since') }}:
                                            </div>
                                            <div class="text-weight-bold">
                                                {{ toDate(item.started) }}
                                            </div>
                                        </div>
                                        <div class="flex">
                                            <div class="q-mr-sm color-vn-label">
                                                {{ t('To') }}:
                                            </div>
                                            <div class="text-weight-bold">
                                                {{ toDate(item.finished) }}
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <QSeparator vertical />

                                <div class="width-data flex">
                                    <div
                                        class="full-width flex justify-between items-center"
                                        v-if="item?.insurances.length"
                                    >
                                        <div class="flex">
                                            <div class="color-vn-label q-mr-xs">
                                                {{ t('Credit') }}:
                                            </div>
                                            <div class="text-weight-bold">
                                                {{ item.insurances[0].credit }}
                                            </div>
                                        </div>
                                        <div class="flex">
                                            <div class="color-vn-label q-mr-xs">
                                                {{ t('Grade') }}:
                                            </div>
                                            <div class="text-weight-bold">
                                                {{ item.insurances[0].grade || '-' }}
                                            </div>
                                        </div>
                                        <div class="flex">
                                            <div class="color-vn-label q-mr-xs">
                                                {{ t('Date') }}:
                                            </div>
                                            <div class="text-weight-bold">
                                                {{ toDate(item.insurances[0].created) }}
                                            </div>
                                        </div>
                                        <div class="flex items-center cursor-pointer">
                                            <QIcon
                                                @click.stop="openViewCredit(item)"
                                                color="primary"
                                                name="preview"
                                                size="md"
                                            >
                                                <QTooltip>{{
                                                    t('View credits')
                                                }}</QTooltip>
                                            </QIcon>
                                        </div>
                                    </div>
                                </div>
                            </QCardSection>
                        </QCard>
                    </div>
                    <h5 class="flex justify-center color-vn-label" v-else>
                        {{ t('globals.noResults') }}
                    </h5>
                </template>
            </VnPaginate>
        </QCard>
    </div>

    <QPageSticky :offset="[18, 18]" v-if="showQPageSticky">
        <QBtn
            @click.stop="toCustomerCreditContractsCreate()"
            color="primary"
            fab
            icon="add"
            shortcut="+"
        />
        <QTooltip>
            {{ t('New contract') }}
        </QTooltip>
    </QPageSticky>
</template>

<style lang="scss" scoped>
.customer-card {
    border: 2px solid var(--vn-light-gray);
    border-radius: 10px;
    padding: 10px;
    display: flex;
    justify-content: space-between;
}
.is-active {
    background-color: var(--vn-light-gray);
}
.width-state {
    width: 30%;
}
.width-data {
    width: 65%;
}
</style>

<i18n>
es:
    Close contract: Cerrar contrato
    Since: Desde
    To: Hasta
    Credit: Crédito
    Grade: Grade
    Date: Fecha
    View credits: Ver créditos
    Created: Fecha creación
    New contract: Nuevo contrato
</i18n>
