import ngModule from '../module';
import './style.scss';

class Controller {
    constructor($scope, $http, $timeout, $element, $translate, vnApp) {
        this.$ = $scope;
        this.$timeout = $timeout;
        this.$http = $http;
        this.$element = $element;
        this.$translate = $translate;
        this.vnApp = vnApp;
        this.totalBasquet = 0;
    }
    set prices(value) {
        this._prices = value;
        if (value && value[0].grouping)
            this.calculateTotal();
    }
    get prices() {
        return this._prices;
    }
    getTags() {
        let filter = {
            where: {itemFk: this.item.id,
                priority: {gte: 4}},
            order: 'priority ASC',
            include: {relation: 'tag'}
        };
        this.quicklinks = {
            btnOne: {
                icon: 'icon-transaction',
                state: `item.card.diary({id: ${this.item.id}})`,
                tooltip: 'Diary'
            }
        };
        this.$http.get(`/item/api/ItemTags?filter=${JSON.stringify(filter)}`).then(response => {
            this.tags = response.data;
            this.$.$applyAsync(() => {
                this.$.popover.relocate();
            });
        });
    }
    show(event, item) {
        this.item = JSON.parse(JSON.stringify(item));
        this.prices = this.item.prices;
        this.getTags();
        this.$.popover.parent = event.target;
        this.$.popover.show();
        this.$.popover.relocate();
    }
    clear() {
        this.item = {};
        this.tags = {};
        this._prices = {};
        this.total = 0;
    }
    calculateMax() {
        this.max = this.item.available - this.total;
    }
    calculateTotal() {
        this.total = 0;

        this.prices.forEach(price => {
            if (!price.quantity) price.quantity = 0;
            this.total += price.quantity;
        });
        this.calculateMax();
    }

    addQuantity(price) {
        if (this.total + price.grouping <= this.max)
            price.quantity += price.grouping;

        this.validate();
    }
    validate() {
        this.$timeout(() => {
            this.calculateTotal();
            let inputs = this.$element[0].querySelectorAll('vn-input-number[name="quantity"] div.infix:not(.validated)');

            inputs.forEach(input => {
                if (this.total > this.item.available)
                    input.classList.add('invalid');
                else
                    input.classList.remove('invalid');
            });
            let wrongInputs = this.$element[0].querySelectorAll('vn-input-number[name="quantity"] div.infix.invalid');

            if (wrongInputs.length > 0)
                this.$element[0].querySelector('vn-vertical.prices').classList.add('invalid');
            else
                this.$element[0].querySelector('vn-vertical.prices').classList.remove('invalid');
        });
    }
    getFilledLines() {
        let filledLines = [];
        let match;
        this.prices.forEach(price => {
            if (price.quantity && price.quantity > 0) {
                match = filledLines.find(element => {
                    return element.warehouseFk == price.warehouseFk;
                });

                if (!match) {
                    filledLines.push(Object.assign({}, price));
                    return;
                }
                match.quantity += price.quantity;
            }
        });
        return filledLines;
    }
    submit() {
        this.calculateTotal();
        let filledLines = this.getFilledLines();

        if (filledLines.length <= 0) {
            this.vnApp.showError('First you must add some quantity');
            return;
        }

        setTimeout(() => {
            let params = {
                orderFk: this.order.id,
                items: filledLines
            };

            this.$http.post(`/order/api/OrderRows/addToOrder`, params).then(res => {
                this.vnApp.showSuccess(this.$translate.instant('Data saved!'));
                this.$.popover.hide();
                this.card.reload();
            });
        });
    }
}

Controller.$inject = ['$scope', '$http', '$timeout', '$element', '$translate', 'vnApp'];

ngModule.component('vnOrderPricesPopover', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        order: '<'
    },
    require: {
        card: '^vnOrderCard'
    }
});