import ngModule from '../module';
import Summary from 'salix/components/summary';
import './style.scss';

class Controller extends Summary {
    constructor($element, $, vnFile) {
        super($element, $);
        this.vnFile = vnFile;
        this.filter = {
            include: [
                {
                    relation: 'dms'
                }
            ]
        };
    }

    $onChanges() {
        if (this.claim && this.claim.id)
            this.loadData();
    }

    loadData() {
        return this.$http.get(`Claims/${this.claim.id}/getSummary`).then(res => {
            if (res && res.data)
                this.summary = res.data;
        });
    }

    reload() {
        this.loadData()
            .then(() => {
                if (this.card)
                    this.card.reload();

                if (this.parentReload)
                    this.parentReload();
            });
    }

    get isSalesPerson() {
        return this.aclService.hasAny(['salesPerson']);
    }

    get isClaimManager() {
        return this.aclService.hasAny(['claimManager']);
    }

    get claim() {
        return this._claim;
    }

    set claim(value) {
        this._claim = value;

        // Get DMS on summary load
        if (value) {
            this.$.$applyAsync(() => this.loadDms());
            this.loadData();
        }
    }

    loadDms() {
        this.$.model.where = {
            claimFk: this.claim.id
        };
        this.$.model.refresh();
    }

    getImagePath(dmsId) {
        return this.vnFile.getPath(`/api/dms/${dmsId}/downloadFile`);
    }

    changeState(value) {
        const params = {
            id: this.claim.id,
            claimStateFk: value
        };

        this.$http.patch(`Claims/updateClaim/${this.claim.id}`, params)
            .then(() => {
                this.reload();
            })
            .then(() => {
                this.vnApp.showSuccess(this.$t('Data saved!'));
            });
    }
}

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

ngModule.vnComponent('vnClaimSummary', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        claim: '<',
        model: '<?',
        parentReload: '&'
    },
    require: {
        card: '?^vnClaimCard'
    }
});