$(function () {
    bsCustomFileInput.init();

    $("#exampleInputFile").change(function () {
        filePreview(this);
    });

    function filePreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $("#img").remove();
                $("#vall").remove();
                $(".gambar").append(
                    '<img src="' +
                        e.target.result +
                        '" width="100%" height="180px" id="img">'
                );
            };
            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#view").on("click", ".gambar", function () {
        var token = $("meta[name='csrf-token']").attr("content");
        var id = $(this).attr("data-id");
        $.ajax({
            type: "POST",
            url: "/view-gambar",
            dataType: "JSON",
            data: {
                id: id,
                _token: token,
            },
            success: function (data) {
                $("#uplgambar").modal("show");
                $("#gam").html(data.gambar);
                $("#idp").val(id);
                $("#gbrlama").val(data.gbrlama);
                $("#nama").val(data.nama);
            },
        });
    });

    $("#view").on("click", ".detail", function () {
        var token = $("meta[name='csrf-token']").attr("content");
        var id = $(this).attr("data-id");
        $.ajax({
            type: "POST",
            url: "/view-detail",
            data: {
                id: id,
                _token: token,
            },
            success: function (data) {
                $("#detail").modal("show");
                $("#vdetail").html(data);
            },
        });
    });

    $("#view").on("click", ".disc", function () {
        var token = $("meta[name='csrf-token']").attr("content");
        var id = $(this).attr("data-id");
        var nm = $(this).attr("data-nm");
        var diskon = $(this).attr("data-ds");
        $("#diskon").modal("show");
        $("#idpr").val(id);
        $("#nmp").html(nm);
        $("#disc").val(diskon);
        // $.ajax({
        //     type: "POST",
        //     url: "/view-detail",
        //     data: {
        //         id: id,
        //         _token: token,
        //     },
        //     success: function (data) {
        //         $("#detail").modal("show");
        //         $("#vdetail").html(data);
        //     },
        // });
    });

    // ceklis
    $("#cekall").change(function () {
        if ($(this).prop("checked")) {
            $(".ceklis").prop("checked", true);
        } else {
            $(".ceklis").prop("checked", false);
        }
    });

    $("#pilih_hapus").click(function () {
        var allVals = [];
        $(".ceklis:checked").each(function () {
            allVals.push($(this).val());
        });
        var token = $("meta[name='csrf-token']").attr("content");

        if (allVals.length <= 0) {
            Toast.fire({
                icon: "error",
                title: "Ceklis data yang akan dihapus!!!.",
            });
        } else {
            Swal.fire({
                title: "Pastikan dengan benar!",
                text: "Data yang anda pilih akan dihapus!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Ya, Hapus!",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: "DELETE",
                        url: "deleteall-produk",
                        data: {
                            allVals: allVals,
                            _token: token,
                        },
                        beforeSend: function () {
                            $("#pilih_hapus").html(
                                '<i class="fas fa-spinner fa-spin"></i> Tunggu..'
                            );
                            $("#pilih_hapus").attr("disabled", true);
                        },
                        success: function (data) {
                            // alert(data)
                            $("#pilih_hapus").html(
                                '<i class="fa fa-trash"></i>'
                            );
                            $("#pilih_hapus").attr("disabled", true);
                            Swal.fire({
                                icon: "success",
                                title: "Berhasil",
                                text: "Data berhasil dihapus!",
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    document.location.href = "";
                                }
                            });
                        },
                    });
                }
            });
        }
    });

    $("#cetak_barcode").click(function () {
        var allVals = [];
        $(".ceklis:checked").each(function () {
            allVals.push($(this).val());
        });
        var token = $("meta[name='csrf-token']").attr("content");

        if (allVals.length <= 0) {
            Toast.fire({
                icon: "error",
                title: "Ceklis data yang akan dicetak!!!.",
            });
        } else {
            $.ajax({
                type: "POST",
                url: "cetak-barcode",
                data: {
                    allVals: allVals,
                    _token: token,
                },
                beforeSend: function () {
                    $("#cetak_barcode").html(
                        '<i class="fas fa-spinner fa-spin"></i> Tunggu..'
                    );
                    $("#cetak_barcode").attr("disabled", true);
                },
                success: function (data) {
                    $(".tampil_data").html(data);
                    $("#hidedata").hide();

                    $("#cetak_barcode").html(
                        '<i class="fa fa-print"> Cetak Barcode </i>'
                    );
                    $("#cetak_barcode").attr("disabled", false);

                    let timerInterval;
                    Swal.fire({
                        title: "Mohon tunggu sebentar!",
                        html: "Proses mempersiapkan data <b></b> milliseconds.",
                        timer: 2000,
                        timerProgressBar: true,
                        didOpen: () => {
                            Swal.showLoading();
                            const timer = Swal.getPopup().querySelector("b");
                            timerInterval = setInterval(() => {
                                timer.textContent = `${Swal.getTimerLeft()}`;
                            }, 100);
                        },
                        willClose: () => {
                            clearInterval(timerInterval);
                        },
                    }).then((result) => {
                        /* Read more about handling dismissals below */
                        if (result.dismiss === Swal.DismissReason.timer) {
                            printPageArea("print");
                            document.location.href = "";
                        }
                    });
                },
            });
        }
    });

    $("#cetak_induk").click(function () {
        $.ajax({
            type: "GET",
            url: "/cetak-induk-produk",
            success: function (data) {
                $(".tampil_data").html(data);
                $("#hidedata").hide();
                let timerInterval;
                Swal.fire({
                    title: "Mohon tunggu sebentar!",
                    html: "Proses mempersiapkan data <b></b> milliseconds.",
                    timer: 2000,
                    timerProgressBar: true,
                    didOpen: () => {
                        Swal.showLoading();
                        const timer = Swal.getPopup().querySelector("b");
                        timerInterval = setInterval(() => {
                            timer.textContent = `${Swal.getTimerLeft()}`;
                        }, 100);
                    },
                    willClose: () => {
                        clearInterval(timerInterval);
                    },
                }).then((result) => {
                    /* Read more about handling dismissals below */
                    if (result.dismiss === Swal.DismissReason.timer) {
                        $("#hidedata").hide();
                        printPageArea("print");
                        document.location.href = "";
                    }
                });
            },
        });
    });

    function printPageArea(areaID) {
        var printContent = document.getElementById(areaID).innerHTML;
        var originalContent = document.body.innerHTML;
        document.body.innerHTML = printContent;
        window.print();
        document.body.innerHTML = originalContent;
    }
});
