$("#upload_image").change(function() {
    loaderPage(true)
    readURL(this);

    const fileupload1 = $(this).prop('files')[0];

    var formData = new FormData();

    formData.append("id", $("#iduseredt").val());
    formData.append("inifile", fileupload1)

    $.ajax({
        url: "editpp",
        data: formData,
        dataType: 'json',
        type: 'POST',
        processData: false,
        contentType: false,
        success: function(data) {
            let response = data
            if (response.code == 0) {
                swal({
                    title: response.info,
                    text: response.data,
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                }).then((isConfirm) => {
                    location.reload()
                })
            } else {
                swal({
                    title: 'Error',
                    text: 'Hubungi Developer',
                    type: "warning",
                    icon: "error",
                    confirmButtonColor: "#00BCD4"
                })
            }

        }
    })
});

function getdetailper(id) {

    $.ajax({
        url: "apps/get-detail-perbaikan",
        data: {
            'id': id
        },
        dataType: 'json',

        success: function(data) {

            var map_detail_perbaikan = L.map('map_detail_perbaikan_dash', {
                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);


            if (data.length === 0) {
                $(".nama_detail_dash").text("Null");
                $(".type_detail_dash").html("Null");
                $(".tanggal_perbaikan_detail_dash").html("Null")
                $(".anggaran_detail_dash").html("Null")
                $(".penanggung_jawab_detail_dash").html("Null")
                $(".penanggung_jawab_lapangan_detail_dash").html("Null")
                $(".kontraktor_detail_dash").html("Null")
                $(".panjang_jalan_detail_dash").html("Null")
                $(".lebar_jalan_detail_dash").html("Null")
                $(".proposal_detail_dash").html(`
                        <a href="media/proposal/null" id="downloadproposal ">
                            <img src="{% static 'img/icon-1/proposal.svg' %} " alt=" " style="height: 65px;width: 65px; ">
                        </a>`);


                $(".bukti_detail_perbaikan_dash").html(`
                        <a href="media/bukti_penyelesaian/null" onclick="viewBukti() " id="view-bukti ">
                            <img src="{% static 'img/icon-1/bukti.svg' %} " alt=" " style="height: 70px;
                            width: 50px;">
                        </a>`);

            } else {
                $(".nama_detail_dash").html(data[0]['name']);
                $(".type_detail_dash").html(data[0]['type'])
                $(".tanggal_perbaikan_detail_dash").text(data[0]['tgl_perbaikan'])
                $(".anggaran_detail_dash").html(data[0]['anggaran'])
                $(".penanggung_jawab_detail_dash").html(data[0]['pj'])
                $(".penanggung_jawab_lapangan_detail_dash").html(data[0]['pj_lapangan'])
                $(".kontraktor_detail_dash").html(data[0]['kontraktor'])
                $(".panjang_jalan_detail_dash").html(data[0]['panjang'])
                $(".lebar_jalan_detail_dash").html(data[0]['lbr_jln_reno'])
                $(".proposal_detail_dash").html(`
                        <a href="media/proposal/` + data[0]['proposal'] + ` target="_blank" "id="downloadproposal">
                            <img src="{% static 'img/icon-1/proposal.svg' %} " alt=" " style="height: 65px;width: 65px; ">
                        </a>`);


                $(".bukti_detail_perbaikan_dash").html(`
                        <a href="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>`);

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



        }
    });
};

$("#pengaturan_btn").click(function() {
    $.ajax({
        url: "api/user-data",
        dataType: 'json',

        success: function(data) {
            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'];

                if (isactive == true) {
                    var isac = `<span class="label label-success">Active</span>`
                } else {
                    var isac = `<span class="label label-danger">Inactive</span>`
                }


                var data_gab = `<tr>
                        <td>` + number + `</td>
                        <td>` + id + `</td>
                        <td>` + username + `</td>
                        <td>` + email + `</td>
                        <td>` + last + `</td>
                        <td>` + isac + `</td>
                        <td class="text-center">
                            <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 onclick="switchuserstatus('` + id + `, ` + isactive + `')"><i class="icon-user-block"></i> Switch user status</a></li>
                                        <li><a onclick="loaduserbyid('` + id + `')"><i class="icon-users"></i> Edit user</a></li>
                                    </ul>
                                </li>
                            </ul>
                        </td>

                    </tr>`;
                data_user.push(data_gab)
            };
            $("#tbody_user_list").html(data_user)

            var data_point = []
            var number2 = 0;

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

                number2 += 1;
                var id = data['point'][i]['id'];
                var nama_tempat = data['point'][i]['nama_tempat'];
                var alamat = data['point'][i]['alamat'];
                var luas = data['point'][i]['luas'];
                var pj = data['point'][i]['pj']
                var db = data['point'][i]['table']

                var data_gab = `<tr>
                        <td>` + number2 + `</td>
                        <td>` + nama_tempat + `</td>
                        <td>` + alamat + `</td>
                        <td>` + luas + `</td>
                        <td>` + pj + `</td>
                        <td class="text-center " style="padding: 0px;">
                            <div class="row">
                                    <a class="btn mdlFire " data-toggle="modal" onclick="modal_detail_point_pengaturan('` + id + `','` + db + `')" style="padding: 10px 12px 10px 12px;">
                                        <div>
                                            <img src="static/img/icon-1/detailpoi.svg" alt="" style="margin-top: -4px;"><span>&nbsp;Detail</span>
                                        </div>
                                        
                                    </a>
    
                            </div>
                        </td>
                    </tr>`;
                data_point.push(data_gab)
            };



            $("#tbody_point_list").html(data_point)


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

                }, ],
                dom: '<"float-left "B>frtip',
                language: {
                    search: ' _INPUT_',
                    searchPlaceholder: 'Data User...',
                    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');
                }
            });

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

                }, ],
                dom: '<"float-left "B>frtip',
                language: {
                    search: ' _INPUT_',
                    searchPlaceholder: 'Data Tempat Penting...',
                    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');
                }
            });

        }
    });
})

function btnuserclick(evt) {
    var i, tabcontent, tablinks;

    tablinks = document.getElementsByClassName("tab-user");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    evt.currentTarget.className += " active";
}

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_point_list(type, fn, dl) {
    $.ajax({
        url: "api/user-data",
        dataType: 'json',

        success: function(data) {

            var thead = `<thead>
                            <tr>
                                <th>No.</th>
                                <th>Nama Tempat</th>
                                <th>Alamat</th>
                                <th>Luas Bangunan</th>
                                <th>Penanggung Jawab</th>
                            </tr>
                        </thead>`


            var data_point = []
            var number2 = 0;

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

                number2 += 1;
                var id = data['point'][i]['id'];
                var nama_tempat = data['point'][i]['nama_tempat'];
                var alamat = data['point'][i]['alamat'];
                var luas = data['point'][i]['luas'];
                var pj = data['point'][i]['pj']

                var data_gab = `<tr>
                        <td>` + number2 + `</td>
                        <td>` + nama_tempat + `</td>
                        <td>` + alamat + `</td>
                        <td>` + luas + `</td>
                        <td>` + pj + `</td>
                    </tr>`;
                data_point.push(data_gab)
            };

            var tbody = `<tbody>
                            ` + data_point + `
                        </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_point.' + (type || 'xlsx')));


        }
    })
}


function loadGroups(isSelect) {
    var isObject = {}
    console.log(isSelect)
    isObject.func_name = "loadGroups";

    $.ajax({
        url: "/getallGroups/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {

            let response = data;
            console.log(response)
            if (response.code == 0) {
                var groups = response.data;
                var html = `<option value="null" selected disabled>-- Pilih Group --</option>`;
                for (i in groups) {
                    if (isSelect) {
                        if (isSelect.length >= 1) {
                            for (j in isSelect) {
                                if (isSelect[j] == groups[i]) {
                                    html += `<option value="` + groups[i] + `" selected>` + groups[i] + `</option>`;
                                    console.log(groups[i])
                                } else {
                                    html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                                }
                            }
                        } else {
                            html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                        }



                    } else {
                        html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                    }

                }

                $("#select_group").html(html);
                $("#select_group_parent").html(html);
                console.log(html)
            } else {
                $("#select_group").html("group tidak tersedia");
                $("#select_group_parent").html("group tidak tersedia");
            }

        }
    });
}


function switchuserstatus(id, isactive) {
    var isObject = {}
    var params = id.split(",");

    isObject.id = params[0];
    isObject.stat = params[1].replace(" ", "");

    console.log(params)
    if (isObject.stat == "True") {
        var title = "Nonaktifkan";
        var text = "User tidak akan bisa login jika dinonaktifkan!";
    } else {
        var title = "Aktifkan";
        var text = "User dapat kembali login jika diaktifkan!";
    }

    swal({
        title: title + " user?",
        text: text,
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Ya!",
        cancelButtonText: "Tidak!",
        closeOnConfirm: false,
        closeOnCancel: false
    }).then((isConfirm) => {
        console.log(isConfirm)
        if (isConfirm.value) {

            $.ajax({
                url: "/switchStatus/",
                data: isObject,
                dataType: 'json',
                type: 'post',
                success: function(data) {

                    let response = data;

                    if (isObject.stat == "True") {
                        var inf = "dinonaktifkan"
                    } else {
                        var inf = "diaktifkan"
                    }
                    if (response.code == 0) {
                        swal({
                            title: "sukses",
                            text: "User berhasil " + inf,
                            type: "success",
                            icon: "success",
                            confirmButtonColor: "#00BCD4"
                        }).then((isok) => {
                            location.reload();
                        })
                    } else {
                        alert("no data in database")
                    }

                }
            });
        } else {
            swal("Dibatalkan", "User status tidak berubah", "error");
        }
    });

}

function loaduserbyid(id) {
    $("#modal_edit_user").modal("show")
    var isObject = {};
    $(".modstit").html("Update User")
    $("#inUsername").attr("disabled", true)

    isObject.id = id;
    $("#iduser").val(id)

    $.ajax({
        url: "/loadUserbyId/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {

            let response = data;

            if (response.code == 0) {
                var user = response.data;
                console.log(user)
                $("#inUsername").val(user.username);
                $("#inNameF").val(user.firstname);
                $("#inNameL").val(user.lastname);
                $("#inEmail").val(user.email);
                if (user.is_staff) {
                    $('input[name=isStaff][value=true]').attr('checked', true)
                } else {
                    $('input[name=isStaff][value=false]').attr('checked', true)
                }
                loadGroups(user.group)
                $("#modalAddButton").click()
            } else {

            }

        }
    });
}

function modal_detail_point_pengaturan(id, db) {
    $("#detail_right").html(``)
    $("#modal_detail_point_pengaturan").modal("show")

    $.ajax({
        url: "/api/load_point_id",
        data: {
            'idx': id,
            'db': db
        },
        dataType: 'json',
        success: function(data) {
            // console.log(data['result'][0][0])
            $("#detail_right").html(`<div>
                                        <span>
                                            Informasi Peta Lokasi
                                        </span>
                                    </div>
                                    <div id="maps_detail_p" style="height: 360px;outline: none;border-bottom-right-radius: 10px;margin-top: 10px;">
                                    </div>`)

            var map_poin_det = L.map('maps_detail_p', {
                editable: true,
                zoomControl: false,
                drawControl: true
            });

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

            $(".nama_point").html(data['result'][0][0]['properties']['f2'])
            $(".pj_bangunan").html(data['result'][0][0]['properties']['f5'])
            $(".luas_bangunan").html(data['result'][0][0]['properties']['f4'])

            var marker = L.marker([data['result'][0][0]['geometry']['coordinates'][1], data['result'][0][0]['geometry']['coordinates'][0]]).addTo(map_poin_det);
            map_poin_det.setView([data['result'][0][0]['geometry']['coordinates'][1], data['result'][0][0]['geometry']['coordinates'][0]], 17)
            document.querySelector("#maps_detail_p > div.leaflet-control-container > div.leaflet-top.leaflet-left").css("display", "none")

            setTimeout(function() {
                map_poin_det.invalidateSize();
            }, 1000);



            $("#edit_point_p").click(function() {
                $("#modal_edit_p_point").modal("show")


            })

        }
    });
}