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

class Controller extends Summary {
    get ticket() {
        return this._ticket;
    }

    set ticket(value) {
        this._ticket = value;

        if (value) this.loadData();
    }

    get formattedAddress() {
        if (!this.summary) return '';

        const address = this.summary.address;
        const postcode = address.postalCode;
        const province = address.province ? `(${address.province.name})` : '';

        return `${address.street} - ${postcode} - ${address.city} ${province}`;
    }

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

    reload() {
        this.loadData()
            .then(() => {
                if (this.card)
                    this.card.reload();
                // Refresh index model
                if (this.model)
                    this.model.refresh();
            });
    }

    get isOnTicketCard() {
        const currentState = this.$state.current.name;
        return currentState.startsWith('ticket.card');
    }

    get isEditable() {
        try {
            return !this.ticket.ticketState.state.alertLevel;
        } catch (e) {}

        return true;
    }

    showInvoiceOutDescriptor(event, refFk) {
        if (!refFk) return;
        this.$.invoiceOutDescriptor.show(event.target, this.summary.invoiceOut.id);
    }

    state(value) {
        const params = {
            ticketFk: 'id' in this.ticket ? this.ticket.id : this.$params.id,
            code: value
        };
        this.$http.post(`Tickets/state`, params)
            .then(() => {
                if ('id' in this.$params) this.reload();
            })
            .then(() => {
                this.vnApp.showSuccess(this.$t('Data saved!'));
            });
    }

    getRequestState(state) {
        switch (state) {
        case null:
            return 'New';
        case false:
            return 'Denied';
        case true:
            return 'Acepted';
        }
    }

    async goToLilium(section, id) {
        window.location.href = await this.vnApp.getUrl(`claim/${id}/${section}`);
    }
}

ngModule.vnComponent('vnTicketSummary', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        ticket: '<',
        model: '<?'
    },
    require: {
        card: '?^vnTicketCard'
    }
});