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

class Controller extends Section {
    constructor($element, $scope) {
        super($element, $scope);
        this.landed = Date.vnNew();
        this.newRoute = null;
        this.smartTableOptions = {
            activeButtons: {
                search: true,
                shownColumns: true,
            },
            columns: [
                {
                    field: 'packageItemName',
                    autocomplete: {
                        url: 'Items',
                        valueField: 'id',
                    }
                }
            ]
        };
    }

    exprBuilder(param, value) {
        switch (param) {
        case 'expeditionFk':
            return {'id': value};
        case 'packageItemName':
            return {'packagingItemFk': value};
        }
    }

    get checked() {
        const rows = this.$.model.data || [];
        const checkedRows = [];
        for (let row of rows) {
            if (row.checked)
                checkedRows.push(row.id);
        }

        return checkedRows;
    }

    get totalChecked() {
        return this.checked.length;
    }

    onDialogAccept(id) {
        return this.$http.delete(`Expeditions/${id}`)
            .then(() => this.$.model.refresh());
    }

    showLog(expedition) {
        this.expedition = expedition;
        this.$.statusLog.show();
    }

    onRemove() {
        const params = {expeditionIds: this.checked};
        const query = `Expeditions/deleteExpeditions`;
        this.$http.post(query, params)
            .then(() => {
                this.vnApp.showSuccess(this.$t('Expedition removed'));
                this.$.model.refresh();
            });
    }

    createTicket(landed, routeFk) {
        const params = {
            clientId: this.ticket.clientFk,
            landed: landed,
            warehouseId: this.ticket.warehouseFk,
            addressId: this.ticket.addressFk,
            agencyModeId: this.ticket.agencyModeFk,
            routeId: routeFk,
            expeditionIds: this.checked
        };
        const query = `Expeditions/moveExpeditions`;
        this.$http.post(query, params).then(res => {
            this.vnApp.showSuccess(this.$t('Data saved!'));
            this.$state.go('ticket.card.summary', {id: res.data.id});
        });
    }
}

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