$(document).ready(function(){
    loadElementsnilai();


})

var arrayHead = [];
var arrayStep = [];


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

    var dtpr = $('#list_pengajuan').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/listproseskp',
            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);
                    
                    var data = response.data.data;
                    
                    return data;
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nim', 'sClass':'','sWidth':'10px'},
            { 'data': 'nim', 'sClass':''},
            { 'data': 'nama', 'sClass':''},
            { 'data': 'nama_prodi', 'sClass':''},
            { 'data': 'dosen_pembimbing', 'sClass':'text-center'},
            { 'data': 'jam', 'sClass':'text-center'},
           
        ],
        // buttons: {            
        //     buttons: [
        //         {
        //             extend: 'colvis',
        //             className: 'btn btn-default'
        //         },
        //     ]
        // },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fl><"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 = ``;
                    
                    $rowData ='<span style="min-width: 70px" class="btn btn-primary btn-sm up-modal">Lihat Proses Kerja Praktik</span>';
                    
                    return $rowData;
                },
                visible: true,
                targets: 5,
            },
           
        ],
        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.$('.up-modal').on('click', function(){

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

                // $(".stepy-basic").reset();

                $selecthead = document.querySelectorAll('[id*="head-"]');
                $selectstep = document.querySelectorAll('[id*="step-"]');
        
                arrayHead = [];
                arrayStep = [];

                for(var i = 0; i < $selectstep.length; i++){
                    arrayHead[i] = $selecthead[i].id;
                    arrayStep[i] = $selectstep[i].id;
                }  

                console.log(arrayHead);
                console.log(arrayStep)

                $(".button-back").hide();
                $(".button-next").hide();
                // $(".medhide").hide()

                // loadAttachments(aData);
                upmodal(aData);

            });

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

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

            

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

            setIFrameSize();

        }
    });

}

function upmodal(isData){
    loadpengajuans(isData.nim, arrayHead, arrayStep)
    loadproseskp(isData.nim, arrayHead, arrayStep)
    $("#modal-proses-mhsw").modal("show");
}

function loadproseskp(nim, arrayHead, arrayStep){
    // console.log(arrayHead);
    var isObject = {};
    isObject.nim = nim;
    // console.log(isObject.nim) 
    var status;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadproseskp',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
                
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                let datas   = data[0];
                // console.log(datas.id_kp)
                // loadtopik(datas.id_kp);
                $("#name").html(datas.nama);
                $("#nimMhs").html(datas.nim);
                $("#program-studi").html(datas.nama_prodi)

                // if(datas.file_foto != null || datas.file_foto != ""){
                   
                //     $("#img-mhsw").attr('src', "/data/profilepicture/"+datas.file_foto);
                // }

                
                if(datas.id_kp != 0 && datas.id_kp != "" && datas.id_kp != null ){
                    
                    if(datas.status_pengajuan == 104 && datas.id_pembimbing == null){
                        if(loadtopik(datas.id_kp) == false){
                            $("#infopengajuan").html('Pendaftaran dikonfirmasi akademik.');
                        } else {
                            $("#infopengajuan").html('Topik telah diinput');
                        }
                    }else if(datas.approve_proses_bimbingan == 1 && datas.id_pembimbing != 0 && datas.isvalidtu == 62){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                        $("#"+arrayHead[1]).addClass('stepy-active');
                        $("#"+arrayStep[0]).hide();
                        $("#"+arrayStep[1]).show();
                        $namapembimbing = setgelardosen(datas.dpembimbing, datas.bpembimbing, datas.dosen_pembimbing);
                        $("#namapembimbing").html($namapembimbing);
                        $("#infopembimbing").html('Proses bimbingan selesai');
                    } else if(datas.isvalidtu == 53){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                        $("#"+arrayHead[2]).addClass('stepy-active');
                        $("#"+arrayStep[0]).hide();
                        $("#"+arrayStep[2]).show();
                        $("#infoberkas").html('Mahasiswa telah mengupload berkas, menunggu hubungi TU untuk melakukan validasi');
                    } else if(datas.id_pembimbing != 0 && datas.approve_proses_bimbingan != 0 && datas.isvalidtu != 53 && datas.isvalidtu != 52 && datas.isvalidtu != 51 && datas.isvalidtu != 53){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                        $("#"+arrayHead[1]).addClass('stepy-active');
                        $("#"+arrayStep[0]).hide();
                        $("#"+arrayStep[1]).show();
                        $namapembimbing = setgelardosen(datas.dpembimbing, datas.bpembimbing, datas.dosen_pembimbing);
                        $("#namapembimbing").html($namapembimbing);
                        $("#infopembimbing").html('Mahasiswa telah memiliki pembimbing dan sedang melakukan proses bimbingan');
                    }  else if(datas.isvalidtu == 52){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                        $("#"+arrayHead[2]).addClass('stepy-active');
                        $("#"+arrayStep[0]).hide();
                        $("#"+arrayStep[2]).show();
                        $("#infoberkas").html('Berkas Mahasiswa tidak valid.');
                    } else if(datas.isvalidtu == 51 && datas.isjadwal == 72){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                        $("#"+arrayHead[2]).addClass('stepy-active');
                        $("#"+arrayStep[0]).hide();
                        $("#"+arrayStep[2]).show();
                        $("#infoberkas").html('Berkas Mahasiswa valid, menunggu TU untuk membuat jadwal persentasi.');
                    }else if(datas.isvalidtu == 51 && datas.isjadwal == 71 && datas.id_nilai == null){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                        $("#"+arrayHead[3]).addClass('stepy-active');
                        $("#"+arrayStep[0]).hide();
                        $("#"+arrayStep[3]).show();
                        $("#infojadwal").html('Jadwal persentasi telah dibuat');
                    } else if(datas.id_nilai != 0 ){
                        if(datas.nilai_akhir == null){
                            $("#"+arrayHead[0]).removeClass('stepy-active');
                            $("#"+arrayHead[4]).addClass('stepy-active');
                            $("#"+arrayStep[0]).hide();
                            $("#"+arrayStep[4]).show();
                            $("#infonilai").html('Nilai sedang dalam proses penginputan.');
                        } else if(datas.nilai_akhir != null){
                            $("#"+arrayHead[0]).removeClass('stepy-active');
                            $("#"+arrayHead[4]).addClass('stepy-active');
                            $("#"+arrayStep[0]).hide();
                            $("#"+arrayStep[4]).show();
                            $("#infonilai").html('Kerja Praktik Selesai, Nilai Akhir:');
                            $("#nilaiakhir").html(datas.nilai_akhir);
                        }
                    }

                    if(datas.status_kp == 123){
                        for(var i = 0; i< arrayHead.length; i++){
                            $("#"+arrayHead[i]).removeClass('stepy-active');
                            $("#"+arrayStep[i]).hide();
                        }
                        $("#"+arrayHead[0]).addClass('stepy-active');
                        $("#"+arrayStep[0]).show();
                        $("#infopengajuan").html('Kerja Praktik Gagal');

                    }else if(datas.status_kp == 122){
                        $("#"+arrayHead[0]).removeClass('stepy-active');
                            $("#"+arrayHead[4]).addClass('stepy-active');
                            $("#"+arrayStep[0]).hide();
                            $("#"+arrayStep[4]).show();
                            $("#infonilai").html('Kerja Praktik Selesai, Nilai Akhir:');
                            $("#nilaiakhir").html(datas.nilai_akhir);
                    }

                }

                
            } else {
                
            }

            
            
        },
        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 loadtopik(idkp){
    var isObject = {};
    isObject.idkp = idkp;
    var topic = false;
    var status;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadtopik',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
                
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
               
                topic = 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"
                });                        
            }
        }
    });

    return topic;
}

function setgelardosen(depan, belakang, nama){
    $namagelar = '';
    // console.log(depan)
    if(depan == null){
        $namagelar = nama;
    } else {
        $namagelar = depan+" "+nama;
    }

    if(belakang == null ){
        $namagelar = $namagelar;
    } else {
        $namagelar = $namagelar+", "+belakang;
    }
    // console.log()
    return $namagelar;
}

function loadpengajuans(nim, arrayHead, arrayStep){
    // console.log(arrayHead);
    var isObject = {};
    isObject.nim = nim;
    // console.log(isObject.nim) 
    var status;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadpengajuans',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
                
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                let datas   = data[0];
                // console.log(datas)

                $("#name").html(datas.nama);
                $("#nimMhs").html(datas.nim);
                $("#program-studi").html(datas.nama_prodi)

                if(datas.id_pengajuan != 0 || datas.id_pengajuan != null){
                    if(datas.status_pengajuan == 91){
                        $("#infopengajuan").html(`Mahasiswa telah mengajukan surat permohonan, menunggu TU untuk generate surat`);
                    }else if(datas.status_pengajuan == 92){
                        $("#infopengajuan").html((datas.status).toLowerCase()+``);
                    } else if(datas.status_pengajuan == 102){
                        $("#infopengajuan").html((datas.status).toLowerCase()+``)
                    }
                }

                
            } else {
                // $(".panel-info").hide();
                // $("#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"
                });                        
            }
        }
    });

}