import ngModule from '../module';

class Controller {
    constructor($http, $state) {
        this.$http = $http;
        this.$state = $state;
        this.order = {};
        this.filter = {
            include: [
                {
                    relation: 'agencyMode', scope: {
                        fields: ['name']
                    }
                },
                {
                    relation: 'address', scope: {
                        fields: ['nickname']
                    }
                },
                {
                    relation: 'rows', scope: {
                        fields: ['id']
                    }
                },
                {
                    relation: 'client',
                    scope: {
                        fields: ['salesPersonFk', 'name', 'isActive', 'isFreezed', 'isTaxDataChecked'],
                        include: {
                            relation: 'salesPerson',
                            scope: {
                                fields: ['userFk'],
                                include: {
                                    relation: 'user',
                                    scope: {
                                        fields: ['nickname']
                                    }
                                }
                            }
                        }
                    }
                }
            ]
        };
    }

    $onInit() {
        this.getCard();
    }

    getCard() {
        let json = encodeURIComponent(JSON.stringify(this.filter));
        let query = `/order/api/Orders/${this.$state.params.id}?filter=${json}`;
        this.$http.get(query).then(res => {
            if (res.data && res.data.rows) {
                if (res.data.rows.length == 0)
                    delete res.data.rows;
                this.order = res.data;
                this.getTotal();
            }
        });
    }

    reload() {
        this.getCard();
    }

    getTotal() {
        let query = `/order/api/Orders/${this.$state.params.id}/getTotal`;
        this.$http.get(query).then(res => {
            if (res.data)
                this.order.total = res.data;
        });
    }
}

Controller.$inject = ['$http', '$state'];

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