// alert('testung testing tetes buntung')
// alert($("#mahasiswalist").attr('id'));
// //console.log($("#mahasiswalist").attr('id'))
// alert(nopeg);
var role_dosen = $("#role_dosen").val()
// alert(role_dosen);

loadElementsnilai();
function loadElementsnilai(clicksc){
    loaderPage(true)
    let isObject     = {}; 
    isObject.ipoly   = 1;
    isObject.nopeg   = nopeg;
    isObject.as      = 'penguji';
    //console.log(isObject.nopeg);

    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/datanilaipengujiasdsn',
            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': 'judul_laporan', 'sClass':''},
            { 'data': 'tanggal', 'sClass':'text-center'},
            { 'data': 'jam', 'sClass':'text-center'},
            { 'data': 'namapenguji1', 'sClass':''},
            { 'data': 'namapenguji2', 'sClass':''},
            { 'data': 'status_nilai_penguji', 'sClass':'text-center'},
            { 'data': 'status_nilai_penguji_2', '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){
                    // //console.log(row);
                    var $rowData = ``;
                    if(row.status_nilai_penguji != 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: 8,
            },
            {   
                render: function (data, type, row){
                    // //console.log(row);
                    var $rowData = ``;
                    console.log(row.namapenguji2 == null);
                    if(row.namapenguji2 == null){
                        $rowData ='<span style="min-width: 70px" class="label label-primary">Tidak terdapat Penguji 2</span>';
                        
                    }else{
                        if(row.status_nilai_penguji_2 != 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: 9,
            },
            {   
                render: function (data, type, row){
                    // //console.log(row);
                    var $rowData = ``;
                    if(row.isnilaicount != 1){
                        $rowData ='<span style="min-width: 70px" class="label label-danger">Nilai Belum Dihitung</span>';
                    }else {
                        $rowData ='<span style="min-width: 70px" class="label label-success">Nilai Sudah Diinput</span>';
                    }
                    return $rowData;
                },
                visible: true,
                targets: 10,
            },
            {   
                render: function (data, type, row){
                    var $rowData = '';
                    var $actpembimbing, $actpenguji = "";
                    console.log(row.nim_mhs)
                    // alert(row.penguji_ke);
                    // alert(row.penguji_ke == 'penguji_2')
                    if(row.penguji_ke == 'penguji_1'){
                        if(row.isnilaicount == 1){
                            // alert("isnilai1");
                            $actpenguji += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`', '`+row.nilai_akhir+`', '`+row.nilai_mutu+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.namapenguji2+`', true)" class=""><i class=" icon-users"></i> Lihat Nilai</a></li>`;
                        }else{
                            if(row.status_nilai_penguji == 1){
                                $actpenguji += `<li class=""><a onclick="modalupdate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`','`+row.namapenguji2+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.penguji_ke+`')" class=""><i class=" icon-pencil3"></i> Update Nilai</a></li>`;
                                if(row.status_nilai_penguji_2 == 1){
                                    $actpenguji += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`', '`+row.nilai_akhir+`', '`+row.nilai_mutu+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.namapenguji2+`', false)" class=""><i class=" icon-users"></i> Hitung Nilai Mahasiswa</a></li>`; 
                                }

                                if(row.namapenguji2 == null){
                                    $actpenguji += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`', '`+row.nilai_akhir+`', '`+row.nilai_mutu+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.namapenguji2+`', false)" class=""><i class=" icon-users"></i> Hitung Nilai Mahasiswa</a></li>`; 
                                }
                            }else{
                                $actpenguji  += `<li class=""><a href="`+baseURL+`/dosen/nilaipenguji?nim=`+encodeURIComponent(btoa(row.nim_mhs))+`&param=`+encodeURIComponent(btoa('penguji'))+`&penguji_ke=`+encodeURIComponent(btoa(row.penguji_ke))+`"class=""><i class=" icon-users"></i> Input Nilai Penguji</a></li>`;
                            }
                        }
                    }else if(row.penguji_ke == 'penguji_2'){
                        
                        if(row.isnilaicount == 1){
                            // alert("isnilai1");
                            $actpenguji += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`', '`+row.nilai_akhir+`', '`+row.nilai_mutu+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.namapenguji2+`', true)" class=""><i class=" icon-users"></i> Lihat Nilai</a></li>`;
                        }else{
                            if(row.status_nilai_penguji_2 == 1){
                                $actpenguji += `<li class=""><a onclick="modalupdate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`','`+row.namapenguji2+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.penguji_ke+`')" class=""><i class=" icon-pencil3"></i> Update Nilai</a></li>`;
                                if(row.status_nilai_penguji == 1){
                                    $actpenguji += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim_mhs+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`', '`+row.nilai_akhir+`', '`+row.nilai_mutu+`','`+row.penguji_1+`','`+row.penguji_2+`','`+row.namapenguji2+`', false)" class=""><i class=" icon-users"></i> Hitung Nilai Mahasiswa</a></li>`; 
                                }
                            }else{
                                $actpenguji  += `<li class=""><a href="`+baseURL+`/dosen/nilaipenguji?nim=`+encodeURIComponent(btoa(row.nim_mhs))+`&param=`+encodeURIComponent(btoa('penguji'))+`&penguji_ke=`+encodeURIComponent(btoa(row.penguji_ke))+`"class=""><i class=" icon-users"></i> Input Nilai Penguji</a></li>`;
                            }
                        }

                    }

                    console.log($actpenguji);
                    
                    $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">
                                                `+$actpenguji+`
                                            </ul>

                                             
                                         </li>
                                     </ul>`

                    return $rowData;
                },
                visible: true,
                targets: 11,
                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();

        }
    });

}

loadElementsnilaipembimbing();
function loadElementsnilaipembimbing(clicksc){
    loaderPage(true)
    let isObject     = {}; 
    isObject.ipoly   = 1;
    isObject.nopeg   = nopeg;
    isObject.as      = 'pembimbing'
    //console.log(isObject.nopeg);

    var dtpr = $('#penilaianpembimbing').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/datanilaipembimbingasdsn',
            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': 'judul_laporan', 'sClass':''},
            { 'data': 'tanggal', 'sClass':'text-center'},
            { 'data': 'jam', 'sClass':'text-center'},
            { 'data': 'dosen_pembimbing', 'sClass':''},
            { 'data': 'status_nilai_pembimbing', '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 = ``;
                    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: 7,
            },
            {   
                render: function (data, type, row){
                    // //console.log(row);
                    var $rowData = ``;
                    if(row.isnilaicount != 1){
                        $rowData ='<span style="min-width: 70px" class="label label-danger">Nilai Belum Dihitung</span>';
                    }else {
                        $rowData ='<span style="min-width: 70px" class="label label-success">Nilai Sudah Diinput</span>';
                    }
                    return $rowData;
                },
                visible: true,
                targets: 8,
            },
            {   
                render: function (data, type, row){
                    var $rowData = '';
                    var $actpembimbing, $actpenguji;

                    if(row.status_nilai_pembimbing != 1){
                        $actpembimbing = `<li class=""><a href="`+baseURL+`/dosen/nilaipenguji?nim=`+encodeURIComponent(btoa(row.nim))+`&param=`+encodeURIComponent(btoa('pembimbing'))+`"class=""><i class=" icon-users"></i> Input Nilai Pembimbing</a></li>`;
                    }else{
                        $actpembimbing = `<li class=""><a onclick="alreadyinputalert('pembimbing')" class=""><i class=" icon-users"></i> Input Nilai Pembimbing</a></li>
                        <li class=""><a onclick="modalupdate(`+row.id_kp+`, '`+row.nim+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`')" class=""><i class=" icon-pencil3"></i> Update Nilai</a></li>`;

                        if(row.status_nilai_penguji == 1 && row.status_nilai_perusahaan == 1){
                            
                            if(row.isnilaicount != 1){
                                $actpembimbing += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`')" class=""><i class=" icon-users"></i> Hitung Nilai Mahasiswa</a></li>`;
                            }else{
                                $actpembimbing += `<li class=""><a onclick="modalgenerate(`+row.id_kp+`, '`+row.nim+`', '`+row.nama+`', '`+row.file_foto+`','`+row.namapenguji1+`', '`+row.dosen_pembimbing+`', '`+row.nama_prodi+`', '`+row.nilai_akhir+`', '`+row.nilai_mutu+`')" class=""><i class=" icon-users"></i> Lihat Nilai</a></li>`;
                            }
                        }else{ //disinirey
                            $actpembimbing += `<li class=""><a onclick="notinputalready('pembimbing')" class=""><i class=" icon-users"></i> Hitung Nilai Mahasiswa</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: true,
                targets: 9,
                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(param){
    swal({
        title: "Alert",
        text:  "Penilaian "+param+" telah diinput, tidak dapat menginput kembali",
        confirmButtonColor: "#2196F3",
        type: "warning",
        icon: "warning"
    });
}

function notinputalready(param){

    if(param == 'penguji'){
        $text = 'Tidak dapat menghitung nilai, nilai pembimbing atau nilai perusahaan belum di input';
    } else {
        $text = 'Tidak dapat menghitung nilai, nilai penguji atau nilai perusahaan belum di input';
    }

    swal({
        title: "Alert",
        text:  $text,
        confirmButtonColor: "#2196F3",
        type: "warning",
        icon: "warning"
    });
}

function modalnilai(){
    // loadnilaiperusahaan();
    // loadnilaipenguji();
    // loadnilaipembimbing();
    $("#modal-nilai").modal('show');
}

function modalupdate(idkp, nim, nama, foto, penguji, pembimbing, prodi, penguji_2, nopeg_peng1, nopeg_peng2, penguji_ke){
    // alert("hi");
    $('#idkp').val(idkp);
    $("#nim").val(nim);
    //console.log(nopeg_peng1);
    //console.log(nopeg_peng2);
    if(!fileExists(foto)){
        $(".normpoint > img").attr('src', baseURL+'/data/profilepicture/defaultpics.png');
    }else{
        $(".normpoint > img").attr('src', baseURL+'/data/profilepicture/'+foto);
    }
    // //console.log(foto);
    // alert(nama+foto+penguji+pembimbing+prodi)
    // $(".normpoint > img").attr('src', '/data/profilepicture/'+foto);
    $("#identitasNaman").html(': '+nama);
    $("#identitasNimn").html(': '+nim);
    $("#identitasProdin").html(': '+prodi);
    $("#identitasPembimbingn").html(': '+pembimbing);
    $("#identitasPengujin").html(': '+penguji);
    $("#identitasPengujin2").html(': '+penguji_2);

    if(role_dosen == 'penguji'){
        if(penguji_ke == 'penguji_1'){
            loadnilaipenguji(idkp, false, true, nopeg_peng1);
        }else{
            loadnilaipenguji(idkp, false, true, nopeg_peng2);
        }
        
    }else{
        loadnilaipembimbing(idkp, false, true);
    }
    


    $("#modal-update-penguji").modal("show");
    
}

function loadnilaipenguji(idkp, ishitung, isUpdate, nopeg){
    
    var isObject = {};
    isObject.idkp = idkp;
    isObject.nopeg = nopeg;
    
    $.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){
                    if(ishitung){
                        $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"><i class="icon-pencil4"></i></span>
                                            <input id="valpenguji`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_penguji+`" disabled>
                                        </div>
                                    </div>
                                </div>`;
                        x++;
                    }else{
                        $res += `<div class="form-group">
                                <label id="nama_nilai`+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"><i class="icon-pencil4"></i></span>
                                        <input id="nilai`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_penguji+`" >
                                    </div>
                                </div>
                            </div>`;
                    x++;
                    }
                }

                if(nopeg == 'generate'){ // untuk modal generate aja
                    
                    let penguji_1 = $("#nopeg_peng_1").val();
                    let penguji_2 = $("#nopeg_peng_2").val();
                    let xz = 1;
                    $resPenguji_1 = '';
                    $resPenguji_2 = '';
                    for($i in data){
                        
                        if(penguji_1 == data[$i].nopeg){
                            $resPenguji_1 += `<div class="form-group">
                                    <label id="npengujipertama`+xz+`"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"><i class="icon-pencil4"></i></span>
                                            <input id="valpengujipertama`+xz+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[$i].nilai_penguji+`" disabled>
                                        </div>
                                    </div>
                                </div>`;
                            xz++;
                        }else{
                            $resPenguji_2 += `<div class="form-group">
                                    <label id="npengujikedua`+xz+`"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"><i class="icon-pencil4"></i></span>
                                            <input id="valpengujikedua`+xz+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[$i].nilai_penguji+`" disabled>
                                        </div>
                                    </div>
                                </div>`;
                            xz++;
                        }
                    }
                    
                }
                
                if(isUpdate == true){
                    $("#pengujinilais").html($res);
                }else{
                    if(nopeg == 'generate'){
                        // alert("hi")
                        $("#nilaipenguji").html($resPenguji_1);
                        $("#nilaipenguji2").html($resPenguji_2);

                        sumNilaiTemporary();
                    }else{
                        $("#nilaipenguji").html($res);
                    }
                    
                }
                
                $("#idnilai").val(data[0].id_nilai)
                
                
            } 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"
                });                        
            }
        }
    });
    
    
}


$("#subUpdNilai").on("click", function(e){
    e.preventDefault();
    
    var isObject    = {};
    var nilai       = document.querySelectorAll('input[id^="nilai"]');
    var nama_nilai  = document.querySelectorAll('[id^="nama_nilai"]');
    var id_nilai    = $('#idnilai').val();
    var nopegParam  = nopeg;
    // alert(nopegParam);
    // return false
    // console.log(nama_nilai);
    // console.log(nilai);
    for(var i = 0; i < nama_nilai.length; i++){
        var head = nama_nilai[i].innerHTML
        isObject[head] = nilai[i].value;
    }

    //console.log(isObject);

    updatenilaipenguji(id_nilai, isObject, nopegParam);
})

function updatenilaipenguji(idnilai, obj, nopegParam){
    var isObject    = obj;
    var isObject2   = {};

    // console.log(isObject);
    // return false;
    isObject2.idnilai    = idnilai;
    isObject2.role_dosen = role_dosen;
    isObject2.nopeg      = nopegParam;

    for(i of Object.keys(isObject)){
        //console.log(i+" -> "+isObject[i])
        if(isObject[i] == 0 || isObject[i] < 0 || isObject[i] > 100){
            swal({
                title: "Alert",
                text:  "Nilai harus berisi angka 0 - 100",
                confirmButtonColor: "#2196F3",
                type: "error"
            }); 
            return false
        }
        
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/updatenilai',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
            iparam2	    : cryptoEncrypt(PHRASE, isObject2),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                swal({
                    title: "Alert",
                    text: "Nilai "+role_dosen+" berhasil di update",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                        if(role_dosen == 'penguji'){
                            window.location = baseURL + "/dosen/penilaianpenguji"
                        }else {
                            window.location = baseURL + "/dosen/penilaianpembimbing" 
                        }
                });
                
                
                
            } else {
                $(".subnilai").attr("disabled", false)
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            $(".subnilai").attr("disabled", false)
            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, ishitung){
 
    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){
                    if(ishitung){
                        $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"><i class="icon-pencil4"></i></span>
                                            <input id="valpembimbing`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_pembimbing+`" disabled>
                                        </div>
                                    </div>
                                </div>`;
                                x++;
                    }else{
                        $res += `<div class="form-group">
                                <label id="nama_nilai`+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"><i class="icon-pencil4"></i></span>
                                        <input id="nilai`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_pembimbing+`">
                                    </div>
                                </div>
                            </div>`;
                            x++;
                    }
                }

                $("#nilaipembimbing").html($res);
                $("#pengujinilais").html($res);
                
                $("#idnilai").val(data[0].id_nilai)
                
                
            } 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 modalgenerate(idkp, nim, nama, foto, penguji, pembimbing, prodi, nilaiakhir, nilaimutu, nopeg_peng1, nopeg_peng2, penguji2, hidebutt){
    if(!fileExists(foto)){
        $(".normpoint > img").attr('src', baseURL+'/data/profilepicture/defaultpics.png');
    }else{
        $(".normpoint > img").attr('src', baseURL+'/data/profilepicture/'+foto);
    }

    // alert(typeof nilaimutu);
    // alert(typeof null)
    
        $("#nilaiakhirs").html(": "+nilaiakhir);
        $("#nilaimutus").html(": "+nilaimutu);

    if(hidebutt == true){
        $("#hitung").hide()
    }else{
        $("#hitung").show()
    }
        
    
    
    $("#nopeg_peng_1").val(nopeg_peng1);
    $("#nopeg_peng_2").val(nopeg_peng2);
    $('#idkps').val(idkp);
    $("#nims").val(nim);
    $("#identitasNama").html(': '+nama);
    $("#identitasNim").html(': '+nim);
    $("#identitasProdi").html(': '+prodi);
    $("#identitasPembimbing").html(': '+pembimbing);
    $("#identitasPenguji").html(': '+penguji);
    $("#identitasPenguji2").html(': '+penguji2);
    loadnilaiperusahaan(idkp);
    loadnilaipenguji(idkp, true, false, 'generate')
    loadnilaipembimbing(idkp, true)

    // console.log(penguji2 == 'null')

    if(penguji2 == null || penguji2 == 'null'){
        // alert("here");
        $("#dnilaipenguji2").css("display", "none");
    }else{
        $("#dnilaipenguji2").css("display", "block");
    }
    


    $("#modal-nilai").modal("show");
}

function loadnilaiperusahaan(idkp){
    loaderPage(true)
    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"><i class="icon-pencil4"></i></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"
                // });
            }

            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"
                });                        
            }
        }
    });
    
    
}

$("#hitung").on('click', function(e){
    // e.preventDefault();
    // loaderPage(true);
    
    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]);
            
    //     }
    // }
    
    // 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;
    // }
    // // //console.log(nilai_penguji);
    // // 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 objpenguji){
    //         sumpenguji[key] = parseFloat(objpenguji[key]);
    //     }
    // // }

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

    // 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;
    // }

    // var nilai_akhir = jumpenguji + jumperusahaan;
    // var nilai_mutu;

    //console.log(nilai_akhir);
    // return false;
    hitungnilaiakhir();
    
})

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;
}

function hitungnilaiakhir(){
    var isObject = {};
    isObject.nilai_akhir = sumNilaiTemporary();
    // return false;
    isObject.idkp = $("#idkps").val();
    isObject.nim  = $("#nims").val();  

    console.log(isObject);
    // return false;
    $.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"
                });                        
            }
        }
    });
}

function compare( a, b ) {
    if ( a.last_nom < b.last_nom ){
      return -1;
    }
    if ( a.last_nom > b.last_nom ){
      return 1;
    }
    return 0;
  }

function sumNilaiTemporary(){
    // load bbot
    var objbobotperusahaan = loadparambobot(81);
    var objbobotpenguji    = loadparambobot(82);

    // nilai penguji 1
    var nilai_penguji       = document.querySelectorAll('[id^="valpengujipertama"]');
    var nama_nilai_penguji  = document.querySelectorAll('[id^="npengujipertama"]');
    var objpenguji    = {};
    
    for(var i = 0; i < nilai_penguji.length; i++){
        
        objpenguji[nama_nilai_penguji[i].innerHTML] = parseInt(nilai_penguji[i].value);

    }

    // nilai penguji 2
    var nilai_penguji_2       = document.querySelectorAll('[id^="valpengujikedua"]');
    var nama_nilai_penguji_2  = document.querySelectorAll('[id^="npengujikedua"]');
    var objpenguji_2    = {};
    
    for(var i = 0; i < nilai_penguji_2.length; i++){
        
        objpenguji_2[nama_nilai_penguji_2[i].innerHTML] = parseInt(nilai_penguji_2[i].value);
    }

    var letters     = /^[A-Za-z]+$/;
    var identitasp2 = $("#identitasPenguji2").html();
    var identitas   = identitasp2.replace(/[^a-zA-Z]/g, "");

    let sorted_1 = sortObj(objpenguji);
    let sorted_2 = sortObj(objpenguji_2);


    console.log(sorted_1);
    console.log(sorted_2);
    // Tambah kedua nilai penguji
    let sumpenguji = {};

    for(var key in sorted_1){

        if(identitas == 'null'){
            sumpenguji[key] = ( parseFloat(sorted_1[key]));
        }else{
            sumpenguji[key] = ( parseFloat(sorted_1[key]) + parseFloat(sorted_2[key]) ) /2;
        }
    }

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

    // console.log(sumpenguji);
    // total nilai penguji dikali bobot
    var jumpenguji = 0;
    for(const key of Object.values(sumpenguji)){
        jumpenguji = jumpenguji + key;
    }


    // nilai perusahaan
    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]);
            
        }
    }

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

    // nilai akhir 
    console.log(jumpenguji);
    console.log(jumperusahaan);
    var nilai_akhir = jumpenguji + jumperusahaan;
    var nilai_mutu  = 0;
    
    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";
    } 

    $("#nilai_akhir_input").val(parseFloat(nilai_akhir).toFixed(2));
    $("#nilai_mutu_input").val(nilai_mutu);
    // append ke form generate
    return nilai_akhir;
}

function sortObj(obj) {
    return Object.keys(obj).sort().reduce(function (result, key) {
      result[key] = obj[key];
      return result;
    }, {});
  }

// function modalstatpenguji(){
//     $("#modal-status-penguji").modal("show");
// }