//Variables globales
var sessionId = sessionStorage.getItem("sessionId");
var pagerNumber = 10;
var userEditId;
window.onload = function () {
    initApp();
    //loadListCurrencies();
    loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);

    var selectOrderBy = document.getElementById("orderBy");
    selectOrderBy.addEventListener("change", function () {
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });

    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change", function () {
        loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });
    document.getElementById("search").addEventListener("keyup", function (e) {
        if (e.keyCode == 13) loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });

    //Crear
    document.getElementById("addData").addEventListener('click', function (event) {

        document.getElementById("buttonSave").classList.remove("noShow");
        document.getElementById("addDepartment").value = "";
        document.getElementById("addMail").value = "";
        document.getElementById("addDesk").value = "";
        document.getElementById("phoneOneNumber").value = "";
        document.getElementById("phoneTwoNumber").value = "";
        document.getElementById("phoneThreeNumber").value = "";
        document.getElementById("phoneOne").selectedIndex = "0";
        document.getElementById("phoneTwo").selectedIndex = "0";
        document.getElementById("phoneThree").selectedIndex = "0";
        //document.getElementById("addDesk").setAttribute("dataNumber","");
        userEditId = 0;
        showModal();
    });
    document.getElementById("deleteM").addEventListener('click', function (event) {
        if (userEditId !== 0)
            transactionsDelete();
        else
            document.getElementById("modalconfir").style.display = "none";

    });
    document.getElementById("aceptM").addEventListener('click', function (event) {
        transactionsUpdate();
    });
    /*funcion del ordenar**/

    var orderDirect = document.getElementById("orderDirect");
    if (orderDirect !== null) {
        orderDirect.addEventListener("change", function () {
            document.getElementById("orderBy").dispatchEvent(new Event("change"));
        });
    }

    /**SOLO NUMEROS */
    var phones = document.getElementsByClassName("inputPhone");
    for (var i = 0; i < phones.length; i++) {
        phones[i].addEventListener("keypress", function (e) {
            soloNumeros(e)
        });
    }
}
//Solo permite introducir numeros.
function soloNumeros(e) {
    var key = window.event ? e.which : e.keyCode;
    if (key < 48 || key > 57) {
        e.preventDefault();
    }
}
//Función para cargar listado
function loadList(filter, order, offset, numofrec, sessionid) {
    var par = {};
    //var currencyid = document.getElementById("pairFilter").value;
    //Se pasa el document.getElementById("search").value por el parametro filter.
    if (filter !== "" && filter !== undefined && filter !== null)
        par.filter = filter;
    //if(currencyid !== "" && currencyid !== undefined && currencyid !== null)
    //par.currencyid = currencyid;
    var order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if (dir == "desc") order = "-" + order;
    par.order = order;
    par.offset = offset;
    par.numofrec = numofrec;
    //par.type = document.getElementById("typeFilter").value;
    //par.daterange = document.getElementById("rangeFilter").value;
    par.sessionid = sessionid;
    //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "departments/list", par, respList);
    return 0;
}
//Función para el retorno del listado listado
function respList(status, rsp) {
    let currencies = JSON.parse(rsp);
    var msg = document.getElementById("messageApi");
    switch (status) {
        case 200:
            // console.log(currencies);
            let newnumofrec = parseInt(currencies.numofrecords);
            if (currencies.numofrecords === 0) {
                /*Blanquear tabla*/
                var nodeNoDelete = document.getElementById("noCurrencieDefine");
                if (nodeNoDelete) {
                    var nodeClone = nodeNoDelete.cloneNode(true);
                    nodeClone.style.display = "none";
                }
                var table = document.getElementById("bodyTableCurrencies");
                table.innerHTML = "";
                if (nodeClone !== undefined && nodeClone !== null) {
                    table.appendChild(nodeClone);
                }
                /**-hasta aqui-**/
                //document.getElementById("noCurrencieDefine").style.display = "block";
                //document.getElementById("msgInTable").innerHTML="No Posee Balances definidos";
                document.getElementById("paginator").style.display = "none";
            } else {
                if (newnumofrec <= pagerNumber) {
                    document.getElementById("paginator").style.display = "none";
                } else {
                    document.getElementById("paginator").style.display = "";
                    drawPags(newnumofrec, "numbersPaginator");
                }
                /*Blanquear tabla*/
                var nodeNoDelete = document.getElementById("noCurrencieDefine");
                if (nodeNoDelete) {
                    var nodeClone = nodeNoDelete.cloneNode(true);
                    nodeClone.style.display = "none";
                }
                var table = document.getElementById("bodyTableCurrencies");
                table.innerHTML = "";
                if (nodeClone !== undefined && nodeClone !== null) table.appendChild(nodeClone);
                /**-hasta aqui-**/
                //Pintar registros
                paintRowsList(currencies);
            }
            break;
        case 400:
            msg.innerHTML = currencies.msg;
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                msg.style.display = "none";
            }, 5000);
            break;
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 500:
            msg.innerHTML = " Error Interno";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                msg.style.display = "none";
            }, 3000);
            break;
        default:
            msg.innerHTML = currencies.msg;
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                msg.style.display = "none";
            }, 3000);
    }
}

//Funcion para el Paginado
function drawPags(numofrecords, tbl) {
    var pages = Math.ceil(numofrecords / pagerNumber);
    var numbersPaginator = document.getElementById(tbl);
    var lastPag = 0;
    if (numbersPaginator.getElementsByClassName("pSelect").length > 0) {
        lastPag = numbersPaginator.getElementsByClassName("pSelect")[0].getAttribute("data-page");
    }
    numbersPaginator.innerHTML = "";
    for (let k = 0; k < pages; k++) {
        var p = document.createElement("div");
        p.classList.add("pages");
        p.innerHTML = k + 1;
        p.dataset.page = k + 1;
        if (lastPag == 0 && k == 0) p.classList.add("pSelect");//Se selecciona la página 1
        else if (lastPag !== 0 && (lastPag - 1) == k) p.classList.add("pSelect");

        p.addEventListener("click", function () {
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) pSel[0].classList.remove("pSelect");

            //Se actualiza la página seleccionada
            this.classList.add("pSelect");

            //Se repinta el listado desde el offset seleccionado
            var offset = (this.innerHTML - 1) * pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        p.style.cursor = "pointer";
        numbersPaginator.appendChild(p);

    }
    //Asignación de eventos validar que sólo se haga una vez
    if (numbersPaginator.getAttribute("arrowsEvent") == "false") {
        var leftArrow = numbersPaginator.previousElementSibling;
        var rightArrow = numbersPaginator.nextElementSibling;
        //Evento flecha izquierda
        leftArrow.addEventListener("click", function () {
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) {
                //Si el elemento anterior al seleccionado es una pagina
                if (pSel[0].previousElementSibling.classList.contains("pages")) {
                    var last = pSel[0];
                    pSel[0].previousElementSibling.classList.add("pSelect");
                    last.classList.remove("pSelect");
                    //Se repinta el listado desde el offset seleccionado
                    var offset = (pSel[0].innerHTML - 1) * pagerNumber;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                }
            }
        });
        //Evento flecha derecha
        rightArrow.addEventListener("click", function () {
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) {
                //Si el elemento anterior al seleccionado es una pagina
                if (pSel[0].nextElementSibling.classList.contains("pages")) {
                    pSel[0].nextElementSibling.classList.add("pSelect");
                    pSel[0].classList.remove("pSelect");

                    //Se repinta el listado desde el offset seleccionado
                    var offset = (pSel[0].innerHTML - 1) * pagerNumber;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                }
            }
        });
        numbersPaginator.setAttribute("arrowsEvent", true);
    }

}
function showModal() {
    //document.getElementById('txid').value = txId;
    if (parseInt(userEditId) === 0) {
        document.getElementById("tittlemodal").innerText = "Agregar";
        document.getElementById("deleteM").innerHTML = "CANCELAR";
    } else {
        document.getElementById("tittlemodal").innerText = "Editar";
        document.getElementById("deleteM").innerHTML = "ELIMINAR";
    }
    var modal = document.getElementById("modalconfir");
    modal.style.display = "block";
    window.onclick = function (event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
}

//Aqui se pintan los registros
function paintRowsList(data) {
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if (pageInPaginator) {
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    rowCurrencie.innerHTML = "";
    var filas;
    let newnumofrec = parseInt(data.numofrecords);
    if (newnumofrec > pagerNumber) {
        filas = newnumofrec - ((parseInt(pageInPaginator) - 1) * pagerNumber);
        if (filas > pagerNumber) {
            filas = pagerNumber;
        }
    } else {
        filas = newnumofrec;
    }


    //type 0 = impar, 1 = par
    let type = 0;
    let dataC = data.records;
    for (let i = 0; i < filas; i++) {
        var tableLine = document.createElement("div");
        tableLine.classList.add("tableLine");
        tableLine.id = "line/" + dataC[i].id;
        if (type === 0) {
            tableLine.classList.add("rowImpar");
            type = type + 1;
        } else if (type === 1) {
            type = 0;
        }

        tableLine.innerHTML = '<div class="cell1">' +
            '<div class="divCellCnt">' +
            '<span>' + dataC[i].dsc + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="cell2">' +
            '<div class="divCellCnt">' +
            '<span>' + dataC[i].email + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="cell3">' +
            '<div class="divCellCnt">' +
            '<span>' + dataC[i].phone1 + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="cell4">' +
            '<div class="divCellCnt">' +
            '<span>' + dataC[i].phone2 + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="cell5">' +
            '<div class="divCellCnt">' +
            '<span>' + dataC[i].phone3 + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="cell6">' +
            '<div class="divCellCnt">' +
            '<span>' + dataC[i].helpdesk + '</span>' +
            '</div>' +
            '</div>';
        rowCurrencie.appendChild(tableLine);
    }
    document.querySelectorAll('[id^="line/"]').forEach(function (element) {
        element.addEventListener('click', function (event) {
            var id = (this.id).split("/")[1];
            document.getElementById("buttonDelete").classList.remove("noShow");
            userEditId = parseInt(id);
            transactionsEntry(id);
            showModal();
        });
    });

}
function transactionsEntry(id) {
    var par = {};
    par.id = parseInt(id);
    par.sessionid = sessionId;
    callWS("GET", "departments/entry", par, rspTransactionsEntry);
    return 0;
}
function rspTransactionsEntry(status, rsp) {
    switch (status) {
        case 200:
            //console.log(JSON.parse(rsp));
            var resp = JSON.parse(rsp);
            document.getElementById("addMail").value = resp.entry.email;
            document.getElementById("addDepartment").value = resp.entry.dsc;
            document.getElementById("addDesk").value = resp.entry.helpdesk;
            showPhone((resp.entry.phone1).split("-")[0], "phoneOne");
            document.getElementById("phoneOneNumber").value = (resp.entry.phone1).split("-")[1];

            if (resp.entry.phone2 !== "") {
                showPhone((resp.entry.phone2).split("-")[0], "phoneTwo");
                document.getElementById("phoneTwoNumber").value = (resp.entry.phone2).split("-")[1];
            }
            if (resp.entry.phone3 !== "") {
                showPhone((resp.entry.phone3).split("-")[0], "phoneThree");
                document.getElementById("phoneThreeNumber").value = (resp.entry.phone3).split("-")[1];
            }
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
        //console.log(rsp);
    }
}
function showPhone(code, codeSelect) {
    switch (code) {
        case "0412":
            document.getElementById(codeSelect).selectedIndex = "0";
            break;
        case "0414":
            document.getElementById(codeSelect).selectedIndex = "1";
            break;
        case "0424":
            document.getElementById(codeSelect).selectedIndex = "2";
            break;
        case "0416":
            document.getElementById(codeSelect).selectedIndex = "3";
            break;
        case "0426":
            document.getElementById(codeSelect).selectedIndex = "4";
            break;
        default:
            document.getElementById(codeSelect).selectedIndex = "0";
    }
}
function transactionsUpdate() {

    var msg = document.getElementById("msgError");
    var email = document.getElementById("addMail").value;
    var desc = document.getElementById("addDepartment").value;

    var phone = "";
    if (document.getElementById("phoneOneNumber").value !== "") {
        if (document.getElementById("phoneOneNumber").value.length !== 7) {
            msg.innerText = "Formato de télefono 1 inválido por favor introduzca 7 dígitos";
            msg.style.visibility = "visible";
            setTimeout(function () {
                msg.style.visibility = "hidden";
            }, 4000);
            return 0;
        }
        phone = document.getElementById("phoneOne").value + "-" + document.getElementById("phoneOneNumber").value;
    }
    var phone2 = "";
    if (document.getElementById("phoneTwoNumber").value !== "") {
        if (document.getElementById("phoneTwoNumber").value.length !== 7) {
            msg.innerText = "Formato de télefono 2 inválido por favor introduzca 7 dígitos";
            msg.style.visibility = "visible";
            setTimeout(function () {
                msg.style.visibility = "hidden";
            }, 4000);
            return 0;
        }
        phone2 = document.getElementById("phoneTwo").value + "-" + document.getElementById("phoneTwoNumber").value;
    }
    var phone3 = "";
    if (document.getElementById("phoneThreeNumber").value !== "") {
        if (document.getElementById("phoneThreeNumber").value.length !== 7) {
            msg.innerText = "Formato de teléfono 3 inválido por favor introduzca 7 dígitos";
            msg.style.visibility = "visible";
            setTimeout(function () {
                msg.style.visibility = "hidden";
            }, 4000);
            return 0;
        }
        phone3 = document.getElementById("phoneThree").value + "-" + document.getElementById("phoneThreeNumber").value;
    }
    var hduser = document.getElementById("addDesk").value;
    if (desc === "") {
        msg.innerText = "Por favor complete el campo departamento.";
        msg.style.visibility = "visible";
        setTimeout(function () {
            msg.style.visibility = "hidden";
        }, 4000);
        return 0;
    }
    if (email === "") {
        msg.innerText = "Por favor complete el campo email.";
        msg.style.visibility = "visible";
        setTimeout(function () {
            msg.style.visibility = "hidden";
        }, 4000);
        return 0;
    }
    if (!checkEmail(document.getElementById("addMail"))) {
        msg.innerText = "Escriba una direcci\u00F3n de correo válida";
        msg.style.visibility = "visible";
        setTimeout(function () {
            msg.style.visibility = "hidden";
        }, 4000);
        return 0;
    }
    if (phone === "" && phone2 === "" && phone3 === "") {
        msg.innerText = "Por favor ingrese al menos un teléfono.";
        msg.style.visibility = "visible";
        setTimeout(function () {
            msg.style.visibility = "hidden";
        }, 4000);
        return 0;
    }


    var par = {};
    par.id = userEditId;
    par.email = email;
    par.dsc = desc;
    par.phone = phone;
    par.phone2 = phone2;
    par.phone3 = phone3;
    par.hduser = hduser;
    par.sessionid = sessionId;
    console.log(par)
    callWS("GET", "departments/update", par, rspTransactionsUpdate);
    return 0;
}
function rspTransactionsUpdate(status, rsp) {
    var msg = document.getElementById("msgError");
    switch (status) {
        case 200:
            console.log(JSON.parse(rsp));
            loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
            document.getElementById("modalconfir").style.display = "none";
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 402:
            msg.innerText = "Registro duplicado, ya existe el departamento";
            msg.style.visibility = "visible";
            setTimeout(function () {
                msg.style.visibility = "hidden";
            }, 4000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}
function transactionsDelete() {
    var par = {};
    par.id = userEditId;
    par.sessionid = sessionId;
    callWS("GET", "departments/delete", par, rspTransactionsDelete);
    return 0;
}
function rspTransactionsDelete(status, rsp) {
    switch (status) {
        case 200:
            console.log(JSON.parse(rsp));
            loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
            document.getElementById("modalconfir").style.display = "none";
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
        //console.log(rsp);
    }
}