import ngModule from '../module';
import Descriptor from 'salix/components/descriptor';

class Controller extends Descriptor {
    get invoiceIn() {
        return this.entity;
    }

    set invoiceIn(value) {
        this.entity = value;
    }

    get entryFilter() {
        if (this.invoiceIn)
            return JSON.stringify({invoiceInFk: this.invoiceIn.id});

        return null;
    }

    get invoiceInFilter() {
        if (this.invoiceIn)
            return JSON.stringify({supplierFk: this.invoiceIn.supplierFk});

        return null;
    }

    deleteInvoiceIn() {
        return this.$http.delete(`InvoiceIns/${this.id}`)
            .then(() => this.$state.go('invoiceIn.index'))
            .then(() => this.vnApp.showSuccess(this.$t('InvoiceIn deleted')));
    }

    cloneInvoiceIn() {
        return this.$http.post(`InvoiceIns/${this.id}/clone`)
            .then(res => this.$state.go('invoiceIn.card.summary', {id: res.data.id}))
            .then(() => this.vnApp.showSuccess(this.$t('InvoiceIn cloned')));
    }

    loadData() {
        const filter = {
            include: [
                {relation: 'supplier'},
                {relation: 'invoiceInDueDay'},
                {relation: 'company',
                    scope: {
                        fields: ['id', 'code']
                    }
                }

            ]
        };

        return this.getData(`InvoiceIns/${this.id}`, {filter})
            .then(res => {
                this.entity = res.data;
                this.invoiceIn.amount = res.data.invoiceInDueDay.reduce(
                    (accumulator, currentValue) => {
                        return accumulator + (currentValue['amount'] || 0);
                    }, 0);
            });
    }

    checkToBook() {
        let message = '';
        const id = this.invoiceIn.id;
        this.$q.all([
            this.$http.get(`InvoiceIns/${this.id}/getTotals`)
                .then(res => {
                    const taxableBaseNotEqualDueDay = res.data.totalDueDay != res.data.totalTaxableBase;
                    const vatNotEqualDueDay = res.data.totalDueDay != res.data.totalVat;
                    if (taxableBaseNotEqualDueDay && vatNotEqualDueDay)
                        message += 'amountsDoNotMatch';
                }),
            this.$http.get('InvoiceInDueDays/count', {
                filter: {
                    where: {
                        invoiceInFk: id,
                        dueDated: {gte: Date.vnNew()}
                    }
                }})
                .then(res => {
                    if (res.data)
                        message += 'future payments';
                })

        ]).finally(() => {
            if (message.length)
                this.$.confirmToBookAnyway.show();
            else
                this.onAcceptToBook();
        });
    }

    onAcceptToBook() {
        this.$http.post(`InvoiceIns/${this.id}/toBook`)
            .then(() => this.$state.reload())
            .then(() => this.vnApp.showSuccess(this.$t('InvoiceIn booked')));
    }

    showPdfInvoice() {
        this.vnReport.show(`InvoiceIns/${this.id}/invoice-in-pdf`);
    }

    sendPdfInvoice($data) {
        if (!$data.email)
            return this.vnApp.showError(this.$t(`The email can't be empty`));

        return this.vnEmail.send(`InvoiceIns/${this.entity.id}/invoice-in-email`, {
            recipient: $data.email,
            recipientId: this.entity.supplier.id
        });
    }

    isAgricultural() {
        return this.invoiceIn.supplier.sageWithholdingFk == this.config[0].sageFarmerWithholdingFk;
    }
}

ngModule.vnComponent('vnInvoiceInDescriptor', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        invoiceIn: '<'
    }
});