// var parambot = loadparambobot();

$("#hitung").on('click', function(e){
    // e.preventDefault();
    loaderPage(true);
    
    // console.log(loadparambobot());
    var objbobotperusahaan = loadparambobot(81);
    var objbobotpenguji    = loadparambobot(82);
    
    var nilai_perusahaan       = document.querySelectorAll('[id^="valperusahaan"]');
    var nama_nilai_perusahaan  = document.querySelectorAll('[id^="nperusahaan"]');
    var objperusahaan    = {};
    
    for(var i = 0; i < nilai_perusahaan.length; i++){
        objperusahaan[nama_nilai_perusahaan[i].innerHTML] = nilai_perusahaan[i].value;
    }

    var sumperusahaan = {};
    if(objperusahaan.length == objbobotperusahaan.length){
        for(var n in objperusahaan){
            sumperusahaan[n] = parseFloat(objperusahaan[n]) * parseFloat(objbobotperusahaan[n]);
            
        }
    }

    console.log(sumperusahaan)
    console.log(objbobotperusahaan)
    


    var nilai_penguji      = document.querySelectorAll('[id^="valpenguji"]');
    var nama_nilai_penguji  = document.querySelectorAll('[id^="npenguji"]');
    var objpenguji    = {};
    
    for(var i = 0; i < nilai_penguji.length; i++){
        
        objpenguji[nama_nilai_penguji[i].innerHTML] = nilai_penguji[i].value;
    }

    var nilai_pembimbing      = document.querySelectorAll('[id^="valpembimbing"]');
    var nama_nilai_pembimbing  = document.querySelectorAll('[id^="npembimbing"]');
    var objpembimbing    = {};
    
    for(var i = 0; i < nilai_pembimbing.length; i++){
        
        objpembimbing[nama_nilai_pembimbing[i].innerHTML] = nilai_pembimbing[i].value;
    }

    var sumpenguji ={};
    if(objpembimbing.length == objpenguji.length){
        for(var key in objpembimbing){
            sumpenguji[key] = parseFloat(objpembimbing[key]) + parseFloat(objpenguji[key]);
        }
    }

    console.log(sumpenguji);
    // var sumpenguji={};
    // console.log(sumpenguji.length)
    // console.log(objbobotpenguji.length)
    if(sumpenguji.length == objbobotpenguji.length){
        for(var n in sumpenguji){
            sumpenguji[n] = (parseFloat(sumpenguji[n]) * parseFloat(objbobotpenguji[n]))/2;
            // console.log(objbobotpenguji[n]);
        }
    }

    console.log(sumpenguji);
    // console.log(objbobotperusahaan);
    console.log(objbobotpenguji)

    var jumpenguji = 0;
    for(const key of Object.values(sumpenguji)){
        jumpenguji = jumpenguji + key;
    }
    console.log(jumpenguji);

    var jumperusahaan = 0;
    for(const keys of Object.values(sumperusahaan)){
        jumperusahaan = jumperusahaan + keys;
    }

    console.log(jumpenguji);
    console.log(jumperusahaan);

    var nilai_akhir = jumpenguji + jumperusahaan;
    var nilai_mutu;
    console.log(nilai_akhir);
    
    if(nilai_akhir >= 80){
        nilai_mutu = "A";
    } else if(nilai_akhir >= 75 && nilai_akhir < 80){
        nilai_mutu = "AB";
    } else if(nilai_akhir >= 68 && nilai_akhir < 75){
        nilai_mutu = "B";
    } else if(nilai_akhir >= 64 && nilai_akhir < 68){
        nilai_mutu = "BC";
    }else {
        nilai_mutu = "C";
    } 

    hitungnilaiakhir(nilai_akhir);
    
})



function hitungnilaiakhir(nilai_akhir){
    var isObject = {};
    isObject.nilai_akhir = nilai_akhir;
    isObject.idkp = $("#idkp").val();
    isObject.nim  = $("#nim").val();  

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savenilaiakhir',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text: "Nilai Akhir telah dihitung",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    
                    location.reload();  
                });
                
                
                
            } 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"
                });                        
            }
        }
    });
}

loadElementsnilai(kodeprodi);
function loadElementsnilai(kodeprodi){
    loaderPage(true)
    let isObject     = {}; 
    isObject.ipoly   = 1;
    isObject.kodeprodi = kodeprodi;

    var dtpr = $('#penilaianpenguji').DataTable({
        serverSide	: true,
        destroy		: true,
        bFilter		: true,
        responsive	: true,
        searching   : true,
        pagingType  : 'full',
        lengthMenu  : [[1, 25, 50, -1], [1, 25, 50, "All"]],
        pageLength  : 25,
        ajax		: {
            url: baseURL + '/jsondata/datanilaiakhir',
            type: 'POST',
            // async: false,
            data : function (d) {         
                return $.extend( {}, d, {
                    iparam	    : cryptoEncrypt(PHRASE, isObject),
                });
            },
            dataSrc: function(response) {
                
                if(response.code == CODE_SUCCESS){
                    response = cryptoDecrypt(PHRASE, response.data);
                    // console.log(response.data.data);
                    var data = response.data.data;
                    // var datas;
                    // var dataada=[];
                    // // datas.push(data[0])
                    // // console.log(datas);
                    // for(i in data){
                    //     datas = {
                    //         "id_mhs": data[i].id_mhs,
                    //         "nim": data[i].nim,
                    //         "nama": data[i].nama,
                    //         "jurusan": data[i].jurusan,
                    //         "jeniskelamin": data[i].jeniskelamin,
                    //         "fakultas": data[i].fakultas,
                    //         "create_date": data[i].create_date,
                    //         // "status": statusberkas(data[i].nim)
                    //     }
                    //     dataada.push(datas)
                    // }
                    console.log(data)
                    // callendars(data);
                    return data;
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nim', 'sClass':'','sWidth':'10px'},
            { 'data': 'nim', 'sClass':''},
            // { 'data': 'jurusan', 'sClass':''},
            { 'data': 'nama', 'sClass':''},
            { 'data': 'dosen_pembimbing', 'sClass':''},
            { 'data': 'dosen_penguji', 'sClass':'text-center'},
            { 'data': 'mulai_kp', 'sClass':''},
            { 'data': 'tanggal', 'sClass':'text-center'},
            { 'data': 'nilai_akhir', 'sClass':'text-center'},
            { 'data': 'nilai_mutu', 'sClass':'text-center'},
            { 'data': 'isnilaicount', 'sClass':'text-center'},
            { 'data': '', 'sClass':'text-center','sWidth':'10px'}
        ],
        buttons: {            
            buttons: [
                {
                    extend: 'colvis',
                    className: 'btn btn-default'
                },
            ]
        },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            lengthMenu: '<span>Show:</span> _MENU_',
            processing: "<div class='table-loading'><img src='../../img/loadingtwo.gif' /></div>",

            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        columnDefs: [
            {
                // width: '20px',
                // targets: 0,
                // visible: true
            },
            {   


                // render: function (data, type, row){
                //     // var $rowData = '<img src="/distro/assets/images/placeholder.jpg" alt="" class="img-rounded img-preview showAtt" style="cursor: pointer;">';
                //     let isIcon = ' icon-file-download2';

                //     var $rowData = '<div class="thumb img-rounded img-preview showAtt" style="width: 70px;">'+
                //         '<img src="/distro/assets/images/placeholder.jpg" alt="" class="img-rounded img-preview showAtt">'+
                //         '<div class="caption-overflow">'+
                //             '<span>'+
                //                 '<p  class="btn showAtt bg-success-400 btn-icon btn-lg" style="font-variant: all-petite-caps;background-color: #0e0e0e33 !important;border-color: #25252591 !important;">'+
                //                     '<i class="'+isIcon+'"></i> '
                //                 '</p>'+
                //             '</span>'+
                //         '</div>'+
                //     '</div>';

                //     return $rowData;
                // },
                // visible: true,
                // targets: 1,
            },  
            {   
                // render: function (data, type, row){
                //     // console.log(row);
                //     var $rowData = ``;
                //     if(row.status_nilai_pembimbing != 1){
                //         $rowData ='<span style="min-width: 70px" class="label label-danger">Nilai Belum Diinput</span>';
                //     }else {
                //         $rowData ='<span style="min-width: 70px" class="label label-success">Nilai Sudah Diinput</span>';
                //     }
                //     return $rowData;
                // },
                // visible: true,
                // targets: 4,
            }, 
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = row.mulai_kp+" sampai "+row.akhir_kp;
                    
                    return $rowData;
                },
                visible: true,
                targets: 5,
            },
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = ``;
                    if(row.isnilaicount == 1){
                        $rowData ='<span style="min-width: 70px" class="label label-success">Nilai Sudah Dihitung</span>';
                    } else {
                        $rowData ='<span style="min-width: 70px" class="label label-danger">Nilai Belum Dihitung</span>';
                    }
                    
                    return $rowData;
                },
                visible: true,
                targets: 9,
            },
            {   
                render: function (data, type, row){
                    var $rowData = '';
                    var $actpembimbing, $actpenguji;

                    if(row.isnilaicount == 1){
                        $actpembimbing = `<li class=""><a onclick="lihatnilai(`+row.id_kp+`,'`+row.nim+`')" class=""><i class=" icon-users"></i> Hitung Nilai</a></li>`;
                        
                    } else {
                        $actpembimbing = `<li class=""><a onclick="modalnilai(`+row.id_kp+`,'`+row.nim+`')" class=""><i class=" icon-users"></i> Hitung Nilai</a></li>`;
                       
                    }

                    $rowData = `<ul class="icons-list">
                                         <li class="dropdown">
                                             <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                                 <i class="icon-menu9"></i>
                                             </a>
                                             <ul class="dropdown-menu dropdown-menu-right">
                                               
                                                `+$actpembimbing+`
                                            </ul>

                                             
                                         </li>
                                     </ul>`

                    return $rowData;
                },
                visible: false,
                targets: 10,
                className: 'dt-center'
            }, 
        ],
        fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ 
            var index = iDisplayIndexFull + 1; 
            $('td:eq(0)', nRow).html('#'+index); 
            return  index;
        },
        drawCallback: function (settings) {
            // console.log(settings.json);
            
            var api  = this.api();
            var rows = api.rows({page:'current'}).nodes();
            var last = null;

            // console.log(rows)
            // Reverse last 3 dropdowns orientation
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');

            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            this.$('.showAtt').on('click', function(){

                var tr      = $(this).parents('tr')
                var aData   = dtpr.row( tr ).data();

                // loadAttachments(aData);

            });

            
        },
        fnInitComplete: function (oSettings, json) {
            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            

            $('#mahasiswalist input').bind('keyup', function (e) {
                return this.value;
            });

            setIFrameSize();

        }
    });

}

function alreadyinputalert(){
    swal({
        title: "Alert",
        text:  "Nilai akhir telah dihitung, tidak dapat menghitung kembali nilai akhir!",
        confirmButtonColor: "#2196F3",
        type: "warning",
        icon: "warning"
    });
}

function modalnilai(idkp, nim){
    $('#idkp').val(idkp);
    $("#nim").val(nim);

    loadnilaiperusahaan(idkp);
    loadnilaipenguji(idkp);
    loadnilaipembimbing(idkp);
    $("#modal-nilai").modal('show');
}

function lihatnilai(idkp, nim){
    // $('#idkp').val(idkp);
    // $("#nim").val(nim);

    loadnilaiperusahaan(idkp);
    loadnilaipenguji(idkp);
    loadnilaipembimbing(idkp);
    $("#lihat-nilai").modal('show');
}

function loadnilaiperusahaan(idkp){
 
    var isObject = {};
    isObject.idkp = idkp;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/nilaiperusahaan',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            var x = 1;
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                console.log(data)
                $res = ``;
                for(i in data){
                    $res += `<div class="form-group">
                                <label id="nperusahaan`+x+`"class="col-lg-4 control-label text-semibold">`+data[i].nama_nilai_perusahaan+`</label>
                                <div class="col-lg-8">
                                    <div class="input-group">
                                        <span class="input-group-addon"></span>
                                        <input id="valperusahaan`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_perusahaan+`"disabled>
                                    </div>
                                </div>
                            </div>`;
                    x++;
                }

                $("#nilaiperusahaan").html($res);
                $("#nilaiperusahaanl").html($res);
                
                
            } else {
                // $("#btn-add").attr('disabled', true)
                // $("#updateberkas").hide();
                // 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 loadnilaipenguji(idkp){
 
    var isObject = {};
    isObject.idkp = idkp;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/nilaipenguji',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            var x = 1;
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                console.log(data)
                $res = ``;
                for(i in data){
                    $res += `<div class="form-group">
                                <label id="npenguji`+x+`"class="col-lg-4 control-label text-semibold">`+data[i].nama_nilai_penguji+`</label>
                                <div class="col-lg-8">
                                    <div class="input-group">
                                        <span class="input-group-addon"></span>
                                        <input id="valpenguji`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_penguji+`"disabled>
                                    </div>
                                </div>
                            </div>`;
                            x++;
                }

                $("#nilaipenguji").html($res);
                $("#nilaipengujil").html($res);
                
                
            } else {
                // $("#btn-add").attr('disabled', true)
                // $("#updateberkas").hide();
                // 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 loadnilaipembimbing(idkp){
 
    var isObject = {};
    isObject.idkp = idkp;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/nilaipembimbing',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            var x = 1;
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                console.log(data)
                $res = ``;
                for(i in data){
                    $res += `<div class="form-group">
                                <label id="npembimbing`+x+`"class="col-lg-4 control-label text-semibold">`+data[i].nama_nilai_pembimbing+`</label>
                                <div class="col-lg-8">
                                    <div class="input-group">
                                        <span class="input-group-addon"></span>
                                        <input id="valpembimbing`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_pembimbing+`"disabled>
                                    </div>
                                </div>
                            </div>`;
                            x++;
                }

                $("#nilaipembimbing").html($res);
                $("#nilaipembimbingl").html($res);
                
                
            } else {
                // $("#btn-add").attr('disabled', true)
                // $("#updateberkas").hide();
                // 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 loadparambobot(param){
    var isObject = {}
    isObject.code = param;
    var objekbobot = {};

    // console.log(pembimbing);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadparambobots',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            // $("tbody").empty();
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data    = result.data;
                // console.log(data);

                for(i in data){
                    objekbobot[data[i].nama_bobot] = data[i].bobot;
                    
                }
                
                // console.log(objekbobot);
            } 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"
                });                        
            }
        }
    });
    return objekbobot;
}

