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

class Controller extends Section {
    constructor($element, $) {
        super($element, $);
    }

    get travelId() {
        return this._travelId;
    }

    set travelId(value) {
        this._travelId = value;

        if (value) this.loadData();
    }

    loadData() {
        const filter = {
            fields: [
                'id',
                'ref',
                'shipped',
                'landed',
                'totalEntries',
                'agencyModeFk',
                'warehouseInFk',
                'warehouseOutFk',
                'cargoSupplierFk'
            ],
            include: [
                {
                    relation: 'warehouseIn',
                    scope: {
                        fields: ['name']
                    }
                }, {
                    relation: 'warehouseOut',
                    scope: {
                        fields: ['name']
                    }
                }
            ]
        };
        this.$http.get(`Travels/${this.travelId}`, {filter})
            .then(res => this.travel = res.data);

        this.$http.get(`Travels/${this.travelId}/getEntries`)
            .then(res => this.entries = res.data);
    }

    get isBuyer() {
        return this.aclService.hasAny(['buyer']);
    }

    onDeleteAccept() {
        this.$http.delete(`Travels/${this.travelId}`)
            .then(() => this.$state.go('travel.index'))
            .then(() => this.vnApp.showSuccess(this.$t('Travel deleted')));
    }

    onCloneAccept() {
        const params = JSON.stringify({
            ref: this.travel.ref,
            agencyModeFk: this.travel.agencyModeFk,
            shipped: this.travel.shipped,
            landed: this.travel.landed,
            warehouseInFk: this.travel.warehouseInFk,
            warehouseOutFk: this.travel.warehouseOutFk
        });
        this.$state.go('travel.create', {q: params});
    }

    onCloneWithEntriesAccept() {
        this.$http.post(`Travels/${this.travelId}/cloneWithEntries`)
            .then(res => this.$state.go('travel.card.basicData', {id: res.data}));
    }
}

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

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