<script setup>
import { onMounted, ref, computed, onUpdated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { dashIfEmpty, toDate, toCurrency } from 'src/filters';
import CardSummary from 'components/ui/CardSummary.vue';
import FetchData from 'components/FetchData.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import InvoiceOutDescriptorProxy from 'pages/InvoiceOut/Card/InvoiceOutDescriptorProxy.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import VnLinkPhone from 'src/components/ui/VnLinkPhone.vue';
import { getUrl } from 'src/composables/getUrl';
import VnUserLink from 'src/components/ui/VnUserLink.vue';

onUpdated(() => summaryRef.value.fetch());

const route = useRoute();
const router = useRouter();

const { t } = useI18n();

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

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

const summaryRef = ref();
const ticket = ref();
const salesLines = ref(null);
const editableStates = ref([]);
const ticketUrl = ref();

onMounted(async () => {
    ticketUrl.value = (await getUrl('ticket/')) + entityId.value + '/';
});
async function setData(data) {
    if (data) {
        ticket.value = data;
        salesLines.value = data.sales;
    }
}

function formattedAddress() {
    if (!ticket.value) return '';

    const address = ticket.value.address;
    const postcode = address.postalCode;
    const province = address.province ? `(${address.province.name})` : '';

    return `${address.street} - ${postcode} - ${address.city} ${province}`;
}

function isEditable() {
    try {
        return !ticket.value.ticketState?.state?.alertLevel;
    } catch (e) {
        console.error(e);
    }

    return true;
}

async function changeState(value) {
    if (!ticket.value.id) return;

    const formData = {
        ticketFk: ticket.value.id,
        code: value,
    };

    await axios.post(`TicketTrackings/changeState`, formData);
    router.go(route.fullPath);
}
</script>

<template>
    <FetchData
        url="States/editableStates"
        @on-fetch="(data) => (editableStates = data)"
        auto-load
    />
    <CardSummary
        ref="summaryRef"
        :url="`Tickets/${entityId}/summary`"
        @on-fetch="(data) => setData(data)"
    >
        <template #header="{ entity }">
            <div>
                Ticket #{{ entity.id }} - {{ entity.client.name }} ({{
                    entity.client.id
                }}) -
                {{ entity.nickname }}
            </div>
        </template>
        <template #header-right>
            <QBtnDropdown
                side
                top
                color="orange-11"
                text-color="black"
                :label="t('ticket.summary.changeState')"
                :disable="!isEditable()"
            >
                <QList>
                    <QVirtualScroll
                        style="max-height: 300px"
                        :items="editableStates"
                        separator
                        v-slot="{ item, index }"
                    >
                        <QItem
                            :key="index"
                            dense
                            clickable
                            v-close-popup
                            @click="changeState(item.code)"
                        >
                            <QItemSection>
                                <QItemLabel>{{ item.name }}</QItemLabel>
                            </QItemSection>
                        </QItem>
                    </QVirtualScroll>
                </QList>
            </QBtnDropdown>
        </template>
        <template #body>
            <QCard class="vn-max">
                <div class="taxes">
                    <VnLv
                        :label="t('ticket.summary.subtotal')"
                        :value="toCurrency(ticket.totalWithoutVat)"
                    />
                    <VnLv
                        :label="t('ticket.summary.vat')"
                        :value="toCurrency(ticket.totalWithVat - ticket.totalWithoutVat)"
                    />
                    <VnLv
                        :label="t('ticket.summary.total')"
                        :value="toCurrency(ticket.totalWithVat)"
                    />
                </div>
            </QCard>
            <QCard class="vn-one">
                <a class="header header-link" :href="ticketUrl + 'basic-data/step-one'">
                    {{ t('globals.summary.basicData') }}
                    <QIcon name="open_in_new" />
                </a>
                <VnLv :label="t('ticket.summary.state')">
                    <template #value>
                        <QChip :color="ticket.ticketState?.state?.classColor ?? 'dark'">
                            {{ ticket.ticketState?.state?.name }}
                        </QChip>
                    </template>
                </VnLv>
                <VnLv :label="t('ticket.summary.salesPerson')">
                    <template #value>
                        <VnUserLink
                            :name="ticket.client?.salesPersonUser?.name"
                            :worker-id="ticket.client?.salesPersonFk"
                        />
                    </template>
                </VnLv>
                <VnLv
                    :label="t('ticket.summary.agency')"
                    :value="ticket.agencyMode.name"
                />
                <VnLv :label="t('ticket.summary.zone')" :value="ticket?.zone?.name" />
                <VnLv
                    :label="t('ticket.summary.warehouse')"
                    :value="ticket.warehouse?.name"
                />
                <VnLv :label="t('ticket.summary.route')" :value="ticket.routeFk" />
                <VnLv :label="t('ticket.summary.invoice')">
                    <template #value>
                        <span :class="{ link: ticket.refFk }">
                            {{ dashIfEmpty(ticket.refFk) }}
                            <InvoiceOutDescriptorProxy
                                :id="ticket.id"
                                v-if="ticket.refFk"
                            />
                        </span>
                    </template>
                </VnLv>
                <VnLv
                    :label="t('ticket.summary.weight')"
                    :value="dashIfEmpty(ticket.weight)"
                />
            </QCard>
            <QCard class="vn-one">
                <a class="header header-link" :href="ticketUrl + 'basic-data/step-one'">
                    {{ t('globals.summary.basicData') }}
                    <QIcon name="open_in_new" />
                </a>
                <VnLv
                    :label="t('ticket.summary.shipped')"
                    :value="toDate(ticket.shipped)"
                />
                <VnLv
                    :label="t('ticket.summary.landed')"
                    :value="toDate(ticket.landed)"
                />
                <VnLv :label="t('global.packages')" :value="ticket.packages" />
                <VnLv :value="ticket.address.phone">
                    <template #label>
                        {{ t('ticket.summary.consigneePhone') }}
                        <VnLinkPhone :phone-number="ticket.address.phone" />
                    </template>
                </VnLv>
                <VnLv :value="ticket.address.mobile">
                    <template #label>
                        {{ t('ticket.summary.consigneeMobile') }}
                        <VnLinkPhone :phone-number="ticket.address.mobile" />
                    </template>
                </VnLv>
                <VnLv :value="ticket.client.phone">
                    <template #label>
                        {{ t('ticket.summary.clientPhone') }}
                        <VnLinkPhone :phone-number="ticket.client.phone" />
                    </template>
                </VnLv>
                <VnLv :value="ticket.client.mobile">
                    <template #label>
                        {{ t('ticket.summary.clientMobile') }}
                        <VnLinkPhone :phone-number="ticket.client.mobile" />
                    </template>
                </VnLv>
                <VnLv
                    :label="t('ticket.summary.consignee')"
                    :value="formattedAddress()"
                />
            </QCard>
            <QCard class="vn-one">
                <a class="header header-link" :href="ticketUrl + 'observation'">
                    {{ t('ticket.pageTitles.notes') }}
                    <QIcon name="open_in_new" />
                </a>
                <VnLv
                    v-for="note in ticket.notes"
                    :key="note.id"
                    :label="note.observationType.description"
                    :value="note.description"
                >
                    <template #value>
                        <QInput
                            v-model="note.description"
                            filled
                            type="textarea"
                            class="notes"
                            readonly
                        />
                    </template>
                </VnLv>
            </QCard>
            <QCard class="vn-max">
                <a class="header header-link" :href="ticketUrl + 'sale'">
                    {{ t('ticket.summary.saleLines') }}
                    <QIcon name="open_in_new" />
                </a>
                <QTable :rows="ticket.sales">
                    <template #header="props">
                        <QTr :props="props">
                            <QTh auto-width></QTh>
                            <QTh auto-width>{{ t('ticket.summary.item') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.visible') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.available') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.quantity') }}</QTh>
                            <QTh auto-width>{{ t('globals.description') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.price') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.discount') }}</QTh>
                            <QTh auto-width>{{ t('globals.amount') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.packing') }}</QTh>
                        </QTr>
                    </template>
                    <template #body="props">
                        <QTr :props="props">
                            <QTd>
                                <QBtn
                                    flat
                                    round
                                    size="xs"
                                    icon="vn:claims"
                                    v-if="props.row.claim"
                                    color="primary"
                                    :to="{
                                        name: 'ClaimCard',
                                        params: {
                                            id: props.row.claim.claimFk,
                                        },
                                    }"
                                >
                                    <QTooltip
                                        >{{ t('ticket.summary.claim') }}:
                                        {{ props.row.claim.claimFk }}</QTooltip
                                    >
                                </QBtn>
                                <QBtn
                                    flat
                                    round
                                    size="xs"
                                    icon="vn:claims"
                                    v-if="props.row.claimBeginning"
                                    color="primary"
                                    :to="{
                                        name: 'ClaimCard',
                                        params: {
                                            id: props.row.claimBeginning.claimFk,
                                        },
                                    }"
                                >
                                    <QTooltip
                                        >{{ t('ticket.summary.claim') }}:
                                        {{ props.row.claimBeginning.claimFk }}</QTooltip
                                    >
                                </QBtn>
                                <QIcon
                                    name="warning"
                                    v-show="props.row.visible < 0"
                                    size="xs"
                                    color="primary"
                                >
                                    <QTooltip
                                        >{{ t('ticket.summary.visible') }}:
                                        {{ props.row.visible }}</QTooltip
                                    >
                                </QIcon>
                                <QIcon
                                    name="vn:reserva"
                                    v-show="props.row.reserved"
                                    size="xs"
                                    color="primary"
                                >
                                    <QTooltip>
                                        {{ t('ticket.summary.reserved') }}
                                    </QTooltip>
                                </QIcon>
                                <QIcon
                                    name="vn:unavailable"
                                    v-show="props.row.itemShortage"
                                    size="xs"
                                    color="primary"
                                >
                                    <QTooltip>
                                        {{ t('ticket.summary.itemShortage') }}
                                    </QTooltip>
                                </QIcon>
                                <QIcon
                                    name="vn:components"
                                    v-show="props.row.hasComponentLack"
                                    size="xs"
                                    color="primary"
                                >
                                    <QTooltip>
                                        {{ t('ticket.summary.hasComponentLack') }}
                                    </QTooltip>
                                </QIcon>
                            </QTd>
                            <QTd class="link">{{ props.row.itemFk }}</QTd>
                            <QTd>{{ props.row.visible }}</QTd>
                            <QTd>{{ props.row.available }}</QTd>
                            <QTd>{{ props.row.quantity }}</QTd>
                            <QTd>
                                <div class="fetched-tags">
                                    <span>{{ props.row.item.name }}</span>
                                    <span v-if="props.row.item.subName" class="subName">{{
                                        props.row.item.subName
                                    }}</span>
                                </div>
                                <fetched-tags
                                    :item="props.row.item"
                                    :max-length="5"
                                ></fetched-tags>
                            </QTd>
                            <QTd>{{ props.row.price }}</QTd>
                            <QTd>{{ props.row.discount }} %</QTd>
                            <QTd
                                >{{
                                    toCurrency(
                                        props.row.quantity *
                                            props.row.price *
                                            ((100 - props.row.discount) / 100)
                                    )
                                }}
                            </QTd>
                            <QTd>{{ dashIfEmpty(props.row.item.itemPackingTypeFk) }}</QTd>
                        </QTr>
                    </template>
                </QTable>
            </QCard>
            <QCard
                class="vn-max"
                v-if="ticket.packagings.length > 0 || ticket.services.length > 0"
            >
                <a class="header header-link" :href="ticketUrl + 'package'">
                    {{ t('globals.packages') }}
                    <QIcon name="open_in_new" />
                </a>
                <QTable :rows="ticket.packagings" flat>
                    <template #header="props">
                        <QTr :props="props">
                            <QTh auto-width>{{ t('ticket.summary.created') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.package') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.quantity') }}</QTh>
                        </QTr>
                    </template>
                    <template #body="props">
                        <QTr :props="props">
                            <QTd>{{ toDate(props.row.created) }}</QTd>
                            <QTd>{{ props.row.packaging.item.name }}</QTd>
                            <QTd>{{ props.row.quantity }}</QTd>
                        </QTr>
                    </template>
                </QTable>

                <a class="header header-link q-mt-xl" :href="ticketUrl + 'service'">
                    {{ t('ticket.summary.service') }}
                    <QIcon name="open_in_new" />
                </a>
                <QTable :rows="ticket.services" flat>
                    <template #header="props">
                        <QTr :props="props">
                            <QTh auto-width>{{ t('ticket.summary.quantity') }}</QTh>
                            <QTh auto-width>{{ t('globals.description') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.price') }}</QTh>
                            <QTh auto-width>{{ t('ticket.summary.taxClass') }}</QTh>
                            <QTh auto-width>{{ t('globals.amount') }}</QTh>
                        </QTr>
                    </template>
                    <template #body="props">
                        <QTr :props="props">
                            <QTd>{{ props.row.quantity }}</QTd>
                            <QTd>{{ props.row.description }}</QTd>
                            <QTd>{{ toCurrency(props.row.price) }}</QTd>
                            <QTd>{{ props.row.taxClass.description }}</QTd>
                            <QTd>{{
                                toCurrency(props.row.quantity * props.row.price)
                            }}</QTd>
                        </QTr>
                    </template>
                </QTable>
            </QCard>
        </template>
    </CardSummary>
</template>
<style lang="scss" scoped>
.notes {
    width: max-content;
}
.cardSummary .summaryBody > .q-card > .taxes {
    border: 2px solid gray;
    padding: 0;
    > .vn-label-value {
        text-align: right;
        display: flex;
        flex-direction: row;
        margin-top: 5px;
        justify-content: flex-end;
        padding-right: 20px;
    }
}

.cardSummary .summaryBody > .q-card:has(.taxes) {
    margin-top: 2px;
    padding: 0;
}
</style>
