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

export default class Controller extends Section {
    onSubmit() {
        const orgData = this.$.watcher.orgData;
        delete this.client.despiteOfClient;

        const hasContactData = this.client.email || this.client.phone || this.client.mobile;
        const hasChangedTaxData = !orgData.isTaxDataChecked && this.client.isTaxDataChecked;

        const shouldInvoice = this.client.isActive && !this.client.hasToInvoice;
        const clientActivation = this.client.isActive && (orgData.isActive != this.client.isActive);
        if (shouldInvoice && clientActivation) {
            this.client.hasToInvoice = true;
            this.vnApp.showMessage(this.$t('Client invoices enabled'));
        }

        if (hasChangedTaxData && hasContactData)
            this.checkExistingClient();
        else this.save();
    }

    checkExistingClient() {
        const findParams = [];
        if (this.client.email)
            findParams.push({email: this.client.email});

        if (this.client.phone)
            findParams.push({phone: this.client.phone});

        if (this.client.mobile)
            findParams.push({mobile: this.client.mobile});

        const filterObj = {
            where: {
                and: [
                    {or: findParams},
                    {id: {neq: this.client.id}}
                ]
            }
        };

        const $t = this.$translate.instant;
        const filter = encodeURIComponent(JSON.stringify(filterObj));
        const query = `Clients/findOne?filter=${filter}`;
        this.$http.get(query).then(res => {
            const params = {clientId: res.data.id};
            const question = $t('Found a client with this phone or email', params, null, null, 'sanitizeParameters');

            this.client.despiteOfClient = params.clientId;
            this.$.confirmDuplicatedClient.question = question;
            this.$.confirmDuplicatedClient.show();
        }).catch(error => {
            if (error.status == 404)
                return this.save();
            throw error;
        });
    }

    checkEtChanges(orgData) {
        const equalizatedHasChanged = orgData.isEqualizated != this.client.isEqualizated;
        const hasToInvoiceByAddress = orgData.hasToInvoiceByAddress || this.client.hasToInvoiceByAddress;

        if (equalizatedHasChanged && hasToInvoiceByAddress)
            this.$.propagateIsEqualizated.show();
        else if (equalizatedHasChanged)
            return this.onAcceptEt();

        return this.$q.resolve();
    }

    onAcceptEt() {
        const query = `Clients/${this.client.id}/addressesPropagateRe`;
        return this.$http.patch(query, {isEqualizated: this.client.isEqualizated}).then(
            () => this.vnApp.showMessage(this.$t('Equivalent tax spreaded'))
        );
    }

    onAcceptDuplication() {
        this.save();

        return true;
    }

    save() {
        const orgData = this.$.watcher.orgData;
        const clonedOrgData = JSON.parse(JSON.stringify(orgData));
        return this.$.watcher.submit().then(
            () => this.checkEtChanges(clonedOrgData));
    }

    onChangeEqualizated(value) {
        const orgData = this.$.watcher.orgData;
        if (value === true)
            this.client.hasToInvoiceByAddress = false;
        else if (orgData.hasToInvoiceByAddress)
            this.client.hasToInvoiceByAddress = true;

        this.$.$apply();
    }

    get province() {
        return this._province;
    }

    // Province auto complete
    set province(selection) {
        const oldValue = this._province;
        this._province = selection;

        if (!selection || !oldValue) return;

        const country = selection.country;

        if (!this.client.countryFk)
            this.client.countryFk = country.id;
    }

    get town() {
        return this._town;
    }

    // Town auto complete
    set town(selection) {
        const oldValue = this._town;
        this._town = selection;

        if (!selection || !oldValue) return;

        const province = selection.province;
        const country = province.country;
        const postcodes = selection.postcodes;

        if (!this.client.provinceFk)
            this.client.provinceFk = province.id;

        if (!this.client.countryFk)
            this.client.countryFk = country.id;

        if (!this.client.postcode && postcodes.length === 1)
            this.client.postcode = postcodes[0].code;
    }

    get postcode() {
        return this._postcode;
    }

    // Postcode auto complete
    set postcode(selection) {
        const oldValue = this._postcode;
        this._postcode = selection;

        if (!selection || !oldValue) return;

        const town = selection.town;
        const province = town.province;
        const country = province.country;

        if (!this.client.city)
            this.client.city = town.name;

        if (!this.client.provinceFk)
            this.client.provinceFk = province.id;

        if (!this.client.countryFk)
            this.client.countryFk = country.id;
    }

    onResponse(response) {
        this.client.postcode = response.code;
        this.client.city = response.city;
        this.client.provinceFk = response.provinceFk;
        this.client.countryFk = response.countryFk;
    }
}

ngModule.vnComponent('vnClientFiscalData', {
    template: require('./index.html'),
    controller: Controller,
    require: {card: '^vnClientCard'},
    bindings: {
        client: '<'
    }
});