import ngModule from '../module';
import Section from 'salix/components/section';
import './style.scss';

class Controller extends Section {
    constructor($element, $, vnReport, vnEmail) {
        super($element, $);
        this.vnReport = vnReport;
        this.vnEmail = vnEmail;
    }

    get invoiceOut() {
        return this._invoiceOut;
    }

    set invoiceOut(value) {
        this._invoiceOut = value;
        if (value)
            this.id = value.id;
    }

    get hasInvoicing() {
        return this.aclService.hasAny(['invoicing']);
    }

    loadData() {
        const filter = {
            include: [
                {
                    relation: 'company',
                    scope: {
                        fields: ['id', 'code']
                    }
                }, {
                    relation: 'client',
                    scope: {
                        fields: ['id', 'name', 'email']
                    }
                }
            ]
        };
        return this.$http.get(`InvoiceOuts/${this.invoiceOut.id}`, {filter})
            .then(res => this.invoiceOut = res.data);
    }
    reload() {
        return this.loadData().then(() => {
            if (this.parentReload)
                this.parentReload();
        });
    }

    cardReload() {
        // Prevents error when not defined
    }

    deleteInvoiceOut() {
        return this.$http.post(`InvoiceOuts/${this.invoiceOut.id}/delete`)
            .then(() => {
                const isInsideInvoiceOut = this.$state.current.name.startsWith('invoiceOut');
                if (isInsideInvoiceOut)
                    this.$state.go('invoiceOut.index');
                else
                    this.$state.reload();
            })
            .then(() => this.vnApp.showSuccess(this.$t('InvoiceOut deleted')));
    }

    bookInvoiceOut() {
        return this.$http.post(`InvoiceOuts/${this.invoiceOut.ref}/book`)
            .then(() => this.$state.reload())
            .then(() => this.vnApp.showSuccess(this.$t('InvoiceOut booked')));
    }

    createPdfInvoice() {
        return this.$http.post(`InvoiceOuts/${this.id}/createPdf`)
            .then(() => this.reload())
            .then(() => {
                const snackbarMessage = this.$t(
                    `The invoice PDF document has been regenerated`);
                this.vnApp.showSuccess(snackbarMessage);
            });
    }

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

        return this.vnEmail.send(`InvoiceOuts/${this.invoiceOut.ref}/invoice-email`, {
            recipientId: this.invoiceOut.client.id,
            recipient: $data.email
        });
    }

    showCsvInvoice() {
        this.vnReport.show(`InvoiceOuts/${this.invoiceOut.ref}/invoice-csv`, {
            recipientId: this.invoiceOut.client.id
        });
    }

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

        return this.vnEmail.send(`InvoiceOuts/${this.invoiceOut.ref}/invoice-csv-email`, {
            recipientId: this.invoiceOut.client.id,
            recipient: $data.email
        });
    }

    showExportationLetter() {
        this.vnReport.show(`InvoiceOuts/${this.invoiceOut.ref}/exportation-pdf`, {
            recipientId: this.invoiceOut.client.id,
            refFk: this.invoiceOut.ref
        });
    }

    refundInvoiceOut(withWarehouse) {
        const query = 'InvoiceOuts/refund';
        const params = {ref: this.invoiceOut.ref, withWarehouse: withWarehouse};
        this.$http.post(query, params).then(res => {
            const tickets = res.data;
            const refundTickets = tickets.map(ticket => ticket.id);

            this.vnApp.showSuccess(this.$t('The following refund tickets have been created', {
                ticketId: refundTickets.join(',')
            }));
            if (refundTickets.length == 1)
                this.$state.go('ticket.card.sale', {id: refundTickets[0]});
        });
    }

    transferInvoice() {
        const params = {
            id: this.invoiceOut.id,
            refFk: this.invoiceOut.ref,
            newClientFk: this.clientId,
            cplusRectificationTypeFk: this.cplusRectificationType,
            siiTypeInvoiceOutFk: this.siiTypeInvoiceOut,
            invoiceCorrectionTypeFk: this.invoiceCorrectionType
        };
        this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => {
            const invoiceId = res.data;
            this.vnApp.showSuccess(this.$t('Transferred invoice'));
            this.$state.go('invoiceOut.card.summary', {id: invoiceId});
        });
    }
}

Controller.$inject = ['$element', '$scope', 'vnReport', 'vnEmail'];

ngModule.vnComponent('vnInvoiceOutDescriptorMenu', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        invoiceOut: '<',
        parentReload: '&'
    }
});