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

class Controller extends Section {
    $onInit() {
        this.getRows();
    }

    set order(value) {
        this._order = value;
        this.getVAT();
    }

    get order() {
        return this._order;
    }

    get subtotal() {
        return this.order ? this.order.total - this.VAT : 0;
    }

    getRows() {
        let filter = {
            where: {orderFk: this.$params.id},
            include: [
                {relation: 'item'},
                {relation: 'warehouse'}
            ]
        };
        this.$http.get(`OrderRows`, {filter})
            .then(res => this.rows = res.data);
    }

    getVAT() {
        this.$http.get(`Orders/${this.$params.id}/getVAT`)
            .then(res => this.VAT = res.data);
    }

    deleteRow(index) {
        let [row] = this.rows.splice(index, 1);
        let params = {
            rows: [row.id],
            actualOrderId: this.$params.id
        };
        return this.$http.post(`OrderRows/removes`, params)
            .then(() => this.card.reload())
            .then(() => this.vnApp.showSuccess(this.$t('Data saved!')));
    }

    save() {
        this.$http.post(`Orders/${this.$params.id}/confirm`).then(() => {
            this.vnApp.showSuccess(this.$t('Order confirmed'));
            this.$state.go(`ticket.index`, {
                q: JSON.stringify({clientFk: this.order.clientFk})
            });
        });
    }
}

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