import ngModule from '../../module';
import Dialog from 'core/components/dialog';

class Controller extends Dialog {
    constructor($element, $, $transclude, vnReport) {
        super($element, $, $transclude);

        this.vnReport = vnReport;
        this.receipt = {
            payed: new Date()
        };
    }

    set payed(value) {
        this.receipt.payed = value;
    }

    set amountPaid(value) {
        this.receipt.amountPaid = value;
        this.amountToReturn = this.deliveredAmount - value;
    }

    get amountPaid() {
        return this.receipt.amountPaid;
    }

    set clientFk(value) {
        this.receipt.clientFk = value;
    }

    get clientFk() {
        return this.receipt.clientFk;
    }

    get companyFk() {
        if (!this.receipt.companyFk)
            this.receipt.companyFk = this.vnConfig.companyFk;
        return this.receipt.companyFk;
    }

    set companyFk(value) {
        this.receipt.companyFk = value;
        this.getAmountPaid();
    }

    set description(value) {
        this.receipt.description = value;
        this.originalDescription = value;
    }

    get description() {
        return this.receipt.description;
    }

    get bankSelection() {
        return this._bankSelection;
    }

    set bankSelection(value) {
        this._bankSelection = value;

        if (value) {
            const accountingType = value.accountingType;
            if (this.originalDescription) {
                this.receipt.description =
                `${accountingType && accountingType.receiptDescription}, ${this.originalDescription}`;
            } else {
                this.receipt.description =
                `${accountingType && accountingType.receiptDescription}`;
            }
            this.maxAmount = accountingType && accountingType.maxAmount;
        }
    }

    set deliveredAmount(value) {
        this._deliveredAmount = value;
        this.amountToReturn = value - this.receipt.amountPaid;
    }

    get amountToReturn() {
        return this._amountToReturn;
    }

    set amountToReturn(value) {
        if (isNaN(value)) return;

        value = value.toFixed(2);

        if (Number.isInteger(value))
            value = parseInt(value);
        else value = parseFloat(value);

        this._amountToReturn = value;
    }

    get deliveredAmount() {
        return this._deliveredAmount;
    }

    get bankFk() {
        if (!this.receipt.bankFk)
            this.receipt.bankFk = this.vnConfig.bankFk;

        return this.receipt.bankFk;
    }

    set bankFk(value) {
        this.receipt.bankFk = value;
    }

    accountShortToStandard(value) {
        this.receipt.compensationAccount = value.replace('.', '0'.repeat(11 - value.length));
    }

    getAmountPaid() {
        const filter = {
            where: {
                clientFk: this.$params.id,
                companyFk: this.receipt.companyFk
            }
        };

        this.$http.get(`ClientRisks`, {filter}).then(res => {
            this.receipt.amountPaid = (res.data.length && res.data[0].amount) || null;
        });
    }

    responseHandler(response) {
        if (response !== 'accept')
            return super.responseHandler(response);

        const exceededAmount = this.receipt.amountPaid > this.maxAmount;

        if (this.bankSelection.accountingType.code == 'cash' && exceededAmount)
            return this.vnApp.showError(this.$t('Amount exceeded', {maxAmount: this.maxAmount}));

        let receiptId;
        return this.$http.post(`Clients/${this.clientFk}/createReceipt`, this.receipt)
            .then(res => {
                receiptId = res.data.id;
                super.responseHandler(response);
            })
            .then(() => this.vnApp.showSuccess(this.$t('Data saved!')))
            .then(() => {
                if (this.viewReceipt) {
                    this.vnReport.show('receipt', {
                        receiptId: receiptId,
                        companyId: this.companyFk
                    });
                }
            });
    }

    bankSearchFunc($search) {
        return /^\d+$/.test($search)
            ? {id: $search}
            : {bank: {like: '%' + $search + '%'}};
    }
}

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

ngModule.vnComponent('vnClientBalanceCreate', {
    slotTemplate: require('./index.html'),
    controller: Controller,
    bindings: {
        payed: '<?',
        bankFk: '<?',
        amountPaid: '<?',
        companyFk: '<?',
        description: '<?',
        clientFk: '<?'
    }
});