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

class Controller extends Section {
    $onChanges() {
        if (this.$params && this.$params.q)
            this.travel = JSON.parse(this.$params.q);
    }

    onShippedChange(value) {
        let hasFilledProperties;
        let hasAgencyMode;
        if (this.travel) {
            hasAgencyMode = Boolean(this.travel.agencyModeFk);
            hasFilledProperties = this.travel.landed || this.travel.warehouseInFk || this.travel.warehouseOutFk;
        }
        if (!hasAgencyMode || hasFilledProperties)
            return;

        const query = `travels/getAverageDays`;
        const params = {
            agencyModeFk: this.travel.agencyModeFk
        };
        this.$http.get(query, {params}).then(res => {
            if (!res.data)
                return;

            const landed = new Date(value);
            const futureDate = landed.getDate() + res.data.dayDuration;
            landed.setDate(futureDate);

            this.travel.landed = landed;
            this.travel.warehouseInFk = res.data.warehouseInFk;
            this.travel.warehouseOutFk = res.data.warehouseOutFk;
        });
    }

    onSubmit() {
        return this.$.watcher.submit().then(
            res => this.$state.go('travel.card.basicData', {id: res.data.id})
        );
    }
}

ngModule.vnComponent('vnTravelCreate', {
    template: require('./index.html'),
    controller: Controller
});