<template>
    <div class="row parentContainer">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div v-show="!$store.getters.isLoading(section)">
                        <list-component :section="section" :endpoint="endpoint" :options="options">
                            <template slot="list" slot-scope="{data}">
                                <!-- <payments-billing-components v-if="endpoint == route('api.transaction.list') && !data.storages" :section="section" :data="data" :selectedInvoice="selectedInvoice" v-on:input="updateList($event)"></payments-billing-components> -->
                                <payments-billing-variant-2-components v-if="endpoint == route('api.transaction.list')" :section="section" :invoices="getMergedInvoices(data, data.storages)" :selectedInvoice="selectedInvoice" :isPaidInvoices="isPaidInvoices" v-on:input="updateList($event)"></payments-billing-variant-2-components>
                                <group-payments-billing-components v-else :section="section" :data="data" :selectedInvoice="selectedInvoice" v-on:input="updateList($event)"></group-payments-billing-components>
                            </template>
                        </list-component>
                    </div>
                </div>
                <div class="col-12 col-sm-12 col-md-4" v-if="!['customerPaidGroupInvoiceComponent', 'customerGroupPaymentInProgressInvoiceComponent', 'customerGroupPaymentExpiredInvoiceComponent'].includes(section)">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="row" v-if="section === 'customerPendingPaymentInvoiceComponent'">
                                <div class="col m-b-15">
                                    <wallet-component :company_module_id="company_module_id" section="billingWalletSection" :creditable=true></wallet-component>
                                </div>
                            </div>
                            <div class="b-a b-grey rounded padding-25 bg-white">
                                <div class="row">
                                    <div class="col">
                                        <h6 class="semi-bold muted">Summary</h6>
                                    </div>
                                </div>
                                <div class="row align-items-center justify-content-center">
                                    <div class="col-auto">
                                        <div class="padding-5">
                                            <i class="fa fa-angle-up"></i>
                                        </div>
                                    </div>
                                    <div class="col p-l-0">
                                        <h6 class="semi-bold text-primary">{{selectedInvoice.length}} Invoice Selected</h6>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col">
                                        <div class="row" v-for="invoice in selectedInvoice">
                                            <div class="col">
                                                <h6 class="no-margin">{{ invoice.bill_no }}</h6>
                                            </div>
                                            <div class="col-auto">
                                                <h6 class="no-margin">MYR  {{ invoice.amount.toFixed(2) }}</h6>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <hr>
                                <div class="row">
                                    <div class="col">
                                        <h6 class="normal m-t-0 m-b-0">Total Amount</h6>
                                    </div>
                                    <div class="col-auto">
                                        <h6 class="text-primary bold m-t-0 m-b-0">MYR {{ sumAmount }}</h6>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row" v-if="selectedInvoice.length">
                        <div class="col">
                            <div v-if="section === 'customerPendingPaymentInvoiceComponent'" class="btn btn-success btn-xl pointer m-t-10 w-100 requestModal" data-type="makePayment">Make Payment</div>
                            <div v-if="['customerPaidInvoiceComponent', 'customerPendingPaymentInvoiceComponent'].includes(section)" class="btn btn-info btn-xl pointer m-t-10 w-100" @click='generateSummaryInvoice'>Generate Summary Invoice</div>
                        </div>
                    </div>
                    <modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="makePayment">
                        <group-payment-form-component :section="section" :company_module_id="company_module_id" :selectedIds="selectedIds" :sumAmount="sumAmount"></group-payment-form-component>
                    </modal-component>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        props: {
            options: {
                default () {
                    return {}
                }
            },
            section:{
                type: String,
                required: true
            },
            company_module_id: {
                type: Number,
                required: true,
            },
            endpoint: {
                type: String,
                required: true
            },
            isPaidInvoices :{
                type: Boolean,
                default: false
            }
        },
        data(){
            return {
                isLoading: true,
                invoices: null,
                selectedInvoice: [],
                selectedPaidInvoice: [],
                selectedUnpaidInvoice: [],
                selectAllInvoice: false,
            }
        },
        computed: {
            pendingQueue () {
                return this.$store.getters.isInCompleteQueue(this.section);
            },
            sumAmount () {
                var new_object = this.selectedInvoice;
                return Object.keys(new_object).reduce(function(total, key) {
                    return total + Math.round(new_object[key].amount * 100) / 100;
                }, 0).toFixed(2);
            },
            selectedIds () {
                return this.selectedInvoice.map(s=>s.id);
            }
        },
        methods: {
            generateSummaryInvoice(){
                window.open(route('invoice.combined_summary', JSON.stringify(this.selectedIds)), '_blank');
            },
            makePayment(){
                this.submit(this.route('api.transaction.group.create', JSON.stringify(this.selectedId)), 'post', this.section, true, false);
            },
            updateList(invoices){
                invoices.forEach(invoice => {
                    if (this.selectedInvoice.includes(invoice)) {
                        this.selectedInvoice.splice(this.selectedInvoice.indexOf(invoice), 1);
                    } else {
                        this.selectedInvoice.push(invoice);
                    }
                });

            },
            getMergedInvoices(shippingInvoice, storages){
                if(storages){
                    const storageMap = {};
                    for (const storage of storages) {
                        storageMap[storage.parentInvoiceId] = storage.storageInvoiceId;
                    }

                    const storageInvoiceId = storageMap[shippingInvoice.id];
                    const storage = storages.find((i) => {
                        return i.storageInvoiceId === storageInvoiceId;
                    });

                    const mergedArray = [
                        ...(shippingInvoice ? [shippingInvoice] : []),
                        ...(storage && storage.storageInvoice.status !== 3 ? [storage.storageInvoice] : [])
                    ];
                    return mergedArray;
                }

                const mergedArray = [
                    ...(shippingInvoice ? [shippingInvoice] : [])
                ];
                return mergedArray;
            }
        }
    }
</script>
