$( document ).ready(function() {
    loaduserkaprodi();
});

function loaduserkaprodi(){
    let isObject = {};
    
    var dtpr = $('#data-list2').DataTable({
        "order": [[ 0, "desc" ]],
        bPaginate   : false,
        serverSide	: true,
        destroy		: true,
        bFilter		: true,
        responsive	: true,
        searching   : false,
        pagingType  : 'full',
        lengthMenu  : [[1, 25, 50, -1], [1, 25, 50, "All"]],
        pageLength  : 25,
        ajax		: {
            url: baseURL + '/jsondata/loaduserkaprodi',
            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': 'nama_prodi', '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_',
            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: 5,
                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="edit"><i class="icon-pencil4"></i>Edit Kaprodi</a></li>
                            </ul>
                        </li>
                    </ul>`;
                   
                    return $rowdata;
                },
                visible: true,
                targets: 6,
                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;

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

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

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

                edituser(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);

            });

            
        },
        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 selectkaprodi(){
    let isObject = {};

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadselectkaprodi',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            if(response.code == CODE_SUCCESS){
                let result = cryptoDecrypt(PHRASE, response.data);
                let data = result.data;

                var $data = [];

                for(x in data){
                    $data.push({
                        id: data[x].nopeg,
                        text: data[x].nama
                    })
                }


                $('#select-kaprodi').select2({
                    placeholder : "Pilih Kaprodi",
                    data:$data,
                    allowClear: true,
                    
                });

                // $res = '';
                // for(z in data){
                //     $res += "<option>"+data[z].nama+"</option>"
                // }
               
                // $("#select-kaprodi").empty();
                // $("#select")
                // $("#select-kaprodi").append($res);
            }
        },
        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 edituser(aData){
    $('#title-modal').empty();
    $('#select-kaprodi').val('').trigger('change');
    $('#temp').val(aData.iduser);

    let kodeprodi = null;
    if(aData.nama_prodi == 'Teknik Mesin'){
        kodeprodi = 131;
    }else if(aData.nama_prodi == 'Teknik Dirgantara'){
        kodeprodi = 136;
    }else if(aData.nama_prodi == 'Teknik Material'){
        kodeprodi = 137;
    }else{
        kodeprodi = null;
    }

    $("#kodeprodi").val(kodeprodi);
    
    selectkaprodi();
    $('#modal-edit').modal('show');
    $('#title-modal').append('Edit Kaprodi '+aData.nama_prodi)

}

$('#btn-update').on('click', function(){
    let isObject = {};
    isObject.iduser  = $('#temp').val();
    isObject.nopeg = $('#select-kaprodi').val();

    if(isObject.nopeg == ''){
        swalValidate('Nama Ketua Prodi Tidak Boleh Kosong');
        return false;
    }

    swal({
        title: "Apakah kamu yakin ?",
        text: "Akan Mengganti Ketua Prodi",
        type: "info",
        showCancelButton: true,
        confirmButtonText: "Ya, Yakin",
        cancelButtonText: "Tidak",
        closeOnConfirm: false,
        closeOnCancel: false
      },
        function (isConfirm) {
        if (isConfirm) {
            savekaprodi();
        }else {    
            swal("Gagal", "Mengganti ketua prodi dibatalkan", "error");
        }
    });

})

function savekaprodi(){
    loaderPage(true);
    let isObject = {};
    isObject.iduser  = $('#temp').val();
    isObject.nopeg = $('#select-kaprodi').val();
    isObject.prodi = $("#kodeprodi").val();

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

                    swal({
                        title: "Sukses",
                        text: "Telah selesai mengganti kaprodi",
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                    loaduserkaprodi();
                    $('#modal-edit').modal('hide');
            }else{
                loaderPage(false);

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

                loaduserkaprodi();
            }
        },
        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: "Kaprodi  "+aData.nama_prodi+" 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 nama_prodi = aData.nama_prodi;
    let temp_prodi = nama_prodi.split(" ");

    nama_prodi = temp_prodi[1];
    nama_prodi = nama_prodi.toLowerCase()

    let isObject = {};
    isObject.iduser = aData.iduser;
    isObject.nim    = aData.username;

    $.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 kaprodi "+aData.nama_prodi+" menjadi 'kaprodi"+nama_prodi+"'",
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    });
                
                    loaduserkaprodi();
            }else{
                loaderPage(false);

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

                loaduserkaprodi();
            }
        },
        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 = 'Kaprodi '+aData.nama_prodi+" menjadi tidak aktif" 
    }else{
        $text = 'Kaprodi '+aData.nama_prodi+" 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"
                    });
                
                loaduserkaprodi();
            }else{
                loaderPage(false);

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

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


