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

class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        this.include = {
            relation: 'bankEntity',
            scope: {
                fields: ['countryFk', 'id', 'name', 'bic']
            }
        };
        const filter = {
            where: {code: 'wireTransfer'}
        };

        this.$http.get(`payMethods/findOne`, {filter})
            .then(res => {
                this.wireTransferFk = res.data.id;
            });
    }

    add() {
        this.$.model.insert({
            supplierFk: this.$params.id
        });
    }

    onAccept(data) {
        const accounts = this.supplierAccounts;
        const targetAccount = accounts[data.index];
        targetAccount.bankEntityFk = data.id;
    }

    onSubmit() {
        this.$.watcher.check();
        return this.$.model.save()
            .then(() => {
                this.$.watcher.notifySaved();
                this.$.watcher.updateOriginalData();
                return this.card.reload();
            })
            .then(() => {
                if (this.supplier.payMethodFk != this.wireTransferFk)
                    this.$.payMethodToTransfer.show();
            });
    }

    setWireTransfer() {
        const params = {
            id: this.$params.id,
            payMethodFk: this.wireTransferFk
        };
        const query = `Suppliers/${this.$params.id}`;
        return this.$http.patch(query, params)
            .then(() => this.$.watcher.notifySaved());
    }
}

ngModule.vnComponent('vnSupplierAccount', {
    template: require('./index.html'),
    controller: Controller,
    require: {
        card: '^vnSupplierCard'
    }
});