<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
<style>
    th {
        font-size: 11px;
    }

    #logList tbody tr {
        cursor: pointer;
    }

    .blockUI {
        z-index: 1500 !important;
    }

    .ellipsis {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 180px;
    }

    .swal2-cancel {
        background-color: #ff0000 !important;
        color: #fff !important;
    }
</style>

<h1>권한 관리</h1>

<div class="row">
    <div class="col-md-7 col-xl-7">
        <div class="main-card mb-3 card">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">메뉴 목록</h3>

                <div class="card-tools d-flex align-items-center ms-auto gap-2">
                    <div class="input-group input-group-sm">
                        <select class="form-control" id="usrlevel">
                            <option value="">그룹 선택</option>
                            <?php foreach ($usrLevel as $d): ?>
                                <option value="<?= $d['cd'] ?>"><?= $d['cd_nm'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="button" class="btn btn-primary btn-sm" id="btnSave">
                            저장
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <!-- <table id="menuList" class="table table-hover table-striped table-bordered"></table> -->
                <div id="menuTree"></div>
            </div>
        </div>
    </div>

    <form class="form-horizontal" id="permissionSrcFrm" name="permissionSrcFrm">
        <input type="hidden" name="usr_level" id="usr_level" />
        <input type="hidden" name="mnu_cd" id="mnu_cd" />
    </form>
</div>


<!-- The jqGrid language file code-->
<script type="text/javascript" src="//cdn.jsdelivr.net/jqgrid/4.6.0/i18n/grid.locale-kr.js">
</script>
<!-- The atual jqGrid code -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jqgrid/4.6.0/jquery.jqGrid.src.js">
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/css/ui.jqgrid.min.css">
<link rel="stylesheet" type="text/css" href="/plugin/css/jsTree/style.min.css">
<script src="/plugin/js/jqgrid/jstree.min.js"></script>
<script type="text/javascript">

    // const tpl = document.querySelector('.my-loader-template')
    let date = new Date()

    $(function () {

        // 그룹 onchange
        $("#usrlevel").on("change", function () {


            if ($(this).val() === "") {
                $('#menuTree').jstree('destroy');
                return;
            }

            changeAuthCombo($(this).val());

        });


        // 저장 btn click
        $("#btnSave").on("click", function () {

            const usr_level = $("#usr_level").val();

            if (usr_level === "") {
                Swal.fire({
                    title: "그룹을 선택해 주세요.",
                    icon: "warning"
                });
                return;
            }

            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#ff0000",
            }).then((result) => {
                if (result.isConfirmed) {

                    var checked_value = [];
                    checked_value.push($("#menuTree").jstree("get_checked"));
                    $("#menuTree .jstree-undetermined").parent().parent().each(function () {
                        checked_value.push(this.id);
                    });
                    $("#permissionSrcFrm [name=mnu_cd]").val(checked_value);

                    $.ajax({
                        url: '/manage/permit/saveMenuAuth',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#permissionSrcFrm").serialize(),
                        beforeSend: function () {
                            blockUI.blockPage({
                                message: tpl
                            })
                        },
                        complete: function () {
                            blockUI.unblockPage()
                        },
                        error: function (xhr, error, thrown) {
                            blockUI.unblockPage()
                            var msg = "";
                            if (xhr.responseText != null) {
                                msg = xhr.responseText
                            } else {
                                msg = "잠시후 다시 시도해 주세요."
                            }

                            Swal.fire({
                                title: msg,
                                icon: "error"
                            })
                        },
                        success: function (result) {

                            if (result.code == '0') {
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

                                });

                                setTimeout(() => {
                                    location.reload();
                                }, 1500);
                            } else {
                                Swal.fire({
                                    title: result.msg,
                                    icon: "error"
                                })
                            }
                        }
                    });
                }
            });

        });

    });

    // 메뉴 목록 및 권한 조회
    function changeAuthCombo(code) {
        $("#usr_level").val(code);
        $('#menuTree').jstree('destroy');


        $.ajax({
            url: '/manage/permit/getMenuAuthList',
            type: 'GET',
            dataType: 'json',
            data: {
                usr_level: code
            },
            beforeSend: function () {
                // 호출 직전에 실행

                blockUI.blockPage({
                    message: tpl
                });
            },
            complete: function () {
                // 완료 시(성공/실패 모두)

                blockUI.unblockPage();
            },
            error: function (xhr) {
                console.error("에러", xhr);
            },
            success: function (data) {
                const filteredData = data;


                $('#menuTree').jstree({
                    'core': {
                        'data': filteredData
                    },
                    'checkbox': {
                        keep_selected_style: false
                    },
                    'plugins': ['checkbox']
                }).on('loaded.jstree', function () {
                    $('#menuTree').jstree('open_all');
                });

                setTimeout(() => {
                    uncheckedItem(data);
                }, 500);
            }
        });



        // $.getJSON('/manage/permit/getMenuAuthList?usr_level=' + code, function (data) {
        //     const filteredData = data;


        //     $('#menuTree').jstree({
        //         'core': {
        //             'data': filteredData
        //         },
        //         'checkbox': {
        //             keep_selected_style: false
        //         },
        //         'plugins': ['checkbox']
        //     }).on('loaded.jstree', function () {
        //         $('#menuTree').jstree('open_all');
        //     });

        //     setTimeout(() => {
        //         uncheckedItem(data);
        //     }, 500);


        // });

    }

    function uncheckedItem(data) {
        data.map(item => {
            const newItem = { ...item };
            if (newItem.state && newItem.state.selected === false) {
                $('#menuTree').jstree('uncheck_node', newItem.id);
            }

        });
    }

</script>
<?= $this->endSection() ?>