(function() {
    openerp.widgetInstancePayslipPaymentsIPSC = null;
    openerp.parentInstancePayslipPaymentsIPSC = null;
    var Qweb = openerp.web.qweb;
    var instance = openerp;
    openerp.PayslipPaymentsIPSC = instance.Widget.extend({
        template: 'eiru_payslip_payments.IPSC',
        id: undefined,
        payslipIpsc: [],
        init: function(parent) {
            this._super(parent);
            this.buttons = parent.$buttons;
        },
        start: function() {
            var self = this;
            this.$el.click(function(){
                self.fectchInitial()
            });
            self.buttons.click(function(e) {
                /* E (Editar) */
                if (e.target.accessKey === 'E')
                    self.$el.css('display','none');
                /* S (Guarrdar) */
                if (e.target.accessKey === 'S')
                    self.$el.css('display','flex');
                /* D (Cancelar) */
                if (e.target.accessKey === 'D')
                    self.$el.css('display','flex');
            });
        },
        updateId: function(id) {
            var self = this;
            self.id = id;
        },
        /* Remover */
        removeModal: function() {
            $('.expired-account-modal').remove();
            $('.modal-backdrop').remove();
        },
        /* Metodo Inicial */
        fectchInitial: function() {
            var self = this;
            self.fetchPayslipPaymentsIpsc(self.id).then(function(payslipIpsc) {
                return payslipIpsc;
            }).then(function(payslipIpsc) {
                self.payslipIpsc = payslipIpsc;
                return  self.fetchAccountJournal();
            }).then(function(accountJournal) {
                self.accountJournal = accountJournal;
                if (!self.payslipIpsc.length){
                    instance.web.notification.do_warn("Atención","No existe registro de I.P.S. Patronal a reconciliar.");
                    return false;
                }
                return self.showPaymentsIpse()
            });
        },
        /* IPSC */
        fetchPayslipPaymentsIpsc: function(id) {
            var payslipRun = new openerp.web.Model('hr.payslip.run');
            return payslipRun.call('eiru_get_payslip_payments_ipsc',[id],{
                    context: new openerp.web.CompoundContext()
            });
        },
        // Account Journal
        fetchAccountJournal: function(id) {
            var payslip = new openerp.web.Model('hr.payslip.run');
            return payslip.call('eiru_get_payslip_account_journal',{
                    context: new openerp.web.CompoundContext()
            });
        },
        /* Get Account Journal Select */
        getAccountJournal: function(){
            var self = this;
            var journal = [];
            _.each(self.accountJournal, function(item) {
                journal.push({
                    'id': item.id,
                    'name': item.name,
                });
            });
            if (journal.length) {
                journal.unshift({
                    'id': '',
                    'name': ''
                });
            }
            return journal
        },
        /* Filter Journal select */
        filterAccountJournal: function(id){
            var self = this;
            return _.filter(self.accountJournal, function(item){
                return  item.id === id;
            });
        },
        /* Modal */
        showPaymentsIpse: function(payslip, currency, journal) {
            var self = this;
            var defer = $.Deferred();
            var state = true;
            var payslispRun = self.payslipIpsc[0];
            var currency = payslispRun.currency;
            var accountJournal = self.getAccountJournal();
            var ipsPayments = []
            var header = [];
            if (payslispRun) {
                header.push({
                    'title': "Procesamiento "+ moment(payslispRun.date_start).format('DD/MM/YYYY')+" - "+moment(payslispRun.date_end).format('DD/MM/YYYY')
                })
            }
            var modal = Qweb.render('eiruPayslipPayments.IPSCModal',{
                'header': header,
                'journal': accountJournal,
            });
            $('.openerp_webclient_container').after(modal);
            $('.expired-account-modal').modal();
            // /* amount */
            var ipsTotal = $('.expired-account-modal').find('.amount-total');
            // /* journal && statement */
            var journalSelected = $('.expired-account-modal').find('.journal-selected');
            var statementSelected = $('.expired-account-modal').find('.statement-selected');
            var refPaymsntIps = $('.expired-account-modal').find('.ref-paymsnt-ips');
            /* button */
            var buttonAccept  = $('.expired-account-modal').find('.button-accept');
            $('.expired-account-modal').find('.ref-payments-ips-select').text("Nóminas a reconciliar\t"+ payslispRun.slipLine.length);
            ipsTotal.val(openerp.web.formatCurrency(payslispRun.amount, currency))
            $('.expired-account-modal').find('.amount-symbol-payslip').text(currency[0].symbol);
            /* Journal Change */
            journalSelected.change(function(e){
                $('.expired-account-modal').find('.paymnet-payslip-statement-open').css('display','none');
                statementSelected.empty();
                if (!!journalSelected.val()) {
                    var statementjournal =  self.filterAccountJournal(parseInt(journalSelected.val())).shift();
                    var statementOpen = statementjournal.statementOpen;
                    if (!!statementOpen.length){
                        $('.expired-account-modal').find('.paymnet-payslip-statement-open').css('display','flex');
                        statementSelected.append('');
                       _.each(statementOpen, function(item) {
                           statementSelected.append('');
                       });
                    }
                }
            });
            buttonAccept.click(function(e) {
                if (!journalSelected.val()) {
                    instance.web.notification.do_warn("Atención","Tienes que seleccionar un método de pago para continuar.");
                    journalSelected.css('border-color','red');
                    journalSelected.focus();
                    return false;
                }
                journalSelected.css('border-color','#ccc');
                var statementjournal =  self.filterAccountJournal(parseInt(journalSelected.val())).shift();
                var statementOpen = statementjournal.statementOpen;
                if (!!statementOpen.length && !statementSelected.val()) {
                    instance.web.notification.do_warn("Atención","Tienes que seleccionar una caja para continuar.");
                    statementSelected.css('border-color','red');
                    statementSelected.focus();
                    return false;
                }
                statementSelected.css('border-color','#ccc');
                if (!refPaymsntIps.val().trim()) {
                    instance.web.notification.do_warn("Atención","Debes ingresar una referencia de pago para continuar.");
                    refPaymsntIps.css('border-color','red');
                    refPaymsntIps.focus();
                    return false;
                }
                refPaymsntIps.css('border-color','#ccc');
                var paymenstIps = {
                    'runId': self.id,
                    'journalId': parseInt(journalSelected.val()),
                    'statementId': parseInt(statementSelected.val()),
                    'refPayments': refPaymsntIps.val().trim(),
                    'amount': payslispRun.amount,
                    'partnerId': payslispRun.partnerId
                }
                /* Guardar */
                $('.expired-account-modal').find('.widget-content.widget-loading-payments-ips').css('display','flex');
                self.paymentsPayslipIpsc(paymenstIps).then(function(paymentsIps){
                    return paymentsIps;
                }).then(function(paymentsIps) {
                    if (!paymentsIps.state) {
                        instance.web.notification.do_warn("Atención", paymentsIps.message, true);
                    }
                    $('.expired-account-modal').find('.widget-content.widget-loading-payments-ips').css('display','none');
                    self.removeModal(e);
                    defer.resolve(paymentsIps)
                });
            });
            /* Click Cerrar */
            $('.expired-account-modal').on('hidden.bs.modal', function (e) {
                defer.resolve(false);
                self.removeModal(e);
            });
            return defer;
        },
        /*Pagar nominas */
        paymentsPayslipIpsc: function(paymenstIps) {
            var payslipRun = new  instance.web.Model('hr.payslip.run');
            return payslipRun.call('eiru_payslip_payments_ipsc', [paymenstIps],{
                context: new instance.web.CompoundContext()
            });
        },
    });
    if (instance.web && instance.web.FormView) {
        instance.web.FormView.include({
            load_record: function(record) {
                this._super.apply(this, arguments);
                if (this.model !== 'hr.payslip.run')
                    return;
                openerp.parentInstancePayslipPaymentsIPSC = this;
                if (openerp.widgetInstancePayslipPaymentsIPSC) {
                    openerp.widgetInstancePayslipPaymentsIPSC.updateId(record.id);
                    if (this.$el.find('.payslip-payments-ipsc').length !== 0){
                        return
                    }
                }
                if (this.$el.find('.payslip-payments-ipsc').length !== 0 )
                    return;
                openerp.widgetInstancePayslipPaymentsIPSC = new openerp.PayslipPaymentsIPSC(this);
                var elemento = this.$el.find('.oe_form').find('.eiru-payslip-payments');
                openerp.widgetInstancePayslipPaymentsIPSC.appendTo(elemento);
                openerp.widgetInstancePayslipPaymentsIPSC.updateId(record.id);
            },
        });
    }
})();