// SIDEBAR JS
$("#sel-kec ").change(function() {
    var id_kec = $(this).val()
    // console.log(id_kec)

    // $(".datatable-show-all.list_perb").dataTable().fnDestroy();
    // $("#list_perbaikan").dataTable().fnDestroy();
    $(".datatab").dataTable().fnDestroy()
        // $("#dataperb").css('display', 'none')
        // $(".datatab").css('display', 'none')
        // $(".datatable-show-all.list_perb").html('kosong')

    $.ajax({
        url: "api/filt_perbaikan_kecamatan",
        data: {
            'id_kec': id_kec
        },
        dataType: 'json',
        success: function(data) {
            if (data['res_kel'] == 'all_kecamatan') {
                $('#sel-desa').html(`<option>Pilih Desa</option>`);
            } else {
                var data_all_desa = []
                for (var i = 0; i < data['res_kel'].length; i++) {
                    var id_k = data['res_kel'][i][0];
                    var data_k = data['res_kel'][i][1];

                    var data_kel = `<option value="` + id_k + ` ">` +
                        data_k +
                        `</option>`;
                    data_all_desa.push(data_kel)
                };
                $('#sel-desa').html(`<option>Pilih Desa</option>` + data_all_desa);
            }


            var data_perbaikan = []
            var number = 0;

            for (var i = 0; i < data['res_perbaikan'].length; i++) {

                number += 1;
                var name_perbaikan = data['res_perbaikan'][i]['name_perbaikan'];
                var id_object = data['res_perbaikan'][i]['id_object'];
                var name = data['res_perbaikan'][i]['name'];
                var type = data['res_perbaikan'][i]['type'];
                var tgl_perbaikan = data['res_perbaikan'][i]['tgl_perbaikan'];
                var anggaran = data['res_perbaikan'][i]['anggaran'];
                var tgl_selesai = data['res_perbaikan'][i]['tgl_selesai'];
                var idbenar = data['res_perbaikan'][i]['id'];

                // console.log(id_object,idbenar)

                var data_gab = `<tr>
                    <td>` + number + `</td>
                    <td>` + name_perbaikan + `</td>
                    <td>` + name + `</td>
                    <td>` + type + `</td>
                    <td>` + tgl_perbaikan + `</td>
                    <td>` + tgl_selesai + `</td>
                    <td class="text-center ">
                        <a class="btn mdlFire " onclick="loaddetailid(`+id_object+`,`+idbenar+`) " data-toggle="modal " data-target="#modal_detail_perbaikan " style="background-color: #5A9AFB;color: white;border-radius: 5px;width: 85px;height: 25px; ">
                            <div style="margin-top: -5px; ">
                                <i class="icon-search4 text-muted text-size-base " style="color: white;font-size: 10px; "></i>
                                <span>&nbsp;&nbsp;
                                    Detail</span>
                            </div>

                        </a>
                    </td>
                </tr>`;

                // var data_gab = `<li class="media panel panel-body stack-media-on-mobile" style="background: transparent;border: none;color: white;">
                //     <div>
                //         ` + number + `
                //     </div>
                //     <div>
                //         ` + name_perbaikan + `
                //     </div>
                //     <div>
                //         ` + name + `
                //     </div>
                //     <div>
                //         ` + type + `
                //     </div>
                //     <div>
                //         ` + tgl_perbaikan + `
                //     </div>
                //     <div>
                //         ` + tgl_selesai + `
                //     </div>
                //     <div>
                //         ` + anggaran + `
                //     </div>
                //     <div>
                //         <a class="btn mdlFire " onclick="loaddetailid( '` + id_object + `') " data-toggle="modal" data-target="#modal_detail_perbaikan" style="background-color: #5A9AFB;color: white;border-radius: 5px;height: 25px; ">
                //             <span>
                //                 <i class="icon-search4 text-muted text-size-base " style="color: white;font-size: 10px; "></i>
                //                 &nbsp;&nbsp;
                //                     Detail
                //             </span>

                //         </a>
                //     </div>
                // </li>`;
                data_perbaikan.push(data_gab)
            };

            // $("#tbody_perbaikan").html(data_perbaikan)
            // $("#dataperb").html(data_perbaikan)
            $("#dataperb").html(data_gab)
            datatatata()
        }

    });


});

$("#sel-desa ").change(function() {
    var id_desa = $(this).val()
    // console.log(id_desa)

    // $(".datatab").dataTable().fnDestroy()
    // $(".datatable-show-all.list_perb").dataTable().fnDestroy();
    // $("#list_perbaikan").dataTable().fnDestroy();
    $(".datatab").dataTable().fnDestroy()

    $.ajax({
        url: "api/filt_perbaikan_desa",
        data: {
            'id_desa': id_desa
        },
        dataType: 'json',
        success: function(data) {

            var data_perbaikan = []
            var number = 0;

            for (var i = 0; i < data['res_perbaikan'].length; i++) {

                number += 1;
                var name_perbaikan = data['res_perbaikan'][i]['name_perbaikan'];
                var id_object = data['res_perbaikan'][i]['id_object'];
                var name = data['res_perbaikan'][i]['name'];
                var type = data['res_perbaikan'][i]['type'];
                var tgl_perbaikan = data['res_perbaikan'][i]['tgl_perbaikan'];
                var anggaran = data['res_perbaikan'][i]['anggaran'];
                var tgl_selesai = data['res_perbaikan'][i]['tgl_selesai'];
                var idbenar = data['res_perbaikan'][i]['id'];

                // console.log(number, name, name_perbaikan)

                var data_gab = `<tr>
                    <td>` + number + `</td>
                    <td>` + name_perbaikan + `</td>
                    <td>` + name + `</td>
                    <td>` + type + `</td>
                    <td>` + tgl_perbaikan + `</td>
                    <td>` + tgl_selesai + `</td>
                    <td class="text-center ">
                        <a class="btn mdlFire " onclick="loaddetailid(`+id_object+`,`+idbenar+`)" data-toggle="modal " data-target="#modal_detail_perbaikan " style="background-color: #5A9AFB;color: white;border-radius: 5px;width: 85px;height: 25px; ">
                            <div style="margin-top: -5px; ">
                                <i class="icon-search4 text-muted text-size-base " style="color: white;font-size: 10px; "></i>
                                <span>&nbsp;&nbsp;
                                    Detail</span>
                            </div>

                        </a>
                    </td>
                </tr>`;

                // var data_gab = `<li class="media panel panel-body stack-media-on-mobile" style="background: transparent;border: none;color: white;">
                //     <div>
                //         ` + number + `
                //     </div>
                //     <div>
                //         ` + name_perbaikan + `
                //     </div>
                //     <div>
                //         ` + name + `
                //     </div>
                //     <div>
                //         ` + type + `
                //     </div>
                //     <div>
                //         ` + tgl_perbaikan + `
                //     </div>
                //     <div>
                //         ` + tgl_selesai + `
                //     </div>
                //     <div>
                //         ` + anggaran + `
                //     </div>
                //     <div>
                //         <a class="btn mdlFire " onclick="loaddetailid( '` + id_object + `') " data-toggle="modal" data-target="#modal_detail_perbaikan" style="background-color: #5A9AFB;color: white;border-radius: 5px;height: 25px; ">
                //             <span>
                //                 <i class="icon-search4 text-muted text-size-base " style="color: white;font-size: 10px; "></i>
                //                 &nbsp;&nbsp;
                //                     Detail
                //             </span>

                //         </a>
                //     </div>
                // </li>`;
                data_perbaikan.push(data_gab)
            };

            // $("#tbody_perbaikan ").html(data_perbaikan)
            // $("#dataperb").html(data_perbaikan)
            $("#dataperb").html(data_gab)
            datatatata()

        }

    });


});

function datatatata() {
    // $('.datatable-show-all.list_perb').DataTable({
    $('.datatab').DataTable({
        autoWidth: false,
        columnDefs: [{
            orderable: false,
            width: '20px',
            targets: [0],

        }, {
            orderable: false,
            width: '20px',
            targets: [6],

        }, {
            orderable: false,
            width: '20px',
            targets: [7],

        }, ],
        dom: '<"float-left "B>frtip',
        language: {
            search: ' _INPUT_',
            searchPlaceholder: 'Data Perbaikan...',
            lengthMenu: '<span>Show:</span><hr> _MENU_',
            paginate: {
                'first': 'First',
                'last': 'Last',
                'next': '&rarr;',
                'previous': '&larr;'
            }
        },
        drawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });
}

//    $("#perbaikan_manage").click(function() {
//        // $(".datatable-show-all.list_perb").dataTable().fnDestroy();
//        $(".datatab").dataTable().fnDestroy();
//        setTimeout(function() {
//            datatatata()
//        }, 100);
//
//
//    })

var nama_delete_perb_det = null;
var tipe_delete_perb_det = null;

var propos = ``;
var doku = ``;

$("#perbaikan_manage").on("click", function() {
    $.ajax({
        url: "api/dataperbaikan",
        dataType: 'json',
        type: 'get',
        success: function(data) {

            // var today = new Date().toISOString().slice(0, 10);
            var dt = new Date();
            var today = dt.getFullYear() + "-" + ((dt.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) + "-" + dt.getDate();

            // var datenow = today.getDate()
            
            console.log(today)
            
            var status = ``;
            var propos = ``;
            var doku = ``;

            var data_per = []
            var num = 0
            for (i in data) {
                num += 1;
                // console.log(data[i].id)

                var tgl_perbaikan = data[i].tgl_perbaikan;
                var tgl_selesai = data[i].tgl_selesai;

                if((data[i].tgl_perbaikan == '0001-01-01') || (data[i].tgl_selesai == '0001-01-01') || (data[i].tgl_disetujui == '0001-01-01')){
                    status = `<span style="background-color:#b81a1a; border-radius: 2px;">&nbsp; Dalam Perencanaan &nbsp;</span>`;
                    if(data[i].tgl_perbaikan == '0001-01-01'){
                        tgl_perbaikan = `-`;
                    }
                    if(data[i].tgl_selesai == '0001-01-01'){
                        tgl_selesai = `-`;
                    }
                    // if(data[i].tgl_disetujui != '0001-01-01'){}
                } else {
                    if (today < data[i].tgl_perbaikan){
                        status = `<span style="background-color:#b86e1a; border-radius: 2px;">&nbsp; Direncanakan &nbsp;</span>`;
                    }
                    else if((today >= data[i].tgl_perbaikan)&&(today <= data[i].tgl_selesai)){
                        status = `<span style="background-color:#b0b81a; border-radius: 2px;">&nbsp; Sedang Berjalan &nbsp;</span>`;
                    }
                    else if(today > data[i].tgl_selesai){
                        status = `<span style="background-color:#35bd6b; border-radius: 2px;">&nbsp; Selesai &nbsp;</span>`;
                    }
                }
                
                console.log(data[i].proposal)

                if (data[i].proposal == 'None'){
                    propos = `<span style="background-color:#b81a1a; border-radius: 2px;">&nbsp; Belum ada Proposal &nbsp;</span>`;
                } else {
                    propos = ``;
                }

                if (data[i].bukti_selesai == 'None'){
                    doku = `<span style="background-color:#b81a1a; border-radius: 2px;">&nbsp; Direncanakan &nbsp;</span>`;
                } else {
                    doku = ``;
                }

                var data_i = `<li class="media panel panel-body stack-media-on-mobile" id="cunli" style="background: transparent;border: none;color: white;">
                            <div>
                                ` + num + `
                            </div>
                            <div>
                                ` + data[i].name_perbaikan + `
                            </div>
                            <div>
                                ` + data[i].name + `
                            </div>
                            <div>
                                ` + data[i].desa + `, ` + data[i].kecamatan + `
                            </div>
                            <div>
                                `+ status +`
                            </div>
                            <div>
                                ` + tgl_perbaikan + `
                            </div>
                            <div>
                                ` + tgl_selesai + `
                            </div>
                            <div>
                                <a class="btn mdlFire " onclick="loaddetailid(`+data[i].id_object+`,`+data[i].id+`) " data-toggle="modal" data-target="#modal_detail_perbaikan" style="background-color: #5A9AFB;color: white;border-radius: 5px;">
                                    <i class="icon-search4 text-muted text-size-base " style="color: white;font-size: 10px; "></i> &nbsp;&nbsp; Detail
                                </a>
                            </div>
                            </li>`;

                data_per.push(data_i)

            }
            $("#dataperb").html(data_per)

            var x = window.matchMedia("(min-width: 700px)")
            if (x.matches) { // If media query matches
                $(".search_list").css('display', 'none')

                $.fn.dataList = function(options) {
                    this.each(function() {
                        var $table = $(this);
                        if ($table.is('ul')) {
                            var $ul = $table;
                            $table = $ul.wrap('<table><tbody/></table').closest('table');
                            $ul.find('li').wrap('<tr></tr>').contents().unwrap();
                            $ul.find('div').wrap('<td><td/>').contents().unwrap();
                            $ul.contents().unwrap()
                            $table.prepend(`<thead><tr><th>No.</th>
                                <th>Sarana Perbaikan</th>
                                <th>Nama</th>
                                <th>Alamat</th>
                                <th>Status</th>
                                <th>Tanggal Mulai</th>
                                <th>Tanggal Selesai</th>
                                <th>Keterangan</th>
                                </tr></thead>`);
                        }
                        $table.dataTable(options);
                    });
                }
                $('.datatab').dataList({
                    "pageLength": 15,
                    autoWidth: false,
                    columnDefs: [{
                        orderable: false,
                        width: '20px',
                        targets: [0],
                    }, ],
                    dom: '<"float-left "B>frtip',
                    language: {
                        search: ' _INPUT_',
                        searchPlaceholder: 'Data Perbaikan...',
                        lengthMenu: '<span>Show:</span><hr> _MENU_',
                        paginate: {
                            'first': 'First',
                            'last': 'Last',
                            'next': '&rarr;',
                            'previous': '&larr;'
                        }
                    },
                });
                $('.datatab').DataTable({
                    autoWidth: false,
                    columnDefs: [{
                        orderable: false,
                        width: '20px',
                        targets: [0],

                    }, {
                        orderable: false,
                        width: '20px',
                        targets: [6],

                    }, {
                        orderable: false,
                        width: '20px',
                        targets: [7],

                    }, ],
                    dom: '<"float-left "B>frtip',
                    language: {
                        search: ' _INPUT_',
                        searchPlaceholder: 'Data Perbaikan...',
                        lengthMenu: '<span>Show:</span><hr> _MENU_',
                        paginate: {
                            'first': 'First',
                            'last': 'Last',
                            'next': '&rarr;',
                            'previous': '&larr;'
                        }
                    },
                    drawCallback: function() {
                        $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
                    },
                    preDrawCallback: function() {
                        $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
                    }
                });
            } else {
                $(".search_list").css('display', 'block')
                $("#download_perbaikan").css('display', 'none')
                    //            document.querySelector("#perbaikan-dashboard\\  > div > div.container-detached > div > ul > li > div:nth-child(1)").style.display = 'none';
                    //$('.datatab').dataTable({
                    //    "pageLength": 15
                    //});
            }
        }
    })
})

function loaddetailid(ido,id) {
    console.log('a')
    console.log(ido,id)
    $(".map_detail_p").html(``)
    var isObject = {};
    isObject.ido = ido;
    isObject.id = id;
    $("#iduser ").val(ido)

    $.ajax({
        url: "loadDetail",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            $("#modal_detail_perbaikan").modal('show')

            $(".map_detail_p").html(`<div id="map_detail_perbaikan" style=" position: relative; height: 220px; width: 90%; border-radius: 5px; ">`)

            var map_detail_perbaikan = L.map('map_detail_perbaikan', {
                editable: true,
                zoomControl: false,
                drawControl: true
            }).setView([-4.125826277307029, 104.1881561279297], 10);

            L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off', {
                maxZoom: 21,
                minZoom: 4,
            }).addTo(map_detail_perbaikan);


            setTimeout(function() {
                map_detail_perbaikan.invalidateSize();
            }, 500);

            nama_delete_perb_det = data[0]['name'];
            tipe_delete_perb_det = data[0]['type'];
            

            if (data.length === 0) {
                $(".nama_detail").text("Null");
                $(".type_detail ").html("Null");
                $(".tanggal_perbaikan_detail ").html("Null")
                    //                    $(".anggaran_detail ").html("Null")
                    //                    $(".penanggung_jawab_detail ").html("Null")
                    //                    $(".penanggung_jawab_lapangan_detail ").html("Null")
                    //                    $(".kontraktor_detail ").html("Null")
                $(".panjang_jalan_detail ").html("Null")
                $(".lebar_jalan_detail ").html("Null")
                $(".proposal_detail ").html(`
                    <a href="static/media/proposal/null" id="downloadproposal">
                        <img src="static/img/icon-1/proposal.svg" alt=" " style="height: 80px;width: 80px; ">
                    </a>`);
                
                
                $(".bukti_detail_perbaikan").html(`
                    <a href="static/media/bukti_penyelesaian/null" onclick="viewBukti() " id="view-bukti ">
                        <img src="static/img/icon-1/bukti.svg" alt=" " style="height: 70px;
                        width: 50px;">
                    </a>`);

                $(".tombol-edit-detail-jln").html(`
                <a href="#" tooltip="Edit" id="btn_edit_det_perb" data-toggle="modal" data-target="#modal_det_perb_edit" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                    <i class="icon-pencil5"></i> EDIT
                </a>`);
                $(".tombol-delete-detail-jln").html(`
                <a href="#" id="btn_delete_det_perb" data-toggle="modal" data-target="#modal_det_perb_delete" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                    <i class="icon-eraser2"></i> DELETE
                </a>`);

            } else {
                // console.log(data[0]['jenis'])
                if (data[0]['jenis'] == 'jalan') {
                    var proposal = ``;
                    if (data[0]['proposal'] == 'None'){
                        proposal = `<span style="background-color:#b81a1a; border-radius: 2px; ">&nbsp; Belum Diupload &nbsp;</span>`;
                    } else {
                        proposal = `
                        <a href="static/media/proposal/` + data[0]['proposal'] + `" target="_blank" "id="downloadproposal">
                            <img src="static/img/icon-1/proposal.svg" alt=" " style="height: 65px;width: 65px; ">
                        </a>`;
                    }
                    var buktilah = ``;
                    if (data[0]['bukti_selesai'] == 'None'){
                        buktilah = `<span style="background-color:#b81a1a; border-radius: 2px; ">&nbsp; Belum Diupload &nbsp;</span>`;
                    } else {
                        buktilah = `
                        <a href="static/media/bukti_penyelesaian/` + data[0]['bukti_selesai'] + `" target="_blank" id="view-bukti">
                            <img src="static/img/icon-1/bukti.svg" alt=" " style="height: 70px;width: 50px;">
                        </a>`;
                    }
                    var lengkapidong = ``;
                    var lengkapidonghapus = ``;
                    if ((data[0]['anggaran'] == 0) || (data[0]['pj'] == "") || (data[0]['pj_lapangan'] == "") || (data[0]['kontraktor'] == "") || (data[0]['sumber_dana'] == "") || 
                    (data[0]['tgl_disetujui'] == '0001-01-01') || (data[0]['tgl_selesai'] == '0001-01-01') || (data[0]['tgl_perbaikan'] == '0001-01-01') || (data[0]['proposal'] == 'None') || (data[0]['bukti_selesai'] == 'None')){
                        lengkapidong = `
                            <div class="text-center" style="background-color: #5A9AFB;height: 40px;bottom: 2px;right: 5px;border: 1pt solid rosybrown;border-radius: 8px;">
                                <a href="#" title="Lengkapi Data" id="btn_edit_det_perb" onclick="edit_perb_det_f(`+id+`,`+ido+`)" data-toggle="modal" data-target="#modal_det_perb_edit" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                                    Lengkapi
                                </a>    
                            </div>
                        `;
                        lengkapidonghapus = `
                            <div class="text-center" data-toggle="modal" data-target="#modal_bangunan_delete" style="background-color: indianred;height: 40px;bottom: 2px;right: 50px;border: 1pt solid rosybrown;border-radius: 10px;">
                                <a href="#" title="Hapus Data" id="btn_delete_det_perb" onclick="delete_perb_det_f(`+id+`,`+ido+`)" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                                    <i class="icon-eraser2"></i> Hapus
                                </a>       
                            </div>
                        `;
                    }
                    var dt = new Date();
                    var today = dt.getFullYear() + "-" + ((dt.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) + "-" + dt.getDate();

                    if((data[0]['tgl_perbaikan'] == '0001-01-01') || (data[0]['tgl_selesai'] == '0001-01-01') || (data[0]['tgl_disetujui'] == '0001-01-01')){
                        // status = `<span style="background-color:#b81a1a; border-radius: 2px;">&nbsp; Dalam Perencanaan &nbsp;</span>`;
                        if(data[0]['tgl_perbaikan'] == '0001-01-01'){
                            lengkapidonghapus = `
                            <div class="text-center" data-toggle="modal" data-target="#modal_bangunan_delete" style="background-color: indianred;height: 40px;bottom: 2px;right: 50px;border: 1pt solid rosybrown;border-radius: 10px;">
                                <a href="#" title="Hapus Data" id="btn_delete_det_perb" onclick="delete_perb_det_f(`+id+`,`+ido+`)" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                                    <i class="icon-eraser2"></i> Hapus
                                </a>       
                            </div>
                        `;
                        }
                        if(data[0]['tgl_selesai'] == '0001-01-01'){
                            lengkapidonghapus = `
                            <div class="text-center" data-toggle="modal" data-target="#modal_bangunan_delete" style="background-color: indianred;height: 40px;bottom: 2px;right: 50px;border: 1pt solid rosybrown;border-radius: 10px;">
                                <a href="#" title="Hapus Data" id="btn_delete_det_perb" onclick="delete_perb_det_f(`+id+`,`+ido+`)" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                                    <i class="icon-eraser2"></i> Hapus
                                </a>       
                            </div>
                        `;
                        }
                        // if(data[i].tgl_disetujui != '0001-01-01'){}
                    } else {
                        if (today < data[0]['tgl_perbaikan']){
                            lengkapidonghapus = `
                            <div class="text-center" data-toggle="modal" data-target="#modal_bangunan_delete" style="background-color: indianred;height: 40px;bottom: 2px;right: 50px;border: 1pt solid rosybrown;border-radius: 10px;">
                                <a href="#" title="Hapus Data" id="btn_delete_det_perb" onclick="delete_perb_det_f(`+id+`,`+ido+`)" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                                    <i class="icon-eraser2"></i> Hapus
                                </a>       
                            </div>`;
                        }
                        else if((today >= data[0]['tgl_perbaikan'])&&(today <= data[0]['tgl_selesai'])){
                            lengkapidonghapus = ``;
                        }
                        else if(today > data[0]['tgl_selesai']){
                            lengkapidonghapus = ``;
                        }
                    }

                    // lengkapidonghapus = `
                    //         <div class="text-center" data-toggle="modal" data-target="#modal_bangunan_delete" style="background-color: indianred;height: 40px;bottom: 2px;right: 50px;border: 1pt solid rosybrown;border-radius: 10px;">
                    //             <a href="#" title="Hapus Data" id="btn_delete_det_perb" onclick="delete_perb_det_f(`+id+`,`+ido+`)" class="btn" style="border-bottom-left-radius: 8px;border-top-right-radius: 8px;width: 100%;height: 100%;bottom: 0px;color: white;">
                    //                 <i class="icon-eraser2"></i> Hapus
                    //             </a>       
                    //         </div>
                    //     `;
                    

                    $(".nama_detail").html(data[0]['name']);
                    $(".alamat_detail").html(data[0]['desa']+`, `+data[0]['kecamatan']);
                    $(".type_detail ").html(data[0]['type']);
                    $(".tanggal_perbaikan_detail ").text(data[0]['tgl_perbaikan']);
                    $(".tanggal_selesai_detail ").html(data[0]['tgl_selesai'])
                        //$(".penanggung_jawab_detail ").html(data[0]['pj'])
                        //$(".penanggung_jawab_lapangan_detail ").html(data[0]['pj_lapangan'])
                        //$(".kontraktor_detail ").html(data[0]['kontraktor'])
                    $(".panjang_jalan_detail ").html(data[0]['panjang']);
                    $(".lebar_jalan_detail ").html(data[0]['lbr_jln_reno']);
                    $(".proposal_detail ").html(proposal);
                    
                    
                    $(".bukti_detail_perbaikan").html(buktilah);

                    $(".tombol-edit-detail-jln").html(lengkapidong);
                    $(".tombol-delete-detail-jln").html(lengkapidonghapus);

                    $('.isi_detail_cek_jalan').show()
                    $('.map_detail_p_jalan').show()

                    map_detail_perbaikan.setView([data[0]['geometry']['coordinates'][0][0][1], data[0]['geometry']['coordinates'][0][0][0]], 18)

                    var myLines = [data[0]['geometry']];

                    var geo_jalan_perbaikan = L.geoJson(data[0]['geometry'], {
                        style: function(feature) {
                            return {
                                color: "#FAFA00",
                                weight: 10,
                                opacity: 2,
                                zIndex: 1001
                            };
                        }
                    }).addTo(map_detail_perbaikan);
                } else if (data[0]['jenis'] == 'bangunan') {
                    $(".nama_detail").html(data[0]['name']);
                    $(".type_detail ").html(data[0]['type'])
                    $(".tanggal_perbaikan_detail ").text(data[0]['tgl_perbaikan'])
                        // $(".anggaran_detail ").html(data[0]['anggaran'])
                        // $(".penanggung_jawab_detail ").html(data[0]['pj'])
                        // $(".penanggung_jawab_lapangan_detail ").html(data[0]['pj_lapangan'])
                        // $(".kontraktor_detail ").html(data[0]['kontraktor'])
                        //$(".proposal_detail ").html(`
                        //    <a href="static/media/proposal/` + data[0]['proposal'] + `" target="_blank" "id="downloadproposal">
                        //        <img src="{% static 'img/icon-1/proposal.svg' %} " alt=" " style="height: 65px;width: 65px; ">
                        //    </a>`);
                    $(".judul_panjang_jalan_detail ").html('Jenis Perbaikan')
                    $(".panjang_jalan_detail ").html(data[0]['jenis_perbaikan'])
                    $('.isi_detail_cek_jalan').hide()
                    $('.map_detail_p_jalan').hide()


                    //$(".bukti_detail_perbaikan").html(`
                    //    <a href="static/media/bukti_penyelesaian/` + data[0].bukti_selesai + `" target="_blank" id="view-bukti">
                    //        <img src="{% static 'img/icon-1/bukti.svg' %} " alt=" " style="height: 70px;
                    //        width: 50px;">
                    //    </a>`);
                }
            }
        }
    });
};

//    var element = $("#map_detail_perbaikan"); // global variable
//    var getCanvas; // global variable
//
//    $("#download_map").on('click', function() {
//        html2canvas(element, {
//            onrendered: function(canvas) {
//                $("#previewImage").append(canvas);
//                getCanvas = canvas;
//            }
//        });
//
//        var imgageData = getCanvas.toDataURL("image/png");
//        // Now browser starts downloading it instead of just showing it
//        var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
//        $("#download_map").attr("download", "image.png").attr("href", newData);
//    });




function download_user_list(type, fn, dl) {
    $.ajax({
        url: "api/user-data",
        dataType: 'json',

        success: function(data) {

            var thead = `<thead>
                            <tr>
                                <th>No.</th>
                                <th>Id user</th>
                                <th>Username</th>
                                <th>Nama</th>
                                <th>Email</th>
                                <th>Last Login</th>
                                <th>Status</th>
                            </tr>
                        </thead>`
            var data_user = []
            var number = 0;

            for (var i = 0; i < data['data'].length; i++) {

                number += 1;
                var id = data['data'][i]['id'];
                var name = data['data'][i]['name'];
                var username = data['data'][i]['username'];
                var group = data['data'][i]['group'];
                var email = data['data'][i]['email'];
                var last = data['data'][i]['last'];
                var isactive = data['data'][i]['isactive'];


                var data_gab = `<tr>
                    <td>` + number + `</td>
                    <td>` + id + `</td>
                    <td>` + username + `</td>
                    <td>` + name + `</td>
                    <td>` + email + `</td>
                    <td>` + last + `</td>
                    <td>` + isactive + `</td>
                </tr>`;
                data_user.push(data_gab)
            }

            var tbody = `<tbody>
                            ` + data_user + `
                        </tbody>`;

            $("#table_downloader").html(thead + tbody)

            var elt = document.getElementById('table_downloader');

            var wb = XLSX.utils.table_to_book(elt, {
                sheet: "sheet1"
            });
            return dl ?
                XLSX.write(wb, {
                    bookType: type,
                    bookSST: true,
                    type: 'base64'
                }) :
                XLSX.writeFile(wb, fn || ('data_user.' + (type || 'xlsx')));


        }
    })
}

function download_all(type, fn, dl) {
    $.ajax({
        url: "api/download_perbaikan_data",
        dataType: 'json',

        success: function(data) {

            var thead = `<thead>
                <tr>
                    <th>No.</th>
                    <th>Id perbaikan</th>
                    <th>Jenis yang diperbaiki</th>
                    <th>Nama</th>
                    <th>Tipe</th>
                    <th>Panjang (Jika perbaikan jalan)</th>
                    <th>Tanggal Pembuatan/Peresmian</th>
                    <th>Tanggal Perbaikan</th>
                    <th>Tanggal Selesai</th>
                    <th>Anggaran</th>
                    <th>Penanggung Jawab</th>
                    <th>Penanggung Jawab Lapangan</th>
                    <th>Kontraktor</th>
                    <th>Panjang yang diperbaiki</th>
                    <th>Lebar yang diperbaiki</th>
                </tr>
            </thead>`
            var data_user = []
            var number = 0;

            for (var i = 0; i < data['data'].length; i++) {
                number += 1;
                var id = data['data'][i]['id'];
                var jenis_perbaikan = data['data'][i]['jenis_perbaikan'];
                var nama = data['data'][i]['nama'];
                var tipe = data['data'][i]['tipe'];
                var panjang = data['data'][i]['panjang'];
                var tgl_pembuatan = data['data'][i]['tgl_pembuatan'];
                var tgl_perbaikan = data['data'][i]['tgl_perbaikan'];
                var tgl_selesai = data['data'][i]['tgl_selesai'];
                var anggaran = data['data'][i]['anggaran'];
                var pj = data['data'][i]['pj'];
                var pj_lapangan = data['data'][i]['pj_lapangan'];
                var kontraktor = data['data'][i]['kontraktor'];
                var panjang_per = data['data'][i]['panjang_per'];
                var lebar_per = data['data'][i]['lebar_per'];



                var data_gab = `<tr>
                                <td>` + number + `</td>
                                <td>` + id + `</td>
                                <td>` + jenis_perbaikan + `</td>
                                <td>` + nama + `</td>
                                <td>` + tipe + `</td>
                                <td>` + panjang + `</td>
                                <td>` + tgl_pembuatan + `</td>
                                <td>` + tgl_perbaikan + `</td>
                                <td>` + tgl_selesai + `</td>
                                <td>` + anggaran + `</td>
                                <td>` + pj + `</td>
                                <td>` + pj_lapangan + `</td>
                                <td>` + kontraktor + `</td>
                                <td>` + panjang_per + `</td>
                                <td>` + lebar_per + `</td>
                                
                            </tr>`;
                data_user.push(data_gab)
            }

            var tbody = `<tbody>
                ` + data_user + `
            </tbody>`;

            $("#table_downloader").html(thead + tbody)

            var elt = document.getElementById('table_downloader');

            var wb = XLSX.utils.table_to_book(elt, {
                sheet: "sheet1"
            });
            return dl ?
                XLSX.write(wb, {
                    bookType: type,
                    bookSST: true,
                    type: 'base64'
                }) :
                XLSX.writeFile(wb, fn || ('data_perbaikan.' + (type || 'xlsx')));
        }
    });


}

var $content, $modal, $apnData, $modalCon;

$content = $(".min");

$(".mdlFire").click(function(e) {

    e.preventDefault();

    var $id = $(this).attr("data-target");
});

$(".modalMinimize").on("click", function() {
    $modalCon = $(this).closest(".mymodal").attr("id");
    $apnData = $(this).closest(".mymodal");
    $modal = "#" + $modalCon;
    $(".modal-backdrop").addClass("display-none");
    $($modal).toggleClass("min");

    if ($($modal).hasClass("min")) {
        $(".minmaxCon").append($apnData);
        $(this).find("i").toggleClass('fa-minus').toggleClass('fa-clone');
    } else {
        $(".container").append($apnData);
        $(this).find("i").toggleClass('fa-clone').toggleClass('fa-minus');
    };
});

$("button[data-dismiss='modal']").click(function() {
    $(this).closest(".mymodal").removeClass("min");
    $(".container").removeClass($apnData);
    $(this).next('.modalMinimize').find("i").removeClass('fa fa-clone').addClass('fa fa-minus');
});

$("#btn-hide-all").click(function() {
    $("#button_keterangan").removeClass("active");
    $("#manage_perbaikan").removeClass("active");
    $("#panel-sm").removeClass("active");
    $("#panel-sm2").removeClass("active");
    $("#panel-sm").css('display', 'none');
    $(this).css('display', 'none');
    $(this).removeClass("hid");
});

function btn_hid_all_close() {
    $("#button_keterangan").removeClass("active");
    $("#manage_perbaikan").removeClass("active");
    $("#panel-sm").removeClass("active");
    $("#panel-sm2").removeClass("active");
    $(this).css('display', 'none');
    $(this).removeClass("hid");
};

$("#keterangan_button").click(function() {
    $("#btn-hide-all").css('display', 'block');
    // $("#btn-hide-all").toggleClass("hid");
});

$("#perbaikan_manage").click(function() {
    $("#btn-hide-all").css('display', 'block');
    // $("#btn-hide-all").toggleClass("hid");
});

function gas_all() {
    var checkBox = document.getElementById("po_all");
    if (document.getElementById("po_all").checked == true) {
        document.getElementById("knt_adm").checked = true;
        document.getElementById("lyn_kes").checked = true;
        document.getElementById("pus").checked = true;
        document.getElementById("rusak").checked = true;
        document.getElementById("ibdh").checked = true;
        document.getElementById("dididik").checked = true;
        document.getElementById("tasiun").checked = true;
        document.getElementById("caheum").checked = true;
        document.getElementById("cabud").checked = true;
        document.getElementById("gardu").checked = true;
        k_adm()
        l_kes()
        pks()
        rs()
        fiksi()
        didik()
        sthall()
        temanggung()
        cb100()
        gl100()
    } else if (document.getElementById("po_all").checked == false) {
        document.getElementById("knt_adm").checked = false;
        document.getElementById("lyn_kes").checked = false;
        document.getElementById("pus").checked = false;
        document.getElementById("rusak").checked = false;
        document.getElementById("ibdh").checked = false;
        document.getElementById("dididik").checked = false;
        document.getElementById("tasiun").checked = false;
        document.getElementById("caheum").checked = false;
        document.getElementById("cabud").checked = false;
        document.getElementById("gardu").checked = false;
        k_adm()
        l_kes()
        pks()
        rs()
        fiksi()
        didik()
        sthall()
        temanggung()
        cb100()
        gl100()
    }
}

// function gas_poin(){
//     document.getElementById("po_all").checked == true;
//     k_adm()
//     l_kes()
//     pks()
//     rs()
//     fiksi()
//     didik()
//     sthall()
//     temanggung()
//     cb100()
//     gl100()
// }

// gas_poin()

function destroymodper() {
    $("#modal_detail_perbaikan").modal('hide')
}

$(".search_list").on('input', function() {
    var v = $(".inp_search_list").val()
    $.ajax({
        url: "api/search_list_perbaikan",
        dataType: 'json',
        data: {
            'v_list': v
        },
        success: function(data) {
            var data_perbaikan = []
            var number = 0;

            for (var i = 0; i < data.length; i++) {

                number += 1;
                var name_perbaikan = data[i][0];
                var id_object = data[i][1];
                var name = data[i][2];
                var type = data[i][3];
                var tgl_perbaikan = data[i][4];
                var anggaran = data[i][5];
                var tgl_selesai = data[i][6];
                var idbenar = data[i][9];

                var data_gab = `<li class="media panel panel-body stack-media-on-mobile" style="background: transparent;border: none;color: white;">
                    <div>
                        ` + number + `
                    </div>
                    <div>
                        ` + name_perbaikan + `
                    </div>
                    <div>
                        ` + name + `
                    </div>
                    <div>
                        ` + type + `
                    </div>
                    <div>
                        ` + tgl_perbaikan + `
                    </div>
                    <div>
                        ` + tgl_selesai + `
                    </div>
                    <div>
                        <a class="btn mdlFire " onclick="loaddetailid(`+id_object+`,`+idbenar+`) " data-toggle="modal" data-target="#modal_detail_perbaikan" style="background-color: #5A9AFB;color: white;border-radius: 5px;height: 25px; ">
                            <span>
                                <i class="icon-search4 text-muted text-size-base " style="color: white;font-size: 10px; "></i>
                                &nbsp;&nbsp;
                                    Detail
                            </span>
                            
                        </a>
                    </div>
                </li>`;
                data_perbaikan.push(data_gab)
            };

            $(".datatab").html(data_perbaikan)
        }
    });

});

function delete_perb_det_f(id, id_obj ) {
    // var idparam = param;
    // console.log(idparam, nama_delete_perb_det, tipe_delete_perb_det)
    // $('#nama_perb_det_delete').val(nama_delete_perb_det)
    // $('#type_perb_det_delete').val(tipe_delete_perb_det)

    swal({
        title: "Perhatian",
        text: "Setelah Terhapus Data tidak dapat dikembalikan",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete",
        cancelButtonText: "No, cancel",
        closeOnConfirm: false,
        closeOnCancel: true
      },
        function (isConfirm) {
            if (isConfirm) {
                var data = new FormData();
                data.append('id_perb', id)
                data.append('id_perb_object', id_obj)

                $.ajax({
                    url: "api/deletedataperb",
                    data: data,
                    dataType: 'json',
                    type: 'POST',
                    processData: false,
                    contentType: false,
                    success: function(data) {
                        loaderPage(false);
                        let response = data;
                        if (response.code == 0) {
                            swal({
                                title: response.info,
                                text: response.data,
                                type: "success",
                                icon: "success",
                                confirmButtonColor: "#00BCD4"
                            }, function() {
                                location.reload()
                            })
                        } else {
                            swal({
                                title: response.info,
                                text: response.data,
                                type: "warning",
                                icon: "error",
                                confirmButtonColor: "#00BCD4"
                            })
                        }
                    }
                })
                
            } else {
                // swal("Cancelled", "Your imaginary file is safe :)", "error");
            }
        }
    );

}

function edit_perb_det_f(id, id_obj) {
    var isObject = {};
    isObject.ido = id_obj;
    isObject.id = id;

    $.ajax({
        url: "loadDetail",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            console.log(data[0])
            var namobj = data[0]['name']
            $("#anggaran_perb_det_edit").val(data[0]['anggaran']);
            $("#sudan_perb_det_edit").val(data[0]['sumber_dana']);
            $("#pihak_perb_det_edit").val(data[0]['pj']);
            $("#pjlap_perb_det_edit").val(data[0]['pj_lapangan']);
            $("#kontraktor_perb_det_edit").val(data[0]['kontraktor']);

            if (data[0]['tgl_disetujui'] != '0001-01-01'){
                $('#tgldisetujui_perb_det_edit').val(data[0]['tgl_disetujui'])
            }
            if (data[0]['tgl_perbaikan'] != '0001-01-01'){
                $('#tglmulaiperbaikan_perb_det_edit').val(data[0]['tgl_perbaikan'])
            }
            if (data[0]['tgl_selesai'] != '0001-01-01'){
                $('#tglselesaiperbaikan_perb_det_edit').val(data[0]['tgl_selesai'])
            }            

            $('#propos_val_det_perb_edit').val(data[0]['proposal']);
            $('#buksel_val_det_perb_edit').val(data[0]['bukti_selesai']);

            var propos = 0;
            var buksel = 0;
            if (data[0]['proposal'] != 'None'){
                $('#proposal_perb').append(`<span style="background-color:#35bd6b; border-radius: 2px;">&nbsp; Sudah Diupload &nbsp;</span>`)
                // $('proposal_perb_det_edit').attr('disabled');
                // proposal = `<span style="background-color:#b81a1a; border-radius: 2px;">&nbsp; Belum Diupload &nbsp;</span>`;
                
                // $('#select_file').html(filename);
                // propos = 1;
            }

            if (data[0]['bukti_selesai'] != 'None'){
                $('#buktiselesai_perb').append(`<span style="background-color:#35bd6b; border-radius: 2px;">&nbsp; Sudah Diupload &nbsp;</span>`)
                // $('buktiselesai_perb_det_edit').attr('disabled');
                // proposal = `<span style="background-color:#b81a1a; border-radius: 2px;">&nbsp; Belum Diupload &nbsp;</span>`;
                
                // buksel = 1;
            }

            $('#anggaran_perb_det_edit').on('input', function() {
                $('#anggaran_perb_det_edit').on('change click keyup input paste',(function (event) {
                    $(this).val(function (index, value) {
                        return value.replace(/(?!\.)\D/g, "").replace(/(?<=\..*)\./g, "").replace(/(?<=\.\d\d).*/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                    });
                }));
            });

            $("#update_perb").click(function() {
                var anggaran = $("#anggaran_perb_det_edit").val();
                var sumber_dana = $("#sudan_perb_det_edit").val();
                var pihak_sah = $("#pihak_perb_det_edit").val();
                var pj_lap = $("#pjlap_perb_det_edit").val();
                var kontraktor = $("#kontraktor_perb_det_edit").val();
                var tglset = $('#tgldisetujui_perb_det_edit').val();
                var tglper = $('#tglmulaiperbaikan_perb_det_edit').val()
                var tglsel = $('#tglselesaiperbaikan_perb_det_edit').val();
                var propo = $('#propos_val_det_perb_edit').val();
                var bukse = $('#buksel_val_det_perb_edit').val();

                if ((anggaran != "0" || anggaran != "") && (sumber_dana != "") && (pihak_sah != "") && 
                (pj_lap != "") && (kontraktor != "") && 
                (tglset!= '') && (tglsel != '') && 
                (tglper != '') ){
                    console.log(anggaran.replace(/,/g,''))

                    var idperb = id;
                    var idobj  = id_obj;
                    var data = new FormData();
                    data.append("file_proposal", $("input[id^='proposal_perb_det_edit']")[0].files[0]);
                    data.append("file_bukti", $("input[id^='buktiselesai_perb_det_edit']")[0].files[0]);
                    data.append("csrfmiddlewaretoken", "{{ csrf_token }}");
                    data.append('id_perb', idperb)
                    data.append('id_obj', idobj)
                    data.append('namobj', namobj)

                    data.append('anggaran', anggaran.replace(/,/g, ""))
                    data.append('sumber_dana', sumber_dana)
                    data.append('pihak_sah', pihak_sah)
                    data.append('pj_lap', pj_lap)
                    data.append('kontraktor', kontraktor)
                    data.append('tgl_disetujui', tglset)
                    data.append('tgl_perbaikan', tglper)
                    data.append('tgl_selesai', tglsel)
                    
                    data.append('proposal', propo)
                    data.append('bukti_selesai', bukse)

                    $.ajax({
                        url: "api/editperb",
                        data: data,
                        dataType: 'json',
                        type: 'POST',
                        processData: false,
                        contentType: false,
                        success: function(data) {
                            let response = data
                            if (response.status == 0) {
                                swal({
                                    title: response.info,
                                    text: response.data,
                                    type: "success",
                                    icon: "success",
                                    confirmButtonColor: "#00BCD4"
                                }, function() {
                                    location.reload();
                                })
                            } else {
                                swal({
                                    title: 'Error',
                                    text: 'Pastikan Semua Data Terisi',
                                    type: "warning",
                                    icon: "error",
                                    confirmButtonColor: "#00BCD4"
                                })
                            }
                        }
                    })
                    
                    
                } else {
                    swal({
                        title: "Perhatian",
                        text: "Semua data harus diisi",
                        type: "warning",
                        icon: "error",
                        confirmButtonColor: "#00BCD4"
                    })
                }
            });

            
        }
    });
}