$( document ).ready(function() {
    loaduserdosen();
    loaddosen();

    $(".file-preview").hide();
    $(".fileinput-upload").hide();
});


$('#btn-savedsn').on('click', function(){
    savedsn();
});

function savedsn(){

    const fileupload = $('#berkas-dsn').prop('files')[0];
    console.log(fileupload);

    if(fileupload == null){
        swalValidate('Berkas Dosen Tidak Boleh Kosong');
        return false;
    }

    let formData = new FormData();
    formData.append('berkas-dsn', fileupload);
    
    loaderPage(true);

    $.ajax({
        type        : 'POST',
        url         : baseURL + '/jsondata/saveberkasdsnxlsx',
        data        : formData,
        cache       : false,
        processData : false,
        contentType : false,
        success: function (result) {

            if(result.code == 0){ 
                loaderPage(false);

                swal({
                    title: "Sukses",
                    text: "Menambah Dosen telah selesai ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                });

                $('#modal-add-dsn').modal('hide');
                loaddosen();

            }else{
                loaderPage(false);

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


function loaduserdosen(){
    let isObject = {};
    
    var dtpr = $('#data-list2').DataTable({
        "order": [[ 0, "desc" ]],
        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/loaduserdosen',
            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);

                    return response.data.data;

                    // console.log(response.data.data);
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'iduser', 'sClass':'','sWidth':'10px'},
            { 'data': 'username', 'sClass':''},
            { 'data': 'nama', 'sClass':''},
            { 'data': 'file_foto', 'sClass':''},
            { 'data': 'inisial', 'sClass':''},
            // { 'data': 'pembimbing_ta', 'sClass':''},
            { 'data': 'update_date', 'sClass':''},
            { 'data': 'status', 'sClass':''},
        ],
        
        // 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>Cari:</span> _INPUT_',
            searchPlaceholder: "cari menggunakan Nama",
            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){
            //         let dpn = '';
            //         let blk = '';

            //         if(row.gelar_dpn != 'null' && row.gelar_dpn != null && row.gelar_dpn != ''){
            //             dpn = row.gelar_dpn;
            //         }

                    
            //         if(row.gelar_blk != 'null' && row.gelar_blk != null && row.gelar_blk != ''){
            //             blk = row.gelar_blk;
            //         }

            //         let $rowdata = dpn+" "+row.nama+" "+blk;
            //         console.log(row);
            //         console.log(row.nama)
            //         console.log(dpn);
            //         console.log(blk);
            //         // if(data == 10){
            //         //     $rowdata= `<span class="label label-info">Aktif<span>`;
            //         // }else {
            //         //     $rowdata= `<span class="label label-danger">Tidak Aktif<span>`;

            //         // }


            //         return $rowdata;
            //     },
            //     visible: true,
            //     targets: 2,
            //     className: 'dt-center'
            // },
            {
                render: function (data, type, row){
                    $rowdata ='';
                    if(data == 10){
                        $rowdata= `<span class="label label-info">Aktif<span>`;
                    }else {
                        $rowdata= `<span class="label label-danger">Tidak Aktif<span>`;

                    }

                    return $rowdata;
                },
                visible: true,
                targets: 6,
                className: 'dt-center'
            },
            {
                render: function(data, type, row){
                    
                    var $url = baseURL+'/data/profilepicture/'+data;

                    if(!fileExists($url)){
                        var $rowData = '<div class="thumb img-rounded img-preview showAtt" style="width: 70px;">'+
                                            '<img src="'+baseURL+'/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="icon-file-picture"></i> '
                                                    '</p>'+
                                                '</span>'+
                                            '</div>'+
                                        '</div>';                    
                    }else{
                        var $rowData = '<div class="thumb img-rounded img-preview showAtt" style="width: 70px;">'+
                                        '<img src="'+$url+'" alt="" class="img-roun ded 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="icon-file-picture"></i> '
                                                '</p>'+
                                            '</span>'+
                                        '</div>'+
                                    '</div>';                      
                    }

                    return $rowData;
                },
                visible: true,
                targets: 3,
                className: 'dt-center'
            },
            {
                render: function (data, type, row){
                    $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">`
                        
                    if(row.status == 10){
                        $rowdata += `<li><a href="#" class="activated"><i class="icon-cross2"></i>Tidak Aktif</a></li>`
                    }else{
                        $rowdata += `<li><a href="#" class="activated"><i class="icon-checkmark"></i>Aktif</a></li>`
                    }
                                
                    $rowdata += `
                                <li><a href="#" class="reset"><i class="icon-reload-alt"></i>Reset Password</a></li>
                                <li><a href="#" class="delete"><i class="icon-trash"></i>Hapus</a></li>
                                <li><a href="#" class="editgelar"><i class="icon-user"></i>Edit Gelar</a></li>
                            </ul>
                        </li>
                    </ul>`;
                   
                    return $rowdata;
                },
                visible: true,
                targets: 7,
                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');
            $(this).find('tbody tr').slice(-3).find('.icons-list, .btn-group').addClass('position-absolute')

            var that = this;
            var td ;
            var tr ;

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

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

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

                activated(aData);
                console.log(aData);

            });
            this.$('.delete').on('click', function(){

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

                deleteuser(aData);

            });
            this.$('.reset').on('click', function(){

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

                reset(aData);

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

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

                loadAttachments(aData);

            });

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

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

                showmodal(aData);

            });

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

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

            

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

            setIFrameSize();

        }
    });
    
}


function loadAttachments(aData){
    $('#modal-image').modal("show");

    $('.isv').html(`<img src="/data/materi/imageuser/mahasiswa/`+aData.file_foto+`" >`);
}


function loadadddosen(){
    // document.getElementById("form-add-dsn").reset();
    $('#modal-add-dsn').modal('show');

    $(".file-input-ajax").fileinput({
        maxFileCount: 1,
        uploadIcon: '',
        uploadClass:'hidden',
        uploadLabel:'',
        initialPreview: [],
        fileActionSettings: fileActionSettingaddmhs,
        layoutTemplates: {
            icon: '<i class="icon-file-check"></i>',
            modal: modalTemplate
        },
        allowedFileExtensions: ["xlsx"],
        msgInvalidFileExtension : `Ekstensi tidak valid untuk file "{name}". Hanya file "{extensions}" yang didukung.`,
        msgFilesTooMany : "Melebihi batas maksimum yang diperbolehkan yaitu <b>{m}</b>. Coba lagi unggah!",
        dropZoneTitle : "Seret & Lepas File di Sini",
        initialCaption: "Tidak ada file yang dipilih",
        previewZoomButtonClasses: previewZoomButtonClasses,
        previewZoomButtonIcons: previewZoomButtonIcons
    });
}

function loaddosen(){
    let isObject = {};
    isObject.status = 'REG';
    
    var dtpr = $('#data-list3').DataTable({
        "order": [[ 0, "desc" ]],
        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/loaddatadosen',
            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);

                    return response.data.data;

                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nopeg', 'sClass':'','sWidth':'10px'},
            { 'data': 'nopeg', 'sClass':''},
            { 'data': 'nama', 'sClass':''},
            { 'data': 'inisial', 'sClass':''},
            // { 'data': 'pembimbing_ta', 'sClass':''},
            
        ],
        
        buttons: {            
            buttons: [
                {
                    extend: 'collection',
                    text: ' Tambah Dosen',
                    className: 'btn btn-default with icon-plus-circle2',
                    action: function ( e, dt, node, config ) {
                        loadadddosen();
                    }
                },
            ]
        },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
        language: {
            search: '<span>Cari:</span> _INPUT_',
            searchPlaceholder: "cari menggunakan Nama",
            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){
                    $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">
                                <li><a href="#" class="adduser"><i class="icon-user-plus"></i>Tambahkan Ke User</a></li>
                            </ul>
                        </li>
                    </ul>`;
                   
                    return $rowdata;
                },
                visible: true,
                targets: 4,
                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');
            $(this).find('tbody tr').slice(-3).find('.icons-list, .btn-group').addClass('position-absolute')

            var that = this;
            var td ;
            var tr ;

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

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

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

                adduser(aData);

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

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

            

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

            setIFrameSize();

        }
    });
    
}

function adduser(aData){
    swal({
        title: "Apakah kamu yakin ?",
        text: "Dosen dengan nama "+aData.nama+" akan ditambahkan menjadi user Sipenkp",
        type: "info",
        showCancelButton: true,
        confirmButtonText: "Ya, Yakin",
        cancelButtonText: "Tidak",
        closeOnConfirm: false,
        closeOnCancel: false
      },
        function (isConfirm) {
          if (isConfirm) {
            saveadduser(aData);

        } else {    
            swal("Gagal", "Penambahan user dosen dibatalkan", "error");
        }
    });
}

function saveadduser(aData){
    
    let isObject = {};
    isObject.nim    = aData.nopeg;
    isObject.nama   = aData.nama;
    isObject.status = '10';

    loaderPage(true);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/saveadduser',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(result){
            if(result.code == 0){
                loaderPage(false);

                    swal({
                        title: "Sukses",
                        text: "Telah selesai menambahkan user dosen dengan nama "+aData.nama,
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                    loaduserdosen();
                    loaddosen();
            }else{
                loaderPage(false);

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

                loaduserdosen();
                loaddosen();
            }
        },
        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 reset(aData){
    swal({
        title: "Apakah kamu yakin ?",
        text: "Dosen dengan nama "+aData.nama+" akan direset passwordnya",
        type: "info",
        showCancelButton: true,
        confirmButtonText: "Ya, Yakin",
        cancelButtonText: "Tidak",
        closeOnConfirm: false,
        closeOnCancel: false
      },
        function (isConfirm) {
          if (isConfirm) {
            savereset(aData);

        } else {    
            swal("Gagal", "Reset password user dibatalkan", "error");
        }
    });
}
function savereset(aData){
    let isObject = {};
    isObject.iduser = aData.iduser;
    isObject.nim    = aData.nopeg;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/resetpasswordusers',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(result){
            if(result.code == 0){
                loaderPage(false);

                    swal({
                        title: "Sukses",
                        text: "Telah selesai mereset password user dosen dengan nama "+aData.nama,
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                    loaduserdosen();
                    loaddosen();
            }else{
                loaderPage(false);

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

                loaduserdosen();
                loaddosen();
            }
        },
        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 deleteuser(aData){
    swal({
        title: "Apakah kamu yakin ?",
        text: "Dosen dengan nama "+aData.nama+" akan dihapus dari user sipintar",
        type: "info",
        showCancelButton: true,
        confirmButtonText: "Ya, Yakin",
        cancelButtonText: "Tidak",
        closeOnConfirm: false,
        closeOnCancel: false
      },
        function (isConfirm) {
          if (isConfirm) {
            deleteuseraction(aData);

        } else {    
            swal("Gagal", "Hapus user dibatalkan", "error");
        }
    });
}

function deleteuseraction(aData){
    let isObject = {}
    isObject.iduser = aData.iduser;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/deleteusers',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(result){
            if(result.code == 0){
                loaderPage(false);

                swal({
                    title: "Sukses",
                    text: "Telah selesai menghapus user dosen dengan nama "+aData.nama,
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                });
            
                loaduserdosen();
                loaddosen();
            }else{
                loaderPage(false);

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

                loaduserdosen();
                loaddosen();
            }
        },
        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 activated(aData){
    let status = aData.status;

    if(status == 10){
        $text = aData.nama+" menjadi tidak aktif" 
    }else{
        $text = aData.nama+" menjadi aktif" 
    }
    
    swal({
        title: "Apakah kamu yakin ?",
        text: "Dosen dengan nama "+$text,
        type: "info",
        showCancelButton: true,
        confirmButtonText: "Ya, Yakin",
        cancelButtonText: "Tidak",
        closeOnConfirm: false,
        closeOnCancel: false
      },
        function (isConfirm) {
          if (isConfirm) {
            saveActivated(aData);

        } else {    
            swal("Gagal", "Aktivasi user dibatalkan", "error");
        }
    });

}


function saveActivated(aData){
    let isObject = {}
    isObject.iduser = aData.iduser;
    isObject.status = aData.status;

    if(isObject.status == 10){
        $textSuccess = "Dosen dengan nama "+aData.nama+" menjadi tidak aktif"
    }else{
        $textSuccess = "Dosen dengan nama "+aData.nama+" menjadi  aktif"

    }
    loaderPage(true);

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/activateduser',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(result){
            if(result.code == 0){
                loaderPage(false);

                    swal({
                        title: "Sukses",
                        text: $textSuccess,
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                loaduserdosen();
                loaddosen();
            }else{
                loaderPage(false);

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

                loaduserdosen();
                loaddosen();            
            }
        },
        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 showmodal(data){
    
    /* set data form */
    $("#nopeg").val(data.nopeg);
    $("#nama").val(data.justnama);
    $("#dpn").val(data.gelar_dpn);
    $("#blk").val(data.gelar_blk);


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

$("#submit-edit-gelar").on("click", function(){
    editgelar();
});

function editgelar(){
    let isObject = {};

    isObject.nopeg = $("#nopeg").val();
    isObject.nama  = $("#nama").val();
    isObject.dpn   = $("#dpn").val();
    isObject.blk   = $("#blk").val();

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

    loaderPage(true);

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/editgelar',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(result){
            if(result.code == 0){
                loaderPage(false);

                    swal({
                        title: "Sukses",
                        text: "edit gelar dosen berhasil!",
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });

                $("#modal-add").modal("hide");
                
                loaduserdosen();
                loaddosen();
            }else{
                loaderPage(false);

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

                loaduserdosen();
                loaddosen();            
            }
        },
        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"
                });                        
            }
        }
    });
}


