const vnReport = require('../../../core/mixins/vn-report.js');

module.exports = {
    name: 'invoiceIn',
    mixins: [vnReport],
    async serverPrefetch() {
        this.invoice = await this.findOneFromDef('invoice', [this.id]);
        this.checkMainEntity(this.invoice);
        this.taxes = await this.fetchTaxes(this.id);

        let defaultTax = await this.findOneFromDef('defaultTax');

        if (defaultTax) {
            defaultTax = Object.assign(defaultTax, {
                taxableBase: 0,
                vat: (this.taxTotal() * defaultTax.rate / 100)
            });
            this.taxes.push(defaultTax);
        }

        const entries = await this.rawSqlFromDef('entry', [this.id]);
        const buys = await this.rawSqlFromDef('buy', [this.id]);

        const map = new Map();

        for (let entry of entries) {
            entry.buys = [];

            map.set(entry.id, entry);
        }

        for (let buy of buys) {
            const entry = map.get(buy.entryFk);

            if (entry) entry.buys.push(buy);
        }

        this.entries = entries;
    },
    methods: {
        async fetchTaxes(id) {
            const taxes = await this.rawSqlFromDef(`taxes`, [id]);
            return this.taxVat(taxes);
        },
        buyImport(buy) {
            return buy.quantity * buy.buyingValue;
        },
        entrySubtotal(entry) {
            let subTotal = 0.00;
            for (let buy of entry.buys)
                subTotal += this.buyImport(buy);

            return subTotal;
        },
        sumTotal(rows, prop) {
            let total = 0.00;
            for (let row of rows)
                total += parseFloat(row[prop]);

            return total;
        },
        taxVat(taxes) {
            for (tax of taxes) {
                let vat = 0;
                if (tax.rate && tax.taxableBase)
                    vat = (tax.rate / 100) * tax.taxableBase;

                tax.vat = vat;
            }

            return taxes;
        },
        taxTotal() {
            const base = this.sumTotal(this.taxes, 'taxableBase');
            const vat = this.sumTotal(this.taxes, 'vat');

            return base + vat;
        }
    },
    props: {
        id: {
            type: Number,
            description: 'The invoice id'
        }
    }
};