/* global $  */

var page_cust = {
    loaded: false,
    baseUrl: "https://retenciones.mercadolibre.com.ve/mlretenciones",
    on_load: function(){
        if(!page_cust.loaded){
            if (global.on_load()){
                page_cust.grid.construction();
                page_cust.loaded = true;
            }
            var obj;
            obj = document.getElementById("frm_save").addEventListener("click", page_cust.form.savefrm);
        }
    },
    grid: {
        searchField: "",
        serachValue: "",
        format: {
            column: {
                errshw: function(value,row,index){
                    var salida = "";
                    if (parseInt(row.statuscust) !== 0){
                        salida = {class:'archiveShow'};
                    }else{
                        salida = {class:'errorShow'};
                    }
                    return salida;
                 },
                 islrpdfshow: function(value,row,index){
                     var salida = "";
                     if (row.islr_pdf){
                         salida = {class:'pdfShow'};
                     }
                     return salida;
                 },
                 ivapdfshow: function(value,row,index){
                     var salida = "";
                     if (row.iva_pdf){
                         salida = {class:'pdfShow'};
                     }
                     return salida;
                 }

            }
        },
        errShow: function(i){
            var row = $("#grid_area").datagrid('getRows')[i];
            var titulo = "";
            var msg = "";
            var header = "";
            switch (row.errlvl){
                case 1:
                    titulo = "Advertencia";
                    msg = row.errdsc.slice(0, -1);
                    header = "<p style='font-size:80%'>Esta factura podrá ser procesado aunque hemos encontrado algunas inconsistencias.</p>";
                    break;
                case 2:
                    titulo = "Error";
                    msg = row.errdsc.slice(0, -1);
                    header = "<p style='font-size:80%'>Esta factura no se enviará para su procesamiento hasta que no se resuelvan los errores.</p>";
                    break;
            }
            
            if (msg.length){
                msg = "<ul><li>" + msg.replace(/\|/g, "</li><li>") + "</li></ul>";
                $.messager.alert(titulo, header + msg);
            }
        },
        construction: function(){
            var getlist="api/crudcust/getlist.php?sessid="+$("#sessid").html();
                //getlist="api/crudcust/getlist.php?sessid="+document.getElementById("sessid").innerHTML;
                
            var anchoCol = parseInt(window.innerWidth*0.95/7);

            // la altura debe hacerse antes de inyectar el codigo del grid
            $("#grid_area").css("height", $(".grid_area").height()+"px");
            
            $("#grid_area").datagrid({
                url: getlist,
                //queryParams: {
                //    name: page_cust.grid.searchField,
                //    value: page_cust.grid.searchValue
                //},
                /*width: (window.innerWidth*0.95)+"px",*/
                sortName: "rif",
                striped: true,
                fitColumns: true,
                autoRowHeight: true,
                singleSelect: true,
                loadMsg: "Cargando Información...",
                emptyMsg: "No hay información, incluya un cliente",
                showHeader: true,
                showFooter: true,
                pagination: true,
                pageSize: 20,
                idField: "id",
                columns:[
                    [
                    {width:  0, align:"left", halign:"left",    field:"statuscust",      title:"ST", hidden:true},
                    {width:  0, align:"left", halign:"left",    field:"id",          title:"ID", hidden:true},
                    {width: anchoCol/2, sortable:false, align:"left", halign:"center",  field:"errshw",      title:"",      styler:page_cust.grid.format.column.errshw},
                    {width: anchoCol*1, sortable:true,  align:"left", halign:"left",    field:"rif",         title:"RIF"},
                    {width: anchoCol*1, sortable:true,  align:"left", halign:"left",    field:"custid",  title:"Cust ID"},
                    {width: anchoCol*1, sortable:true,  align:"left", halign:"left",    field:"nickname",    title:"Apodo"},
                    {width: anchoCol*2, sortable:true,  align:"left", halign:"left",    field:"name",        title:"Razón Social"},
                    {width: anchoCol*2, sortable:true,  align:"left", halign:"left",    field:"email",       title:"eMail"}
                    ]
                ],
                toolbar: [{
                            iconCls: 'icon-add',
                            text: 'Incluir',
                            handler: page_cust.form.add
                         },'-', {
                            iconCls: 'icon-edit',
                            text: 'Editar',
                            handler: page_cust.form.edit
                         },'-',{
                            iconCls: 'icon-remove',
                            text: 'Eliminar',
                            handler: page_cust.form.del
                }],
                onLoadSuccess: function(){
                    $("#datagrid-td-group1-0-1").css("background-color", "#dfdfdf");
                    $("#datagrid-td-group1-0-2").css("background-color", "#555");
                    // incluir search box
                    var html = '<div id="buscarCont" style="width:400px;position:absolute;top:3px;right:3px;text-align:right;">' +
                               '<input id="buscar" style="width:300px"></input>' +
                               '    <div id="menuBuscar" style="width:100px">' +
                               '        <div data-options="name:\'all\'">Todo</div>' +
                               '        <div data-options="name:\'rif\'">RIF</div>' +
                               '        <div data-options="name:\'custid\'">Cust Id</div>' +
                               '        <div data-options="name:\'nickname\'">Apodo</div>' +
                               '        <div data-options="name:\'name\'">Razón Social</div>' +
                               '        <div data-options="name:\'email\'">eMail</div>' +
                               '    </div>' +
                               '</div>';
                    $("#buscarCont").remove();
                    $(".datagrid-toolbar").append(html);
                    $("#buscar").searchbox({
                        prompt:'Buscar...',
                        searcher: function(value, name){
                            page_cust.grid.searchField = name;
                            page_cust.grid.searchValue = value;
                            $('#grid_area').datagrid('load', {
                                name: name,
                                value: value
                            });
                            //alert(value + " - " + name);
                        },
                        menu: "#menuBuscar"
                    });
                    $("#buscar").searchbox("selectName",page_cust.grid.searchField);
                    $("#buscar").searchbox("setValue",page_cust.grid.searchValue);
                },
                onLoadError: function(e){
                    //console.log(e);
                    $.messager.alert("No se puede mostrar la información", e.responseJSON.msg); 
                },
            });
            
            page_cust.form.construction();
        }
    },
    form: {
        status: 0,
        construction: function(){

            $("#custid").textbox({
                label: 'Cust ID:',
                labelPosition: 'top',
                required: true,
                missingMessage: 'Código de Cliente de ML',
                width: 150
            });
            $("#status").switchbutton({
                width : 100,
                onText: "Activo",
                offText: "Inactivo",
                onChange: function(checked){
                }
            });

            $("#rif").textbox({
                label:'RIF N°:',
                labelPosition:'top',
                required:true,
                missingMessage: 'Número de RIF',
                width: 325
            });
            $("#name").textbox({
                label:'Nombre o Razón Social',
                labelPosition:'top',
                required:true,
                missingMessage: 'Nombre o Razón Social del cliente',
                width: 325
            });
            $("#nickname").textbox({
                label:'Apodo',
                labelPosition:'top',
                required:true,
                missingMessage: 'Apodo del cliente',
                width: 325
            });
            $("#email").textbox({
                label:'Correo electrónico',
                labelPosition:'top',
                required:true,
                missingMessage: 'Correo electrónico',
                width: 325
            });
            
            $('#progressdlg').dialog({
                title: "Guardando",
                closed: true,
                modal: true,
                border: 'thin'
            });
            $('#dlg').dialog({
                closed: true,
                modal: true,
                border: 'thin'
            });

            $('#fm').form({
                iframe: false,
                width: 345
            });

            // BOTONES
            $("#frm_save").linkbutton({
                /*iconCls: "icon-ok"*/
            });            


            
        },
        edit: function(){
            var row = $('#grid_area').datagrid('getSelected');
            var sessid = $("#sessid").html();

            if (row){
                var parameterAjax = {   metodo      : "GET",
                                        url         : global.baseUrl + "/crudcust/getentry.php",  
                                        parameters  : "?sessid="+sessid+"&id="+row.id,
                                        onsucces    : function(json){   
                                                                        var rs = JSON.parse(json);
                                                                        if(rs.rsp){
                                                                            if (rs){
                                                                                page_cust.form.status = row.status;
                                                                                $('#dlg').dialog('open').dialog('center').dialog('setTitle','Edición de Cliente');
                                                                                $('#fm').form('load',rs);
                                                                            }
                                                                        }else{ //console.log(json.msg);
                                                                            var msg = json.msg;
                                                                            $.messager.alert('Error al cargar la cliente N°'+ row.documentid, msg); 
                                                                        }
                                                                    },
                                        onerror     : function(json){   //console.log(json);
                                                                        json = JSON.parse(json);
                                                                        var msg = "";
                                                                        if(json.rsp){
                                                                            msg = json.msg;
                                                                            $.messager.alert('Error al cargar la cliente N°'+ row.documentid, msg); 
                                                                        }
                                                                    } 
                                    };
                global.utils.callAjax( parameterAjax);
                
            }else{
                $.messager.alert("Para Editar", "Selecciona algún cliente antes de editar");
            }
        },
        add: function(){
            var sessid = $("#sessid").html();
            $('#dlg').dialog('open').dialog('center').dialog('setTitle','Nuevo Cliente');
            $('#fm').form('clear');
            $('#grid_area').datagrid('clearSelections');
        },
        del: function(){
            var row = $('#grid_area').datagrid('getSelected');
            var sessid = $("#sessid").html();
            if (row){
                $.messager.confirm( 'Confirme el borrado',
                    '¿Estás seguro de querer eliminar este registro?',
                    function(r){ 
                        if (r){
                            var parameterAjax = {   metodo      : "GET",
                                                     url         : global.baseUrl + "/crudcust/delete.php",  
                                                     parameters  : "?sessid="+sessid+"&id="+row.id,
                                                     onsucces    : function(json){   
                                                                                     $('#grid_area').datagrid('reload');
                                                                                 },
                                                     onerror     : function(json){   
                                                                                     json = JSON.parse(json);
                                                                                     var msg = "";
                                                                                     if(!json.rsp){
                                                                                         msg = json.msg;
                                                                                         $.messager.alert('Error al eliminar el cliente N°'+ row.custid, msg); 
                                                                                     }
                                                                                 } 
                                                 };
                            global.utils.callAjax( parameterAjax);
                        }
                    });
            }else{
                $.messager.alert("Para Borrar", "Selecciona algún cliente antes de borrar");
            }
        },
        close: function(){
            $('#dlg').dialog('close')
        },
        savefrm: function(){
            // prevenir cuando está deshabilitado

            //if (page_cust.form.status !==0) return;
            var id;
            var row = $('#grid_area').datagrid('getSelected');

   
            if(!row){ id = 0;}else{ id = row.id}

            $('#fm').form('submit',{
                enctype: "multipart/form-data",
                url: global.baseUrl + "/crudcust/update.php"+
                     "?sessid="+$("#sessid").html()+
                     "&id="+id,
                onProgress: function(percent) {
                    $('#progressbar').progressbar("setValue",percent);
                },
                onSubmit: function(){ 
                    if ($(this).form('validate')){
                        $('#progressdlg').dialog('open');
                        $('#progressbar').progressbar("setValue",0);
                        return(true);
                    }else{
                        $.messager.alert("Completa la Información", "Hay campos requeridos que no se están completando");
                        return(false);
                    }
                },
                success:  function(result){
                    $('#progressdlg').dialog('close');
                    var jsonresp;
                    if (global.utils.isJSON(result)){
                        jsonresp = JSON.parse(result);
                    }else{
                        jsonresp = {
                                    rsp: false,
                                    errno: 99,
                                    msg: result
                        }
                    }

                    if (!jsonresp.rsp){
//console.log("Aqui");
                        $.messager.show({ title: 'Error:', msg: jsonresp.msg});
                    }else{
                        if (jsonresp.errlvl == 1){
                            $.messager.alert("Guardado con Advertencias", "Se ha guardado la información pero se han reportado algunas advertencias.");
                        }
                        if (jsonresp.errlvl == 2){
                            $.messager.alert("Guardado con Errores", "Se ha guardado la información pero no será procesado hasta que atienda los errores ocurridos.");
                        }

                        $('#dlg').dialog('close');
                        $('#grid_area').datagrid('reload');
                    }
                }
            });
        },
    }
};
page_cust.on_load();