<template>
    <div class="row">
        <div class="col">
            <loading-component style="height: 200px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
            <div class="row" v-if="transaction">
                <div class="col">
                    <div class="row p-b-5 b-b b-grey m-b-10 m-l-0 m-r-0">
                        <div class="col no-padding">
                            <h6>Account Statement - Transaction History</h6>
                        </div>
                    </div>
                    <div class="row" v-if="transaction">
                        <div class="col">
                            <div class="row padding-10">
                                <div class="col-2 fs-10">Date</div>
                                <div class="col-3 fs-10">Description</div>
                                <div class="col fs-10">Marking</div>
                                <div class="col-2 fs-10 text-center">Incoming</div>
                                <div class="col-2 fs-10 text-center">Outgoing</div>
                                <div class="col-2 fs-10 text-right">Balance</div>
                            </div>

                            <div class="row bg-white padding-10 m-b-10 rounded" v-for="(item, index) in transaction" :key="item.id">
                                <div class="col-2 fs-12">{{item.created_at}}</div>
                                <div class="col-3 fs-12">
                                    {{ convertTransactionType(item.type) }} {{ item.payment_reference ? ' - ' + item.payment_reference : '' }}
                                    <a target="_blank" v-if="[9,11].includes(parseFloat(item.type))" @click="downloadTransaction(item)">
                                        <i class="fa fa-download fs-11 m-l-5 text-secondary hover-primary"></i>
                                    </a>
                                </div>
                                <div class="col fs-12"><a :href="route('booking.details', item.booking_marking)">{{item.booking_marking}}</a></div>
                                <div class="col-2 text-success text-center" v-if="parseFloat(item.type) !== 2">
                                    {{[5, 9].includes(parseFloat(item.type)) ? (Math.round((parseFloat(item.amount) + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : ''}}
                                </div>
                                <div class="col-2 text-success text-center" v-if="parseFloat(item.type) === 2">
                                    {{(Math.round(((parseFloat(item.amount) / parseFloat(item.currency_rate) + parseFloat(item.service_charge)) + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
                                </div>
                                <div class="col-2 text-danger text-center">
                                    {{[1, 11].includes(parseFloat(item.type)) ? '- ' + (Math.round((parseFloat(item.amount) + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : ''}}
                                </div>
                                <div class="col-2 text-right">{{remainingBalance(index)}}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useRequest } from '@/composables/useRequest';
import { useQueueStore } from '@/stores/queue';
import route from '@/general/functions/router';

const props = defineProps<{
    id: number;
}>();

const section = 'customerTransactionSection';
const { submit } = useRequest();
const queueStore = useQueueStore();

const transaction = ref<any[] | null>(null);
const attention = ref(false);
const isLoading = ref(true);

const pendingQueue = computed(() => queueStore.isInCompleteQueue(section));

const successHandler = (response: any) => {
    isLoading.value = false;
    transaction.value = response.payload.data;
};

const fetchTransaction = () => {
    isLoading.value = true;
    submit(
        route('api.transaction.company.transaction.fetch', props.id),
        'get',
        section,
        false,
        false,
        undefined,
        {
            successHandler
        }
    );
};

watch(pendingQueue, (inComplete) => {
    if (inComplete) {
        fetchTransaction();
    }
});

const convertTransactionType = (type: any) => {
    const t = parseFloat(type);
    const transactionTypeArray: Record<number, string> = {
        0: 'Payment Attempt',
        1: 'Payment',
        2: 'Invoice',
        3: 'Bill',
        4: 'Proforma',
        5: 'Top Up',
        6: 'Refund',
        7: 'Purchase Order',
        8: 'Supplier Deliver',
        9: 'Credit Note',
        11: 'Debit Note',
        10: 'Withdraw',
        12: 'Transfer Fee',
        13: 'Cash Back'
    };
    return transactionTypeArray[t];
};

const remainingBalance = (index: number) => {
    let tempBalance = 0;

    if (transaction.value) {
        let transactions = [...transaction.value].reverse();
        transactions.slice(0, transactions.length - index).forEach((t: any) => {
            const type = parseFloat(t.type);
            const amount = parseFloat(t.amount);
            if (type === 2) {
                tempBalance += (amount / parseFloat(t.currency_rate) + parseFloat(t.service_charge));
            } else {
                [1, 11].includes(type) ? tempBalance -= amount : tempBalance += amount;
            }
        });
    }

    return (Math.round((tempBalance + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const downloadTransaction = (paramItem: any) => {
    const url = route('transaction.credit_note.download', paramItem.id);
    if (window.LARAVEL_VAPOR_ENABLED) {
        fetch(url, { method: 'GET' })
            .then(response => {
                const success = response.ok;
                response.json().then(data => {
                    if (!success) return;
                    if (data.src) {
                        window.open(data.src, '_blank');
                    }
                });
            });
    } else {
        window.open(url, '_blank');
    }
};

onMounted(() => {
    queueStore.updateListQueue({ name: section });
});
</script>
