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

class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.filter = {
            order: 'concept ASC',
            include: [{
                relation: 'item',
            }, {
                relation: 'components',
                scope: {
                    fields: ['componentFk', 'value'],
                    include: {
                        relation: 'component',
                        scope: {
                            fields: ['typeFk', 'name'],
                            include: {
                                relation: 'componentType',
                                scope: {
                                    fields: ['type', 'isBase']
                                }
                            }
                        }
                    }
                }
            }]
        };
    }
    get ticket() {
        return this._ticket;
    }

    set ticket(value) {
        this._ticket = value;

        if (!value) return;
        this.getTheoricalCost();
        this.getComponentsSum();
        if (this.ticket.zone && this.ticket.zone.isVolumetric)
            this.getTicketVolume();
    }

    base() {
        let sales = this.$.model.data;
        let sum = 0;
        if (!sales) return;

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

    getTotal() {
        const sales = this.$.model.data;
        let total = 0;
        if (!sales) return;
        for (let sale of sales) {
            for (let saleComponent of sale.components)
                total += sale.quantity * saleComponent.value;
        }
        return total;
    }

    getTheoricalCost() {
        this.$http.get(`Tickets/${this.ticket.id}/freightCost`)
            .then(res => this.theoricalCost = res.data);
    }

    getComponentsSum() {
        this.$http.get(`Tickets/${this.ticket.id}/getComponentsSum`)
            .then(res => this.componentsList = res.data);
    }

    getTicketVolume() {
        if (!this.ticket) return;

        this.$http.get(`Tickets/${this.ticket.id}/getVolume`)
            .then(res => {
                if (res.data.length)
                    this.ticketVolume = res.data[0].volume;
            });
    }
}

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