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

class Controller {
    constructor($scope, $stateParams) {
        this.$stateParams = $stateParams;
        this.$scope = $scope;
        this.filter = {
            order: 'concept ASC',
            include: [{
                relation: 'item',
            },
            {
                relation: 'components',
                scope: {
                    fields: ['componentFk', 'value'],
                    include: {
                        relation: 'componentRate',
                        scope: {
                            fields: ['componentTypeRate', 'name'],
                            include: {
                                relation: 'componentType',
                                scope: {
                                    fields: ['type', 'isBase']
                                }
                            }
                        }
                    }
                }
            }]
        };
    }

    base() {
        let sales = this.$scope.model.data;
        let sum = 0;

        if (!sales) return;

        for (let sale of sales) {
            for (let component of sale.components) {
                if (component.componentRate.componentType.isBase)
                    sum += sale.quantity * component.value;
            }
        }

        return sum;
    }

    showDescriptor(event, itemFk) {
        this.quicklinks = {
            btnThree: {
                icon: 'icon-transaction',
                state: `item.card.diary({
                    id: ${itemFk}, 
                    warehouseFk: ${this.ticket.warehouseFk},
                    ticketFk: ${this.ticket.id}
                })`,
                tooltip: 'Item diary'
            }
        };
        this.$scope.descriptor.itemFk = itemFk;
        this.$scope.descriptor.parent = event.target;
        this.$scope.descriptor.show();
    }

    onDescriptorLoad() {
        this.$scope.popover.relocate();
    }
}

Controller.$inject = ['$scope', '$stateParams'];

ngModule.component('vnTicketComponents', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        ticket: '<'
    }
});