//~ Empresa Libre
//~ Copyright (C) 2016-2018  Mauricio Baeza Servin (web@correolibre.net)
//~
//~ This program is free software: you can redistribute it and/or modify
//~ it under the terms of the GNU General Public License as published by
//~ the Free Software Foundation, either version 3 of the License, or
//~ (at your option) any later version.
//~
//~ This program is distributed in the hope that it will be useful,
//~ but WITHOUT ANY WARRANTY; without even the implied warranty of
//~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//~ GNU General Public License for more details.
//~
//~ You should have received a copy of the GNU General Public License
//~ along with this program.  If not, see <http://www.gnu.org/licenses/>.


var cfg_partners = new Object()


var partners_controllers = {
    init: function(){
        $$('cmd_new_partner').attachEvent('onItemClick', cmd_new_partner_click);
        //~ $$('cmd_new_contact').attachEvent('onItemClick', cmd_new_contact_click);
        $$('cmd_edit_partner').attachEvent('onItemClick', cmd_edit_partner_click);
        $$('cmd_delete_partner').attachEvent('onItemClick', cmd_delete_partner_click);
        $$('cmd_save_partner').attachEvent('onItemClick', cmd_save_partner_click);
        $$('cmd_cancel_partner').attachEvent('onItemClick', cmd_cancel_partner_click);
        //~ $$('cmd_cancel_contact').attachEvent('onItemClick', cmd_cancel_contact_click);
        //~ $$('cmd_partner_zero').attachEvent('onItemClick', cmd_partner_zero_click);
        $$('codigo_postal').attachEvent('onKeyPress', postal_code_key_press);
        $$('codigo_postal').attachEvent('onTimedKeyPress', postal_code_key_up);
        $$('colonia').attachEvent('onFocus', colonia_on_focus)
        $$("tipo_persona").attachEvent( "onChange", opt_tipo_change)
        $$("es_cliente").attachEvent( "onChange", is_client_change)
        $$("es_proveedor").attachEvent( "onChange", is_supplier_change)
        $$("rfc").attachEvent( "onBlur", rfc_lost_focus)
        $$('multi').attachEvent('onViewChange', multi_change)
        $$('grid_partners').attachEvent('onItemDblClick', grid_partners_double_click)
        //~ $$('grid_partners').attachEvent('onSelectChange', grid_partners_on_select_change)

        $$('partner_balance').attachEvent('onChange', partner_balance_on_change)
        $$('cmd_partner_add_account_bank').attachEvent('onItemClick', cmd_partner_add_account_bank_click)
        $$('grid_partner_account_bank').attachEvent('onItemClick', grid_partner_account_bank_click)
        default_config_partners()
    }
}


function default_config_partners(){
    webix.ajax().get('/config', {'fields': 'partners'}, {
        error: function(text, data, xhr) {
            msg = 'Error al consultar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json()
            cfg_partners = values
            //~ show('cmd_partner_zero', cfg_partners['chk_config_change_balance_partner'])
        }
    })

}


function get_condicion_pago(){
    webix.ajax().get('/values/condicionespago', {
        error: function(text, data, xhr) {
        },
        success: function(text, data, xhr) {
            var values = data.json();
            $$('condicion_pago').define('suggest', values)
            $$('condicion_pago').refresh()
        }
    })
}


function cmd_new_partner_click(id, e, node){
    $$('form_partner').clearValidation()
    $$('form_partner_account_bank').clearValidation()

    $$('form_partner').setValues({
            id: 0, pais: 'México', tipo_persona: 1, es_activo: true,
            partner_balance: 0.00})
    $$('forma_pago').getList().load('/values/formapago')
    get_condicion_pago()
    $$('grid_partners').clearSelection()
    $$('multi_partners').setValue('partners_new')
    $$('tab_partner').setValue('Datos Fiscales')

    get_uso_cfdi_to_table()
    query = table_usocfdi.chain().find({fisica: true}).data()
    $$('lst_uso_cfdi_socio').getList().parse(query)
    $$('partner_balance').define('readonly', !cfg_partners['chk_config_change_balance_partner'])
    get_partner_banks()
    get_partner_accounts_bank(0)
    get_sat_regimenes()
}


function cmd_new_contact_click(id, e, node){
    $$('grid_contacts').clearSelection()
    $$('multi_contacts').setValue('contacts_new')
}


function cmd_edit_partner_click(){
    var msg = ''
    var row = $$('grid_partners').getSelectedItem()

    $$('form_partner_account_bank').clearValidation()

    if (row == undefined){
        msg = 'Selecciona un Socio de Negocio'
        msg_error(msg)
        return
    }
    get_condicion_pago()

    webix.ajax().get("/partners", {id: row['id']}, {
        error: function(text, data, xhr) {
            msg_error()
        },
        success: function(text, data, xhr){
            var values = data.json()

            $$('form_partner').clearValidation()
            $$('form_partner').setValues(values)
            $$('forma_pago').getList().load('/values/formapago')

            $$('partner_balance').define('readonly', !cfg_partners['chk_config_change_balance_partner'])
            get_uso_cfdi_to_table()

            if(values.tipo_persona == 1){
                query = table_usocfdi.chain().find({fisica: true}).data()
                get_sat_regimenes()
            }else if(values.tipo_persona == 2){
                query = table_usocfdi.chain().find({moral: true}).data()
                get_sat_regimenes(true)
            }else{
                query = [{id: 'P01', value: 'Por definir'}]
            }
            $$('lst_uso_cfdi_socio').getList().parse(query)
            if(values.es_cliente){
                $$('cuenta_cliente').enable()
            }
            if(values.es_proveedor){
                $$('cuenta_proveedor').enable()
            }
            get_partner_accounts_bank(row['id'])
            pause(250)
            $$('lst_receptor_regimenes_fiscales').select(values.regimenes)
        }
    })

    $$('multi_partners').setValue('partners_new')
    $$('tab_partner').setValue('Datos Fiscales')
    get_partner_banks()

}


function cmd_delete_partner_click(id, e, node){
    var msg = ''
    var row = $$('grid_partners').getSelectedItem()

    if (row == undefined){
        msg = 'Selecciona un Cliente o Proveedor'
        msg_error(msg)
        return
    }

    msg = '¿Estás seguro de eliminar al cliente?<BR><BR>'
    msg += row['nombre'] + ' (' + row['rfc'] + ')'
    msg += '<BR><BR>ESTA ACCIÓN NO SE PUEDE DESHACER<BR><BR>'
    msg += 'Solo se pueden eliminar clientes o proveedores sin documentos '
    msg += 'relacionados. Se recomienda solo desactivar en vez de eliminar'
    webix.confirm({
        title:'Eliminar Cliente',
        ok:'Si',
        cancel:'No',
        type:'confirm-error',
        text:msg,
        callback:function(result){
            if (result){
                delete_partner(row['id'])
            }
        }
    })
};


function delete_partner(id){
    webix.ajax().del('/partners', {id: id}, function(text, xml, xhr){
        var msg = 'Socio eliminado correctamente'
        if (xhr.status == 200){
            $$('grid_partners').remove(id);
            msg_ok(msg)
        } else {
            msg = 'No se pudo eliminar. Asegurate de que no tenga documentos relacionados'
            msg_error(msg)
        }
    })
}


function cmd_save_partner_click(id, e, node){
    var msg = 'Valores inválidos'
    var form = this.getFormView();

    if (!form.validate()) {
        msg_error(msg)
        return
    }

    var values = form.getValues();

    if(!values.rfc){
        msg = 'Captura el RFC'
        msg_error(msg)
        $$('tab_partner').setValue('Datos Fiscales')
        return
    }

    if(values.tipo_persona != 4){
        if(values.codigo_postal && values.codigo_postal.length != 5){
            msg = 'Longitud inválida del C.P.'
            msg_error(msg)
            return
        }
    }

    if (!values.es_cliente && !values.es_proveedor){
        msg = 'Selecciona si es cliente, proveedor o ambos'
        msg_error(msg)
        $$('tab_partner').setValue('Otros Datos')
        return
    }

    if(values.tipo_persona == 4){
        if(values.pais && values.pais.length != 3){
            msg = 'Longitud de país inválida'
            msg_error(msg)
            return
        }
    }

    var ids_regimenes = $$('lst_receptor_regimenes_fiscales').getSelectedId()
    if(values.tipo_persona < 3){
        if(!ids_regimenes){
            msg = 'Selecciona al menos un Regimen Fiscal'
            msg_error(msg)
            return
        }
    }

    values['accounts'] = $$('grid_partner_account_bank').data.getRange()
    values['regimenes'] = ids_regimenes

    webix.ajax().post('/partners', values, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico';
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            var values = data.json();
            if (values.ok) {
                update_grid_partner(values)
            } else {
                msg_error(values.msg)
            }
        }
    })

}


function update_grid_partner(values){
    var msg = 'Socio de negocio agregado correctamente'
    if (values.new){
        $$('form_partner').clear()
        $$('grid_partners').add(values.row)
    }else{
        msg = 'Socio de negocio actualizado correctamente'
        $$("grid_partners").updateItem(values.row['id'], values.row)
    }
    $$('multi_partners').setValue('partners_home')
    msg_ok(msg)
}


function cmd_cancel_partner_click(id, e, node){
    $$('multi_partners').setValue('partners_home')
}


function cmd_cancel_contact_click(id, e, node){
    $$('multi_contacts').setValue('contacts_home')
}


function postal_code_key_up(){
    var value = this.getValue()
    var msg = ''
    if( value.length == 5 ){
        webix.ajax().get('/values/cp', {cp: value}, {
            error: function(text, data, xhr) {
                msg_error('Error al consultar el C.P.')
            },
            success: function(text, data, xhr) {
                var values = data.json();
                if (values.estado == undefined){
                    msg = 'No se encontró el C.P., asegurate de que sea correcto'
                    msg_error(msg)
                } else {
                    $$('form_partner').setValues({
                        estado: values.estado,
                        municipio: values.municipio,
                        colonia: ''}, true)
                    $$('colonia').define('suggest', [])
                    if (webix.isArray(values.colonia)){
                        $$('colonia').define('suggest', values.colonia)
                    }else{
                        $$('form_partner').setValues({colonia: values.colonia}, true)
                    }
                    $$('colonia').refresh()
                    $$('form_partner').focus('colonia')
                }
            }
        })
    }
}


function postal_code_key_press(code, e){
    var data = [8, 9, 37, 39, 46]
    if ( data.indexOf(code) >= 0 ){
        return true;
    }

    if ( code < 48 || code > 57){
        return false;
    }
}


function colonia_on_focus(){
    if ($$(this.config.suggest).getList().config.height > 2){
        $$(this.config.suggest).show(this.getInputNode())
    }
}


function opt_tipo_change(new_value, old_value){

    $$("nombre").define("value", "")
    $$("pais").define("readonly", true)
    $$("pais").define("value", PAIS)
    $$('id_fiscal').define('value', '')
    show('id_fiscal', new_value == 4)

    $$('lst_receptor_regimenes_fiscales').clearAll()
    var regimen_616 = {id: 11, value: '[616] Sin obligaciones fiscales'}

    if (new_value == 1 || new_value == 2){
        $$("rfc").define("value", "")
        $$("rfc").define("readonly", false)
        moral = false
        if(new_value == 2){
            moral = true
        }
        get_sat_regimenes(moral)
    } else if (new_value == 3) {
        $$("rfc").define("value", RFC_PUBLICO)
        $$("nombre").define("value", PUBLICO)
        $$("rfc").define("readonly", true)
        $$('lst_receptor_regimenes_fiscales').parse(regimen_616)
    } else if (new_value == 4) {
        $$("rfc").define("value", RFC_EXTRANJERO)
        $$("rfc").define("readonly", true)
        $$("pais").define("readonly", false)
        $$("pais").define("value", "")
        $$('lst_receptor_regimenes_fiscales').parse(regimen_616)
    }

    $$("nombre").refresh();
    $$("rfc").refresh();
    $$("pais").refresh();
    if (new_value == 3) {
        $$("calle").focus();
    } else {
        $$("rfc").focus();
    }

    $$('lst_uso_cfdi_socio').define('suggest', [])
    if (new_value == 1){
        query = table_usocfdi.chain().find({fisica: true}).data()
    }else if (new_value == 2){
        query = table_usocfdi.chain().find({moral: true}).data()
    }else{
        query = [{id: 'S01', value: '[S01] Sin efectos fiscales.  '}]
    }
    $$('lst_uso_cfdi_socio').getList().parse(query)
    $$('lst_uso_cfdi_socio').refresh()


}


function is_client_change(new_value, old_value){
    var value = Boolean(new_value)
    if (value){
        $$("cuenta_cliente").enable();
    } else {
        $$("cuenta_cliente").disable();
    }
}


function is_supplier_change(new_value, old_value){
    var value = Boolean(new_value)
    if (value){
        $$("cuenta_proveedor").enable()
    } else {
        $$("cuenta_proveedor").disable()
    }
}


function rfc_lost_focus(prev_view){
    //~ var form = this.getFormView()
    //~ var values = form.getValues()

    //~ if (values.rfc.trim() == ""){
        //~ return
    //~ }

    //~ if (values.id == undefined){
        //~ exclude = ''
    //~ } else {
        //~ exclude = {'id': values.id}
    //~ }

    //~ values = {
        //~ 'table': 'partner',
        //~ 'filter': {'rfc': values.rfc.trim().toUpperCase()},
        //~ 'exclude': exclude,
    //~ }
    //~ webix.message(values)
    //~ webix.ajax().get("/values/validate", values, {
        //~ error:function(text, data, XmlHttpRequest){
            //~ msg = "No se pudo validar el RFC"
            //~ webix.message({ type:"error", text: msg });
        //~ },
        //~ success:function(text, data, XmlHttpRequest){
            //~ var values = data.json();
            //~ if (values.exists) {
                //~ msg = "El RFC ya existe"
                //~ webix.message({ type:"error", text: msg });
            //~ }
        //~ }
    //~ })
}


function multi_partners_change(prevID, nextID){
    //~ webix.message(prevID)
    //~ webix.message(nextID)
}


function grid_partners_double_click(id, e, node){
    //~ if(id.column!='saldo_cliente'){
    cmd_edit_partner_click()
    //~ }
}


function partner_balance_on_change(new_value, old_value){
    if(!isFinite(new_value)){
        this.config.value = old_value
        this.refresh()
    }
}


function cmd_partner_add_account_bank_click(){
    var form = $$('form_partner_account_bank')

    if (!form.validate()){
        msg = 'Valores inválidos'
        msg_error(msg)
        return
    }

    var values = form.getValues()
    var id_partner = $$('form_partner').getValues().id

    var account = {
        id_partner: id_partner,
        delete: '-',
        banco: $$('lst_partner_bank').getText(),
        cuenta: values.partner_account.trim(),
        clabe: values.partner_clabe.trim(),
    }

    if(!account.cuenta){
        msg = 'La cuenta es requerida'
        msg_error(msg)
        return
    }

    if(!account.cuenta.is_number()){
        msg = 'Solo digitos en la cuenta'
        msg_error(msg)
        return
    }

    if(account.cuenta.length < 10){
        msg = 'Longitud incorrecta de la cuenta'
        msg_error(msg)
        return
    }

    if(!account.clabe){
        msg = 'La CLABE es requerida'
        msg_error(msg)
        return
    }

    if(account.clabe.length != 18){
        msg = 'La CLABE debe ser de 18 digitos'
        msg_error(msg)
        return
    }

    if(!account.clabe.is_number()){
        msg = 'Solo digitos en la CLABE'
        msg_error(msg)
        return
    }

    var grid = $$('grid_partner_account_bank')

    if(id_partner){
        partner_new_account_bank(account, grid)
    }else{
        grid.add(account)
    }

    form.setValues({})
}


function get_partner_banks(){
    webix.ajax().get('/satbancos', {opt: 'active'}, function(text, data){
        var values = data.json()
        $$('lst_partner_bank').getList().parse(values)
    })
}


function partner_new_account_bank(account, grid){
    webix.ajax().post('/socioscb', {opt: 'new', values: account}, {
        error: function(text, data, xhr) {
            msg = 'Error al guardar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json()
            if(values.ok){
                account['id'] = values.id
                grid.add(account)
                msg_ok(values.msg)
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function get_partner_accounts_bank(id_partner){
    var grid = $$('grid_partner_account_bank')
    grid.clearAll()

    if(id_partner){
        var data = {opt: 'by_partner', id_partner: id_partner}
        webix.ajax().get('/socioscb', data, {
            error: function(text, data, xhr) {
                msg = 'Error al consultar'
                msg_error(msg)
            },
            success: function(text, data, xhr) {
                var values = data.json()
                grid.parse(values)
            }
        })
    }
}


function grid_partner_account_bank_click(id, e, node){
    if(id.column != 'delete'){
        return
    }
    var id_partner = $$('form_partner').getValues().id
    var grid = $$('grid_partner_account_bank')

    var msg = '¿Estás seguro de eliminar la cuenta de banco seleccionada?<BR><BR>'
    msg += 'ESTA ACCION NO SE PUEDE DESHACER'
    webix.confirm({
        title: 'Eliminar cuenta de banco',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if (result){
                if(id_partner){
                    partner_delete_account_bank(id.row)
                }else{
                    grid.remove(id.row)
                }
            }
        }
    })
}


function partner_delete_account_bank(row){
    var grid = $$('grid_partner_account_bank')

    webix.ajax().post('/socioscb', {opt: 'delete', values: {id: row}}, {
        error: function(text, data, xhr) {
            msg = 'Error al eliminar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json()
            if(values.ok){
                grid.remove(row)
                msg_ok(values.msg)
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function get_sat_regimenes(morales=false){
    var data = {opt: 'actives', morales: morales}
    webix.ajax().sync().get('/satregimenes', data, {
        error: function(text, data, xhr) {
            msg = 'Error al consultar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json()
            $$('lst_receptor_regimenes_fiscales').clearAll()
            $$('lst_receptor_regimenes_fiscales').parse(values)
        }
    })

}

