$( document ).ready(function() {
    loadusermahasiswa();
    loadmahasiswa();
    loadselectprodi();

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


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

function loadselectprodi(){
    let isObject = {};

    $.ajax({
		type: 'POST',
		dataType: 'json',
        url: baseURL + '/jsondata/loadprodi',
        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;

                var $dataSelect= [];
                
                for(x in data){
                    $dataSelect.push({
                        id: data[x].id_prodi,
                        text: data[x].nama_prodi
                    })
                }

                $('.select-prodi').select2({
                    placeholder : "-- Semua --",
                    minimumResultsForSearch: -1,
                    data:$dataSelect,
                    allowClear: true
                });

                $('.select-prodi1').select2({
                    placeholder : "-- Semua --",
                    minimumResultsForSearch: -1,
                    data:$dataSelect,
                    allowClear: true
                });

                // console.log($dataSelect);
            }
		}
    });
}

function savemhs(){

    const fileupload = $('.berkass').prop('files')[0];
    console.log(fileupload);
    if(fileupload == null){
        swalValidate('Berkas Mahasiswa Tidak Boleh Kosong');
        return false;
    }
    
    let formData = new FormData();
    formData.append('berkas-mhs', fileupload);
    
    loaderPage(true);

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

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

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

                $('#modal-add-mhs').modal('hide');
                loadmahasiswa();

            }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 loadaddmhs(){
    document.getElementById("form-add-mhs").reset();
    $('#modal-add-mhs').modal('show');

    $(".file-input-ajax").fileinput({
        maxFileCount: 1,
        uploadIcon: '',
        uploadClass:'hidden',
        uploadLabel:'',
        // initialPreview: false,
        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
    });
}

$('.select-prodi').on('change', function(){
    loadusermahasiswa();
 });
$('.select-prodi1').on('change', function(){
    loadmahasiswa();
 });

function loadusermahasiswa(){
    let isObject = {};
    isObject.filter = $('.select-prodi').val();

    var tableuser = $('#data-list2').DataTable({
        "order": [[ 0, "desc" ]],
        dom: 'Blfrtip',
        processing: true,
        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/loadusermahasiswa',
            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);
                    return response.data.data;

                   
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nim', 'sClass':'','sWidth':'10px'},
            { 'data': 'username', 'sClass':''},
            { 'data': 'name', 'sClass':''},
            { 'data': 'nama_prodi', 'sClass':''},
            { 'data': 'file_foto', 'sClass':''},
            { 'data': 'email', 'sClass':''},
            { 'data': 'update_date', 'sClass':''},
            { 'data': 'status', 'sClass':''},
        ],
        
        buttons: [
           
            // {
            //     extend: 'colvis',
            //     text: ' FilterTabel',
            //     collectionLayout: 'fixed two-column',
            //     className: 'btn with glyphicon  glyphicon-filter',
            // }
        ],
        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 NIM",
            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 ='';
                    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: 7,
                className: 'dt-center'
            },
            // {
            //     render: function(data, type, row){
                    
            //         var $url = baseURL+'/data/materi/imageuser/mahasiswa/'+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: 4,
            //     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>
                            </ul>
                        </li>
                    </ul>`;
                   
                    return $rowdata;
                },
                visible: true,
                targets: 8,
                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   = tableuser.row( tr ).data();

                activated(aData);

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

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

                deleteuser(aData);

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

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

                reset(aData);

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

                var tr      = $(this).parents('tr')
                var aData   = tableuser.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;
            });

            

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

            setIFrameSize();

        }
    });
}



function loadAttachments(aData){
    $('#modal-image').modal("show");
    $('.isv').html(`<img src="`+baseURL+`/data/materi/imageuser/mahasiswa/`+aData.file_foto+`" >`);
}

function loadmahasiswa(){
    let isObject = {};
    isObject.filter = $('.select-prodi1').val();
    
    var table = $('#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/loaddatamahasiswa',
            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);
                    return response.data.data;

                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nim', 'sClass':'','sWidth':'10px'},
            { 'data': 'nim', 'sClass':''},
            { 'data': 'nama', 'sClass':''},
            { 'data': 'nama_prodi', 'sClass':''},
            { 'data': 'email', 'sClass':''},
            { 'data': 'sks', 'sClass':''},
            { 'data': 'ip', 'sClass':''},
            
        ],
        
        buttons: {            
            buttons: [
                {
                    extend: 'collection',
                    text: ' Tambah Mahasiswa',
                    className: 'btn btn-default with icon-plus-circle2',
                    action: function ( e, dt, node, config ) {
                        loadaddmhs();
                    }
                },
            ]
        },
        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 NIM",
            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: 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.$('.adduser').on('click', function(){

                var tr      = $(this).parents('tr')
                var aData   = table.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-list3 input').bind('keyup', function (e) {
                return this.value;
            });

            setIFrameSize();

        }
    });
    
}

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

function saveadduser(aData){
    
    let isObject = {};
    isObject.nim    = aData.nim;
    isObject.nama   = aData.nama;

    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 mahasiswa dengan nama "+aData.nama,
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                    loadusermahasiswa();
                    loadmahasiswa();
            }else{
                loaderPage(false);

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

                loadusermahasiswa();
                loadmahasiswa();
            }
        },
        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: "Mahasiswa dengan nama "+aData.name+" 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.nim;

    // console.log(isObject);

    $.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 mahasiswa dengan nama "+aData.name,
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                    loadusermahasiswa();
                    loadmahasiswa();
            }else{
                loaderPage(false);

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

                loadusermahasiswa();
                loadmahasiswa();
            }
        },
        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: "Mahasiswa dengan nama "+aData.name+" akan dihapus dari user Sipenkp",
        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 mahasiswa dengan nama "+aData.name,
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                });
            
                loadusermahasiswa();
                loadmahasiswa();
            }else{
                loaderPage(false);

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

                loadusermahasiswa();
                loadmahasiswa();
            }
        },
        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.name+" menjadi tidak aktif" 
    }else{
        $text = aData.name+" menjadi aktif" 
    }
    
    swal({
        title: "Apakah kamu yakin ?",
        text: "Mahasiswa 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 = "Mahasiswa dengan nama "+aData.name+" menjadi tidak aktif"
    }else{
        $textSuccess = "Mahasiswa dengan nama "+aData.name+" 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"
                    });
                
                loadusermahasiswa();
                loadmahasiswa();
            }else{
                loaderPage(false);

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

                loadusermahasiswa();
                loadmahasiswa();            
            }
        },
        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"
                });                        
            }
        }
    });
}


