var modalTemplate = '<div class="modal-dialog modal-lg" role="document">\n' +
'  <div class="modal-content">\n' +
'    <div class="modal-header">\n' +
'      <div class="kv-zoom-actions btn-group">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
'      <h6 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h6>\n' +
'    </div>\n' +
'    <div class="modal-body">\n' +
'      <div class="floating-buttons btn-group"></div>\n' +
'      <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
'    </div>\n' +
'  </div>\n' +
'</div>\n';

// Buttons inside zoom modal
var previewZoomButtonClasses = {
toggleheader: 'btn btn-default btn-icon btn-xs btn-header-toggle',
fullscreen: 'btn btn-default btn-icon btn-xs',
borderless: 'btn btn-default btn-icon btn-xs',
close: 'btn btn-default btn-icon btn-xs'
};

// Icons inside zoom modal classes
var previewZoomButtonIcons = {
prev: '<i class="icon-arrow-left32"></i>',
next: '<i class="icon-arrow-right32"></i>',
toggleheader: '<i class="icon-menu-open"></i>',
fullscreen: '<i class="icon-screen-full"></i>',
borderless: '<i class="icon-alignment-unalign"></i>',
close: '<i class="icon-cross3"></i>'
};

// File actions
var fileActionSettings = {
zoomClass: 'btn btn-link btn-xs btn-icon',
zoomIcon: '<i class="icon-zoomin3"></i>',
dragClass: 'btn btn-link btn-xs btn-icon',
dragIcon: '<i class="icon-three-bars"></i>',
removeClass: 'btn btn-link btn-icon btn-xs',
removeIcon: '<i class="icon-trash"></i>',
indicatorNew: '<i class="icon-file-plus text-slate"></i>',
indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
indicatorError: '<i class="icon-cross2 text-danger"></i>',
indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>'
};

$('.file-input').fileinput({
    browseLabel: 'Browse',
    browseIcon: '<i class="icon-file-plus"></i>',
    uploadLabel: '',
    uploadClass: 'hidden',
    uploadIcon: '',
    removeIcon: '<i class="icon-cross3"></i>',
    layoutTemplates: {
        icon: '<i class="icon-file-check"></i>',
        modal: modalTemplate
    },
    initialCaption: "No file selected",
    previewZoomButtonClasses: previewZoomButtonClasses,
    previewZoomButtonIcons: previewZoomButtonIcons,
    fileActionSettings: fileActionSettings
});
$(document).ready(function(){
    loadbobot();
    
    
    $("#btn-update").on("click", function(){
        var totbobot = sumnewVal();
        console.log(totbobot);
        // var id       = loadbobot()
        validateedit(totbobot);
    })

    $("#btn-add-add").on("click", function(){
        $('#modal-add').modal("show");
    })

    $("#addPopUp").on("click", function(){
        $("#modal-add").modal('show');
    })
    
    $("#deletePopUp").on("click", function(){
        $("#modal-delete").modal('show');
    })

    $("#btndelete").on("click", function(){
        validatedelete();
    })
})

// $(window).bind('beforeunload', function(){
//     return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
// });

function loadbobot(){
    let isObject = {};
    isObject.param = iduser;
    // console.log(isObject)

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadbobot',
        async: true,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data    = result.data;
                let counter = 1;
                console.log(data);
                
                $("tbody").empty()
                
                var totalbobot = 0;
                var i ;
                var countPenguji = 0;
                var countPerusahaan = 0;
                var rowCounter  = 1;

                //count bobot berdasarkan penilaian
                for(x in data){
                    if(data[x].code_penilaian == 81){
                        countPerusahaan += 1;
                    }else if(data[x].code_penilaian == 82){
                        countPenguji += 1;
                    }
                }

                var no = 1;

                //
                for(i in data){
                    var bobot           = data[i].bobot;
                    var bobottofloat    = parseFloat(bobot);
                    totalbobot += bobottofloat;
                    cols = "";

                    if(rowCounter <= countPerusahaan || data[i].code_penilaian == 81){
                        if(rowCounter == 1){
                            cols += `<tr>
                                        <td class="nilai" rowspan="`+countPerusahaan+`"> Perusahaan</td>
                                        <td class="text-center">`+no+`</td>
                                        <td name="quantity" id="paramEdt`+data[i].id_bobot+`">`+data[i].nama_bobot+`</td>
                                        <td class="col5" id="b1">x `+data[i].bobot+`</td>
                                        <td  class="col5"><input style="border:0;" class="col5 getval" min="0.05" max="1" step="0.05" id="newValb`+data[i].id_bobot+`" onchange="sumnewVal()" type="number" value="`+bobottofloat+`"></td>
                                    </tr>`;
                        } else {
                            cols += `<tr>
                                        <td class="text-center">`+no+`</td>
                                        <td id="paramEdt`+data[i].id_bobot+`">`+data[i].nama_bobot+`</td>
                                        <td class="col5" id="b1">x `+data[i].bobot+`</td>
                                        <td  class="col5"><input style="border:0;" class="col5 getval" min="0.05" max="1" step="0.05" id="newValb`+data[i].id_bobot+`" onchange="sumnewVal()" type="number" value="`+bobottofloat+`"></td>
                                    </tr>`;
                        }
                    } else if(data[i].code_penilaian == 82){
                        if(rowCounter == (countPerusahaan+1)){
                            cols += `<tr>
                                    <td class="nilai" rowspan="`+countPenguji+`">Penguji</td>
                                    <td class="text-center">`+no+`</td>
                                    <td id="paramEdt`+data[i].id_bobot+`">`+data[i].nama_bobot+`</td>
                                    <td class="col5" id="b1">x `+data[i].bobot+`</td>
                                    <td  class="col5"><input style="border:0;" class="col5 getval" min="0.05" max="1" step="0.05" id="newValb`+data[i].id_bobot+`" onchange="sumnewVal()" type="number" value="`+bobottofloat+`"> </td>
                                </tr>`;
                        } else {
                            cols += `<tr>
                                    <td class="text-center">`+no+`</td>
                                    <td id="paramEdt`+data[i].id_bobot+`">`+data[i].nama_bobot+`</td>
                                    <td class="col5" id="b1">x `+data[i].bobot+`</td>
                                    <td  class="col5"><input style="border:0;"class="col5 getval" min="0.05" max="1" step="0.05" id="newValb`+data[i].id_bobot+`" onchange="sumnewVal()" type="number" value="`+bobottofloat+`"> </td>
                                </tr>`;
                        }
                        
                    } 

                    $("tbody").append(cols);
                    rowCounter += 1;
                    no += 1;
                }
                var bottomcols  =   `<tr>
                                        <td id ="textr" colspan="3">TOTAL BOBOT</td>
                                        <td class="col5">`+parseInt(totalbobot)+`</td>
                                        <td class="col5" id="newBobot" ><span>`+parseInt(totalbobot)+`</span></td>
                                    </tr>`;
                var buttonc     =  `<tr>
                                        <td id="textr"colspan="4"></td>
                                        <td id="btn-container" class="col5"><button onclick="validateedit(sumnewVal())" id="btn-update" class="btn btn-primary">Ubah Bobot</button></td>
                                    </tr>`
                $("tbody").append(bottomcols);
                $("tbody").append(buttonc);

                var counterDelete = 1;
                var rowDelete = ``;
                $("#isDelete").empty();
                for(nama_bobot in data){
                    // console.log(data[nama_bobot].nama_bobot);
                    rowDelete += `  <div class="checkbox checkbox-right">
                                        <label class="text-bold">
                                            <input name="checkdelete" value="`+data[nama_bobot].id_bobot+`" type="checkbox" >
                                            `+counterDelete+`. `+data[nama_bobot].nama_bobot+`
                                        </label>
                                    </div>`;
                    
                    counterDelete++;

                }

                $("#isDelete").append(rowDelete);
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function validateedit(bobot){
    // event.preventDefault();
    console.log(bobot.totalbobot)
    var total = bobot.totalbobot;
    var totalfix = total.toFixed(2);
    console.log(totalfix);
    if(totalfix == 1){
        swal({
            title: "Edit Bobot Penilaian",
            text: "Edit bobot ?",
            // type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Ya!",
            cancelButtonText: "Tidak!",
            cancelButtonColor: "#DD6B55",
            closeOnConfirm: false,
            closeOnCancel: false
          },
          function(isConfirm){
            if (isConfirm) {
                editbobotbatch(bobot);
                         // submitting the form when user press yes
            } else {
              swal("Edit Bobot dibatalkan", "", "error");
            }
        });
    } else{
        swal({
            title: "Alert",
            text:  " total bobot harus = 1",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
    }
}

function editbobotbatch(id){
    var isObjects = id;
    var isObject = {};

    for(i of Object.keys(isObjects)){
        console.log(i+" -> "+isObjects[i])
        if(isObjects[i] == 0 || isObjects[i] < 0){
            swal({
                title: "Alert",
                text:  "nilai bobot tidak boleh 0 atau kurang dari 0",
                confirmButtonColor: "#2196F3",
                type: "error"
            }); 
            return false
        }
        isObject[i] = isObjects[i];
    }

    console.log(isObject);
    // return false;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/editbobotbatch',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                // let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                // let data    = result.data;
                // let counter = 1;
                // console.log(data);
                swal({
                    title: "Alert",
                    text: "Bobot telah diubah",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    // $("tbody").empty();
                    // loadUser();  
                    // loadbobot();
                    location.reload();  
                });
                
                
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}


function editbobot(id){
    var isObject = {};
    
    isObject.id     = id;
    isObject.newVal = $("#newVal"+id).val();
    var val = isObject.newVal * 5;
    console.log(val);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/editbobot',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                // let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                // let data    = result.data;
                // let counter = 1;
                // console.log(data);
                swal({
                    title: "Alert",
                    text: "Bobot telah diubah",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    // $("tbody").empty();
                    // loadUser();  
                    loadbobot();
                });
                
                
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function sumnewVal(){
    // var allow  = false;paramEdt
    var  n = document.querySelectorAll('[id^="newVal"]');
    var  nama_bobot = document.querySelectorAll('[id^="paramEdt"]');
    var  x = [];
    var  counter = 0;
    var counterpain= 0;
    var totalbobotbaru = 0;
    var isObject = []
    var i;

    console.log(nama_bobot[0].innerHTML);

    for(i = 0; i < n.length; i++){
        counterpain     = parseFloat(n[i].value);
        totalbobotbaru += counterpain;
        x.push(counterpain);
        isObject[nama_bobot[i].innerHTML] = counterpain;
    }

    isObject.totalbobot = totalbobotbaru;
    console.log(isObject);

    $("#newBobot").empty()
    var span = '<span>'+totalbobotbaru.toFixed(2)+'</span>';
    $("#newBobot").append(span);

    return isObject;
}




function savebobot(){
    var isObject = {};

    isObject.nama_bobot     = $("#namaBobot").val();
    isObject.jenis_bobot    = $("#jenisBobot").val();
    isObject.jumlah_bobot   = $("#jumBobot").val();
    
    console.log(isObject);

    if(isObject.nama_bobot == null || isObject.nama_bobot == ""){
        swal({
            title: "Alert",
            text:  " Nama bobot tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
        return false;
    }

    if(isObject.jenis_bobot == null || isObject.jenis_bobot == ""){
        swal({
            title: "Alert",
            text:  " Nama bobot tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
        return false;
    }

    if(isObject.jumlah_bobot == null || isObject.jumlah_bobot == ""){
        swal({
            title: "Alert",
            text:  " Nama bobot tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
        return false;
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savebobot',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text: "Bobot telah ditambahkan",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    
                    location.reload();  
                });
                
                
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

}

function validatedelete(){
    var favorite = {};
    var counterdel = 1;
    $.each($("input[name='checkdelete']:checked"), function(){
        // favorite.push($(this).val());
        favorite[counterdel] = $(this).val();
        counterdel++;
    });

    if(favorite != null){
        swal({
            title: "Konfirmasi",
            text: "Menghapus bobot penilaian dapat membuat bobot tidak valid, lanjutkan?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            cancelButtonColor: "#DD6B55",
            closeOnConfirm: false,
            closeOnCancel: false
          },
          function(isConfirm){
            if (isConfirm) {
                deletebobot(favorite);
                         // submitting the form when user press yes
            } else {
              swal("Hapus Bobot dibatalkan", "", "error");
            }
        });
    }
    
}

function deletebobot(datadelete){
    var isObject = datadelete;
    console.log(isObject);

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/deletebobot',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            $("#modal-delete").modal('hide');
            if(response.code == CODE_SUCCESS){
               
                swal({
                    title: "Alert",
                    text: "Bobot telah dihapus",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    // $("tbody").empty();
                    // loadUser();  
                    loadbobot();
                    // location.reload();  
                });

            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

    
}

loademailparam()
function loademailparam(){
    var isObject = {};
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadmasteremail',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                var email   = result.data[0].param_val1;
                
                $("#emails").val(email);
                $("#emails").attr('disabled',true);
            }
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

$("#updateemail").on("click", function(){
    $("#modal-email").modal('show');
})

function saveemail(){
    loaderPage(true)
    var isObject = {};
    isObject.email     = $("#email").val();
    isObject.pass      = $("#password").val();
    
    if(isObject.email == null || isObject.email == ""){
        swal({
            title: "Alert",
            text:  " email tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });loaderPage(false);
        return false;
    }

    if(!validateEmail(isObject.email)){
        swal({
            title: "Alert",
            text:  " email tidak valid",
            confirmButtonColor: "#2196F3",
            type: "error"
        });loaderPage(false);
        return false;
    }

    if(isObject.pass == null || isObject.pass == ''){
        swal({
            title: "Alert",
            text:  " password tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });loaderPage(false);
        return false;
    }
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/saveemail',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text: "email telah diubah",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    loademailparam();
                    $("#modal-email").modal("hide");
                });
                
                
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            loaderPage(false)
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function validateEmail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

$(".dh").on("click", function(){
    $("#fors").val("DaftarHadir");
    $(".f-title").html("Form Daftar Hadir");
    $('.isv').html(`<embed src="../data/forms/daftarhadir.pdf" type="application/pdf"   style="width: 100%; height: 100%; min-height: 480px;">`);
    $("#modal-forms").modal('show');
})

$(".fp").on("click", function(){
    $("#fors").val("FormPenilaian");
    $(".f-title").html("Form Penilaian Perusahaan");
    $('.isv').html(`<embed src="../data/forms/nilaiperusahaan.pdf" type="application/pdf"   style="width: 100%; height: 100%; min-height: 480px;">`);
    $("#modal-forms").modal('show');
})

$("#btn-form").on("click", function(){
    updateFormParameter();
});

function updateFormParameter(){
    const fileupload1 = $('#file1').prop('files')[0];
    const fileupload2 = $('#file2').prop('files')[0];
   
    let formData = new FormData();
    console.log(fileupload1);
    console.log(fileupload2);
    
    if(!document.getElementById("file1").files.length == 0 ){
        var regexpattern = /[\/.](pdf)$/i;
        let nameF1 = fileupload1.name;
        

        if(!regexpattern.test(nameF1)){
            swal({
                title: "Alert",
                text:  "File Harus Berupa PDF!",
                confirmButtonColor: "#2196F3",
                type: "warning"
            });  
            return false;
        }else{
            formData.append('fileupload1', fileupload1);
        }
    } 

    if(!document.getElementById("file2").files.length == 0 ){
        var regexpattern = /[\/.](pdf)$/i;
        let nameF1 = fileupload2.name;
        

        if(!regexpattern.test(nameF1)){
            swal({
                title: "Alert",
                text:  "File Harus Berupa PDF!",
                confirmButtonColor: "#2196F3",
                type: "warning"
            });  
            return false;
        }else{
            formData.append('fileupload2', fileupload2);
        }
    }
   
    $.ajax({
        type        : 'POST',
        url         : baseURL + '/jsondata/parameterforms',
        data        : formData,
        cache       : false,
        processData : false,
        contentType : false,
        success: function (response) {

            if(response.code == CODE_SUCCESS){
                loaderPage(false)
                // document.getElementById("form-data").reset();

                swal({
                    title: "Alert",
                    text: "Form telah di update ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                },function(){ 
                    $.ajax({
                        url: "",
                        context: document.body,
                        success: function(s,x){
                
                            $('html[manifest=saveappoffline.appcache]').attr('content', '');
                            $(this).html(s);
                        }
                    }); 
                    window.location = baseURL+"/admin/settingbobot"
                });

            }else{
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            };

            loaderPage(false);
            
        },
        error: function () {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Alert",
                    text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}




