<template>
    
        <!-- <router-link to="/">Go back to Home</router-link> -->
        <!-- <div class="contrainer" v-if="id==null && !loading">
            <div class="row">
                <div class="card col-md-4 my-3 mx-auto bg-secondary p-1">
                    <h4>Please select an Invoice :</h4>
                    <select v-model="id" class="col-sm-12 col-md-6 form-select form-select-lg mb-3" aria-label=".form-select-lg example" @change.prevent="getInvoiceData()">
                        <option selected>Open this select menu</option>
                        <option v-for="(temp,index) in ddHolder.invoices" :key="index" :value="temp.id" :selected="temp.id==id">{{ temp.name }}</option>            
                    </select>
                </div>


            </div>
        </div> -->
        <cdTable :allowNew="false" :links="links" title="Invoices" table-name="invoices" :hidden="hidden" :headers="headers" :gen-form="false" v-if="id==null && !loading" @popForm="e=>getInvoiceData(e)" ></cdTable>
        <div class="container" v-else>

            <div class="printblock border border-1 shadow p-3 mb-5 bg-white rounded mx-auto" >
                                <div class="row g-0" v-if="invoice['biller_header_type']">
                            <!-- BILLER HEADER -->             
                            <div class="col-12 py-0 bg-light px-1 rounded border border-1 shadow-sm mb-3">
                                <div class="container border-bottom border-1 mb-0">
                                                                        <div class="row align-items-center">
                                                                                <img
                                                                                    v-if="invoice['biller_header_logo_url'] && ['logo_only','logo_entity_name','logo_custom_text'].includes(invoice['biller_header_type'])"
                                                                                    :src="invoice['biller_header_logo_url']"
                                                                                    alt="logo"
                                                                                    class="object-fit-contain col-4 pb-0"
                                                                                    style="height: 2cm;"
                                                                                >
                                                                                <h3
                                                                                    v-if="invoice['biller_header_type'] === 'logo_entity_name' || invoice['biller_header_type'] === 'entity_name_only'"
                                                                                    :class="invoice['biller_header_logo_url'] && ['logo_only','logo_entity_name','logo_custom_text'].includes(invoice['biller_header_type']) ? 'col-8 pb-0 text-start' : 'col-12 pb-0 text-start'"
                                                                                >
                                                                                    {{ invoice['biller_name'] }}
                                                                                </h3>
                                                                                <h3
                                                                                    v-else-if="invoice['biller_header_type'] === 'logo_custom_text'"
                                                                                    :class="invoice['biller_header_logo_url'] ? 'col-8 pb-0 text-start' : 'col-12 pb-0 text-start'"
                                                                                >
                                                                                    {{ invoice['biller_header_custom_text'] || invoice['biller_name'] }}
                                                                                </h3>
                                                                                <h3
                                                                                    v-else-if="invoice['biller_header_type'] === 'custom_text_only'"
                                                                                    class="col-12 pb-0 text-start"
                                                                                >
                                                                                    {{ invoice['biller_header_custom_text'] }}
                                                                                </h3>
                                                                        </div>
                                                                </div>
                                                <div class="container border-bottom border-1 mb-0" v-if="invoice['biller_header_type'] === 'logo_only'">
                                                        <h3 class="pb-0">{{ invoice['biller.name'] }}</h3>
                        </div>
                                <div class="row g-0">
                                    <div class="col-8 p-1 border-end border-1">
                                        <div class="d-flex flex-column align-items-start">
                                            <p class="m-0" style="text-align: justify;"><b>Address: </b>{{ invoice['biller_address']+', '+invoice['biller_contact_no']+', '+invoice['biller_email'] }},</p>
                                            <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>PAN: </b> {{  invoice['biller_pan'] }}, <b>GST: </b> {{ invoice['biller_gst']==null? 'N/A': invoice['biller_gst']}}</p>
                                            <p v-if="invoice['biller_tax_details']!=null" class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>Note: </b> {{ invoice['biller_tax_details']}}</p>
                                            <hr class="hr"/>
                                        </div>
                                    </div>
                                    <div class="col-4 d-xl-flex justify-content-xl-end align-items-xl-center px-3">
                                        <!-- <p><b>Invoice Date:</b>{{getDayForm(new Date(invoice.createdAt))}}</p> -->
                                        <div class="d-flex flex-column align-items-start">
                                            <p v-if="!editMode"><b>Invoice No:</b>{{ invoice.invoice_no }}</p>
                                            <div v-else class="input-group input-group-sm mb-1">
                                                <span class="input-group-text">Invoice No</span>
                                                <input type="text" class="form-control" v-model="invoice.invoice_no">
                                            </div>
                                            <p><b>Invoice Date:</b>{{getDayForm(new Date(invoice.createdAt))}}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- BILLER HEADER ENDS -->
                            <!-- PAYEE SECTION -->
                            <div class="col-12 py-0 bg-light px-1 rounded border border-1 shadow-sm mb-3">
                                <div class="container border-bottom border-1 mb-0">
                                    <h4 class="pb-0">Payee Details</h4>
                                </div>
                                <div class="row g-0">
                                    <div class="col-12 p-1 ">
                                        <div class="d-flex flex-column align-items-start">
                                            <p class="m-0" style="text-align: justify;"><b>Name: </b>{{ invoice['payee_name'] }}</p>
                                            <p class="m-0" style="text-align: justify;"><b>Address: </b>{{ invoice['payee_address']+', '+invoice['payee_contact_no']+', '+invoice['payee_email'] }},</p>
                                            <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>PAN: </b> {{  invoice['payee_pan'] }}, <b>GST: </b> {{ invoice['payee_gst']==null? 'N/A': invoice['biller_gst']}}</p>
                                            <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>Note: </b> {{ invoice['payee_tax_details']==null? '': invoice['payee_tax_details']}}</p>
                                            <hr class="hr">
                                        </div>
                                    </div>                            
                                </div>
                            </div>
                            <!-- PAYEE SECTION ENDS -->
                            
                            <div class="col-12 px-1">
                                <!-- REGULAR INVOICE TABLE -->
                                <table class="table">
                                <thead>
                                    <tr>
                                    <th scope="col" class="text-start" style="width: 80px;">#</th>
                                    <th scope="col" class="text-start">Billable</th>
                                    <th scope="col" class="text-end" >Qty</th>
                                    <th scope="col" class="text-end" >Cost</th>
                                    <th scope="col" class="text-end" >Sub Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(item,index) in invoice.billables" :key="index">                                
                                    <th scope="row" class="text-start py-0" style="width: 80px;">{{ index+1 }}</th>
                                    <td class="py-0">{{ item.name }}</td>
                                    <td class="text-end py-0">
                                        <span v-if="!editMode">{{ item.qty }}</span>
                                        <input v-else class="form-control form-control-sm text-end" type="number" min="1" step="1" v-model.number="item.qty" @change="item.subTotal=item.qty*item.cost;setTotal();setTaxes();">
                                    </td>
                                    <td class="text-end py-0">
                                        <span v-if="!editMode">{{ formatCurrency(item.cost) }}</span>
                                        <input v-else class="form-control form-control-sm text-end" type="number" min="0" step=".01" v-model.number="item.cost" @change="item.subTotal=item.qty*item.cost;setTotal();setTaxes();">
                                    </td>
                                    <td class="text-end py-0" >{{ formatCurrency(item.subTotal) }}</td>                              
                                    </tr>
                                    <tr class="table-secondary text-white">
                                        <td></td>
                                    <th scope="row" class="text-start" colspan="3">Total before Taxes ===></th>
                                    <td  class="text-end m-0">

                                        <b> {{ formatCurrency(total) }}</b>
                                    </td>
                                    
                                    </tr>
                                    <tr class="table-secondary text-white">
                                        <td></td>
                                    <th scope="row" class="text-start"  colspan="1"> Taxes ===></th>
                                    <td class="text-end p-0" colspan="4">

                                        <p class="text-end m-0" v-for="t,i in taxes" :key="i"> {{ t.name }}: {{ formatCurrency(t.val)}}</p>
                                    </td>
                                    </tr>
                                    <tr class="table-secondary text-white">
                                        <td></td>
                                    <th scope="row" class="text-start"  colspan="3">Total With Taxes ===></th>
                                    <td  class="text-end">

                                        <b> {{ formatCurrency(getTotal) }}</b>
                                    </td>
                                    </tr>
                                    <tr class="table-secondary text-white">
                                        <td></td>
                                        <td scope="row" class="text-start"  colspan="4">
                                            <b>In words: </b><i> {{ convertToWords(getTotal,currency) }}</i>
                                    </td>
                                    </tr>
                                </tbody>
                                </table>
                                <!-- REGULAR INVOICE TABLE ENDS -->
                            </div>
                            <div class="col-12" >
                                <!-- View mode terms -->
                                <template v-if="!editMode">
                                    <bsList v-if="invoice['terms']" :terms="invoice['terms']['delivery']" :title="'Terms Of Delivery'"/>
                                    <hr/>
                                    <bsList v-if="invoice['terms']" :terms="invoice['terms']['payment']" :title="'Terms Of Payment'"/>
                                </template>
                                <!-- Edit mode terms -->
                                <template v-else>
                                    <div class="card mb-2">
                                        <div class="card-header bg-secondary text-white fw-bold">Terms Of Delivery</div>
                                        <div class="card-body p-2">
                                            <div v-for="(term, i) in invoice.terms.delivery" :key="i" class="input-group input-group-sm mb-1">
                                                <input type="text" class="form-control" v-model="invoice.terms.delivery[i]">
                                                <button class="btn btn-outline-danger btn-sm" @click.prevent="invoice.terms.delivery.splice(i,1)">&#x2715;</button>
                                            </div>
                                            <button class="btn btn-outline-secondary btn-sm mt-1" @click.prevent="invoice.terms.delivery.push('')">+ Add Term</button>
                                        </div>
                                    </div>
                                    <hr/>
                                    <div class="card mb-2">
                                        <div class="card-header bg-secondary text-white fw-bold">Terms Of Payment</div>
                                        <div class="card-body p-2">
                                            <div v-for="(term, i) in invoice.terms.payment" :key="i" class="input-group input-group-sm mb-1">
                                                <input type="text" class="form-control" v-model="invoice.terms.payment[i]">
                                                <button class="btn btn-outline-danger btn-sm" @click.prevent="invoice.terms.payment.splice(i,1)">&#x2715;</button>
                                            </div>
                                            <button class="btn btn-outline-secondary btn-sm mt-1" @click.prevent="invoice.terms.payment.push('')">+ Add Term</button>
                                        </div>
                                    </div>
                                </template>
                                <hr/>
                                <div class="input-group mb-3">
                                <span class="input-group-text" id="input1">Note</span>
                                <input
                                    type="text"
                                    class="form-control"
                                    placeholder=" -- -- --"
                                    aria-label="Note"
                                    aria-describedby=" -- -- --"
                                    v-model="invoice.note"
                                    :disabled="!editMode"
                                />
                                </div>
                            </div>
                            <!-- PAYEE SECTION -->
                            <div class="col-12 py-0 bg-light px-1 rounded border border-1 shadow-sm mb-3">
                                <div class="container border-bottom border-1 mb-0">
                                    <h4 class="pb-0">Payment Option / Bank Details</h4>
                                </div>
                                <div class="row g-0">
                                    <div class="col-12 p-1 ">
                                        <div class="d-flex flex-column align-items-start">
                                            <p class="m-0 display-6" style="text-align: justify;font-size: initial;"><b>Bank Account </b></p>
                                            <p class="m-0" style="text-align: justify;"><b>Name on Account: </b>{{ invoice['bank_account_name'] }}</p>
                                            <p class="m-0" style="text-align: justify;"><b>Bank Name: </b>{{ invoice['bank_name'] }},</p>
                                            <p class="m-0" style="text-align: justify;"><b>Account No.: </b>{{ invoice['bank_account_no'] }},</p>
                                            <p class="m-0" style="text-align: justify;"><b>IFSC Code: </b>{{ invoice['bank_branch_ifsc'] }}</p>
                                            
                                            <hr class="hr">
                                        </div>
                                    </div>                            
                                </div>
                            </div>
                            <!-- PAYEE SECTION ENDS -->
                            <div class="col-12 d-flex justify-content-center align-items-center noprint flex-wrap gap-2">
                                <button v-if="!editMode" class="btn btn-warning mx-2" @click.prevent="startEdit()">Edit</button>
                                <button v-if="editMode" class="btn btn-success mx-2" @click.prevent="updateInvoice()">Save Changes</button>
                                <button v-if="editMode" class="btn btn-danger mx-2" @click.prevent="cancelEdit()">Cancel</button>
                                <button class="btn btn-primary mx-2" @click.prevent="printInvoice()">Print</button>
                                <button class="btn btn-secondary mx-2" @click.prevent="id=null;">Back</button>
                            </div>

                            <!-- HISTORY INDICATOR & TIMELINE -->
                            <div class="col-12 noprint mt-3" v-if="changeLogs.length > 0">
                                <div class="d-flex justify-content-center">
                                    <button class="btn btn-outline-secondary btn-sm" @click.prevent="showHistory = !showHistory">
                                        🕐 {{ changeLogs.length }} Change{{ changeLogs.length > 1 ? 's' : '' }}
                                        <span class="badge bg-secondary ms-1">{{ changeLogs.length }}</span>
                                        <span class="ms-1">{{ showHistory ? '▲' : '▼' }}</span>
                                    </button>
                                </div>
                                <div v-if="showHistory" class="mt-3 px-2">
                                    <h6 class="text-muted text-center mb-3">Change History</h6>
                                    <div class="timeline">
                                        <div v-for="(log, idx) in changeLogs" :key="log.id" class="timeline-item mb-4">
                                            <div class="d-flex align-items-start gap-2">
                                                <div class="timeline-dot bg-secondary rounded-circle flex-shrink-0 mt-1" style="width:12px;height:12px;"></div>
                                                <div class="flex-grow-1 border rounded p-2 bg-light">
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <small class="text-muted fw-semibold">Change #{{ changeLogs.length - idx }}</small>
                                                        <small class="text-muted">{{ new Date(log.createdAt).toLocaleString() }}</small>
                                                    </div>
                                                    <ul class="list-unstyled mb-0 small">
                                                        <template v-if="log.og_data && log.new_data">
                                                            <li v-if="log.og_data.invoice_no !== log.new_data.invoice_no">
                                                                <strong>Invoice No:</strong>
                                                                <span class="text-danger text-decoration-line-through ms-1">{{ log.og_data.invoice_no }}</span>
                                                                <span class="text-success ms-1">→ {{ log.new_data.invoice_no }}</span>
                                                            </li>
                                                            <li v-if="log.og_data.note !== log.new_data.note">
                                                                <strong>Note:</strong>
                                                                <span class="text-danger text-decoration-line-through ms-1">{{ log.og_data.note || '(empty)' }}</span>
                                                                <span class="text-success ms-1">→ {{ log.new_data.note || '(empty)' }}</span>
                                                            </li>
                                                            <li v-if="JSON.stringify(log.og_data.billables) !== JSON.stringify(log.new_data.billables)">
                                                                <strong>Billables:</strong> <span class="text-muted">line items changed</span>
                                                            </li>
                                                            <li v-if="JSON.stringify(log.og_data.terms) !== JSON.stringify(log.new_data.terms)">
                                                                <strong>Terms:</strong> <span class="text-muted">delivery/payment terms changed</span>
                                                            </li>
                                                        </template>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- HISTORY ENDS -->
                            
                        </div>
                        <!-- <div class="row" >
                            <div class="col-6">
                                
                                <p>Invoice for: {{ invoice.entity }}</p>
                                <p>Amount: {{ invoice.amount }}</p>
                                <p>Date: {{ invoice.date }}</p>
                            </div>
                            <div class="col-6">
                            </div> 
                        </div> -->
                    </div>
            </div>
</template>
<script>
import { convertToWords } from '@/parts/numwords';
import { dropDownLinks,invoiceLinks, changeLogLinks } from '@/cd-links';
import bsList from '@/parts/bs-list.vue';
import cdTable from '@/components/cddatatables/cdTable.vue';
import getDayForm from '@/parts/dayForm';
/* import Editor from '@tinymce/tinymce-vue'; */

    export default {
        name: 'InvoiceView',
        components: {
            /* Editor, */ bsList, cdTable,
        },
        data() {
            return {
                links: invoiceLinks,
                editor: null,
                id: null,
                loading: false,
                editMode: false,
                invoiceOriginal: null,
                changeLogs: [],
                showHistory: false,
                ddHolder: {
                    invoices: [],                    
                },
                total:0,
                taxes:[],
                currency:'INR',
                curr:{
                    'INR': {
                        name: 'Indian Rupee',
                        code: 'INR',
                        symbol: '₹'
                    },
                    'USD': {
                        name: 'United States Dollar',
                        code: 'USD',
                        symbol: '$'
                    },
                    'EUR': {
                        name: 'Euro',
                        code: 'EUR',
                        symbol: '€'
                    },
                    'GBP': {
                        name: 'British Pound Sterling',
                        code: 'GBP',
                        symbol: '£'
                    },
                    'AUD': {
                        name: 'Australian Dollar',
                        code: 'AUD',
                        symbol: 'A$'
                    },
                    'CAD': {
                        name: 'Canadian Dollar',
                        code: 'CAD',
                        symbol: 'C$'
                    },
                    'CHF': {
                        name: 'Swiss Franc',
                        code: 'CHF',
                        symbol: 'CHF'
                    },
                    'CNY': {
                        name: 'Chinese Yuan',
                        code: 'CNY',
                        symbol: '¥'
                    },
                    'JPY': {
                        name: 'Japanese Yen',
                        code: 'JPY',
                        symbol: '¥'
                    },
                    'NZD': {
                        name: 'New Zealand Dollar',
                        code: 'NZD',
                        symbol: 'NZ$'
                    },
                    'SEK': {
                        name: 'Swedish Krona',
                        code: 'SEK',
                        symbol: 'kr'
                    },
                    'RUB': {
                        name: 'Russian Ruble',
                        code: 'RUB',
                        symbol: '₽'
                    }
                },
                invoice: {
                    billables: [],
                    tax_id: [],
                    terms: {
                        delivery: [],
                        payment: []
                    },
                    note: null,
                    'biller_name': null,
                    'biller_address': null,
                    'biller_contact_no': null,
                    'biller_email': null,
                    'biller_pan': null,
                    'biller_gst': null,
                    'biller_tax_details': null,
                    'payee_name': null,
                    'payee_address': null,
                    'payee_contact_no': null,
                    'payee_email': null,
                    'payee_pan': null,
                    'payee_gst': null,
                    'payee_tax_details': null
                },
                headers:{
                    name: "Name",
                    'biller_name':"Biller",
                    'payee_name': "Payee",                    
                    'createdAt':"Created At",
                },
                hidden:[
                    'creatorId',
                    'updatedAt',
                    'tempalte_id'
                ],
            }
        },
        computed: {
            getEntity() {
                return this.$store.getters.getEntity;
            },
            getUser() {
                return this.$store.getters.getUser;
            },
            getTotal() {
                return Number (this.total) + Number (this.taxes.reduce((acc, t) => acc + t.val, 0));
            },            
        },
        methods: {
          normalizeInvoiceData(invoiceData) {
                const parsedInvoice = invoiceData ? { ...invoiceData } : {};
                const arrayFields = ['billables', 'tax_id'];
                const objectFields = ['terms'];

                arrayFields.forEach((field) => {
                    if (typeof parsedInvoice[field] === 'string') {
                        try {
                            parsedInvoice[field] = JSON.parse(parsedInvoice[field]);
                        }
                        catch (err) {
                            parsedInvoice[field] = [];
                        }
                    }

                    if (!Array.isArray(parsedInvoice[field])) {
                        parsedInvoice[field] = [];
                    }
                });

                objectFields.forEach((field) => {
                    if (typeof parsedInvoice[field] === 'string') {
                        try {
                            parsedInvoice[field] = JSON.parse(parsedInvoice[field]);
                        }
                        catch (err) {
                            parsedInvoice[field] = null;
                        }
                    }
                });

                if (!parsedInvoice.terms || typeof parsedInvoice.terms !== 'object' || Array.isArray(parsedInvoice.terms)) {
                    parsedInvoice.terms = { delivery: [], payment: [] };
                }

                if (!Array.isArray(parsedInvoice.terms.delivery)) {
                    parsedInvoice.terms.delivery = [];
                }

                if (!Array.isArray(parsedInvoice.terms.payment)) {
                    parsedInvoice.terms.payment = [];
                }

                return {
                    ...this.invoice,
                    ...parsedInvoice
                };
            },
          formatCurrency(value) {
                        if (isNaN(value)) {
                            return "Invalid value";
                        }

                        const currencySymbol = this.curr[this.currency].symbol || "^"; // Default to ^ if currency not found
                        
                        // Formatting the value with commas
                        const formattedValue = this.currency!='INR'? value.toLocaleString("en-US",{ maximumFractionDigits: 2, minimumFractionDigits: 2 }) : value.toLocaleString("en-IN", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
                        
                        // Combining currency symbol and formatted value
                        return `${currencySymbol}${formattedValue}`;
            },
            getDayForm(date) {
                return getDayForm(date);
            },
            convertToWords(num,curr) {
                return convertToWords(num,curr);
            },
            printInvoice() {
                window.print();
            },
            startEdit() {
                this.invoiceOriginal = JSON.parse(JSON.stringify(this.invoice));
                this.editMode = true;
            },
            cancelEdit() {
                this.invoice = JSON.parse(JSON.stringify(this.invoiceOriginal));
                this.setTotal();
                this.setTaxes();
                this.editMode = false;
            },
            async updateInvoice() {
                const payload = {
                    id: this.invoice.id,
                    invoice_no: this.invoice.invoice_no,
                    note: this.invoice.note,
                    billables: this.invoice.billables,
                    terms: this.invoice.terms,
                };
                await this.$store.getters.getAxios.post(invoiceLinks.put, payload)
                    .then(resp => {
                        if (!resp.data.isLoggedIn) {
                            this.$store.dispatch('loggedOut');
                        } else if (resp.data.success) {
                            this.invoiceOriginal = JSON.parse(JSON.stringify(this.invoice));
                            this.editMode = false;
                            this.getChangeLogs(this.invoice.id);
                        }
                        this.$store.commit('addAlert', {
                            title: resp.data.title,
                            message: resp.data.msg,
                            type: resp.data.success ? 'success' : 'danger'
                        });
                    })
                    .catch(() => {
                        this.$store.commit('addAlert', {
                            title: 'Update Error',
                            message: 'Unable to save invoice changes',
                            type: 'danger'
                        });
                    });
            },
            setTotal() {
                this.total = 0;
                for(let i=0;i<this.invoice.billables.length;i++){
                    /* console.log(this.invoice.billables[i]); */
                    this.total += Number(this.invoice.billables[i].subTotal);
                }                                
            },            
            setTaxes() {
                this.taxes = [];
                for(let i=0;i<this.invoice.tax_id.length;i++){

                    this.taxes.push(
                        {  name: this.invoice.tax_id[i].name, val: Number (this.invoice.tax_id[i].perc) * Number (this.total) / 100}
                    );
                    
               }
               console.log(this.taxes);
            },
            getCurrentDate() {
                    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                    const today = new Date();
                    const day = String(today.getDate()).padStart(2, "0");
                    const month = months[today.getMonth()];
                    const year = today.getFullYear();
                    return `${day}-${month}-${year}`;
            },
            async getInvoiceData(e) {
                this.id = e?.rowData?.id ?? e?.id ?? null;
                this.loading=true;
                if(this.id!=undefined){
                    await this.$store.getters.getAxios.post(invoiceLinks.getItem,{id:this.id})
                        .then(resp=>{
                            if(!resp.data.isLoggedIn){
                                this.$store.dispatch('loggedOut');
                            }
                            else {
                                console.log(resp.data.data);
                                this.invoice = this.normalizeInvoiceData(resp.data.data);
                                this.invoiceOriginal = JSON.parse(JSON.stringify(this.invoice));
                                this.editMode = false;
                                this.changeLogs = [];
                                this.showHistory = false;
                                this.setTotal();
                                this.setTaxes();
                                this.getChangeLogs(this.invoice.id);
                                /* this.invoice.terms==null? this.invoice.terms = {delivery:'',payment:''}: this.invoice.terms;
                                if(this.invoice.terms['delivery'] == undefined || this.invoice.terms['delivery']==null) this.invoice.terms['delivery']=[];
                                if(this.invoice.terms['payment'] == undefined || this.invoice.terms['payment']==null) this.invoice.terms['payment']=[];
                                console.log(this.invoice.terms); */
                            }
                            this.$store.commit('addAlert', {
                                title: resp.data.title,
                                message: resp.data.msg,
                                type: resp.data.success? 'info' : 'danger'
                            });
                            this.loading=false;
                        })
                        // eslint-disable-next-line
                        .catch(err=>{
                            this.$store.commit('addAlert', {
                                title: "Error Getting Invoice Data",
                                message: "Try after some time",
                                type: 'danger'
                            });
            
                        })
                }
            },
            async getChangeLogs(invoiceId) {
                if (!invoiceId) return;
                await this.$store.getters.getAxios.post(changeLogLinks.readForInvoice, { invoice_id: invoiceId })
                    .then(resp => {
                        if (resp.data.success) {
                            this.changeLogs = resp.data.data || [];
                        }
                    })
                    .catch(() => {});
            },
            async getDropDownData(table,listName,filter) {
                    this.loading=true;
                    await this.$store.getters.getAxios.post(dropDownLinks[table],{ent_id:this.$store.getters.getEntity,filter:filter})
                        .then(resp=>{
                            if(!resp.data.isLoggedIn){
                                this.$store.dispatch('loggedOut');
                            }
                            else this.ddHolder[listName] =  resp.data.data;
                            this.loading=false;
                        })
                        // eslint-disable-next-line
                        .catch(err=>{
                            this.$store.commit('addAlert', {
                                title: "Error Getting DropDown Data for "+listName,
                                message: "Try after some time",
                                type: 'danger'
                            });
        
                        })
            },
        },
        mounted() {
            this.getDropDownData('invoices','invoices',null);
            
        },
    }
</script>
<style scoped>
[type="number"] {
    /* max-width: 300px; */ /* Set the maximum width */
    /* width: 100%; */ /* Make it responsive */
    max-width: 100px !important; /* Set the maximum width */
}
.printblock{
    font-size: 3mm !important;
    width: 210mm; /* A4 width */
    /* height: 297mm; */ /* A4 height */
    /* padding: 10mm; */ /* Optional: content padding */
  }
@page {
  margin: 0;
}
@media print {
  body{
    visibility: hidden;
  }
  .navbar .navbar-expand-md .bg-dark .py-3 {
    display: none !important;
  }
  .printblock{
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    page-break-after: always; /* Force page break after each A4 block */
  }
  .noprint{
    display: none !important;
  }
}
.timeline-item:not(:last-child) > .d-flex > .timeline-dot {
    position: relative;
}
.timeline-item:not(:last-child) > .d-flex > .timeline-dot::after {
    content: '';
    position: absolute;
    left: 50%;
    top: 14px;
    transform: translateX(-50%);
    width: 2px;
    height: calc(100% + 1rem);
    background: #ccc;
}
</style>