<?= $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">조직 관리</div> -->
            <div class="card-body">
                <table id="menuList" class="table table-hover table-striped table-bordered"></table>
            </div>
        </div>
    </div>

    <div class="col-md-5 col-xl-5">
        <div class="main-card mb-3 card">
            <div class="card-header">메뉴 정보</div>
            <div class="card-body">
                <form method="POST" id="frm_menu_info" name="frm_menu_info" onsubmit="return false;">
                    <input type="hidden" name="depth" value="ROOT" />
                    <input type="hidden" name="level" value="1" />


                    <!-- 상위메뉴 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">상위메뉴</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="mnu_pid" readonly="readonly">
                        </div>
                    </div>

                    <!-- 메뉴아이디 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">메뉴아이디</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="mnu_id">
                        </div>
                    </div>

                    <!-- 메뉴명 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">메뉴명</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="mnu_nm">
                        </div>
                    </div>

                    <!-- 메뉴유형 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">메뉴유형</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="mnu_tp">
                                <option value="">선 택</option>
                                <!-- <option value="R">루트</option> -->
                                <option value="D">디렉토리</option>
                                <option value="P">화면</option>
                                <!-- <option value="A">기능</option>
                                <option value="L">화면링크</option> -->
                            </select>
                        </div>
                    </div>

                    <!-- 경로 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">경로</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="mnu_url">
                        </div>
                    </div>

                    <!-- 정렬순서 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">정렬순서</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="view_odr">
                        </div>
                    </div>

                    <!-- 사용여부 -->
                    <div class="position-relative row form-group mb-3">
                        <label class="col-sm-2 col-form-label">사용여부</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="use_yn">
                                <option value="Y" selected>사용</option>
                                <option value="N">미사용</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="card-footer d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-success" id="btnNew">
                    신규
                </button>
                <button type="button" class="btn btn-primary" id="btnSave">
                    저장
                </button>
            </div>
        </div>
    </div>
</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">
<script type="text/javascript">

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

    var tbl;

    $(function () {

        tbl = $("#menuList").jqGrid({
            url: "/manage/menu/getMenuList",
            datatype: "json",
            mtype: "POST",
            height: 480,
            rowNum: 10000,
            autowidth: true,
            width: "auto",
            shrinkToFit: true,
            treeGrid: true,
            treedatatype: "json",
            gridview: true,
            sortorder: "desc",
            ExpandColumn: 'mnu_nm',
            expanded: true,
            viewrecords: true,
            scrollrows: true,
            treeGridModel: 'adjacency',
            colNames: ['메뉴명', '메뉴ID', '메뉴유형', 'URL', '정렬순서', '사용여부', '', ''],
            colModel: [
                { name: 'mnu_nm', index: 'mnu_nm', width: 150 },
                { name: 'mnu_id', index: 'mnu_id', width: 80 },
                { name: 'mnu_tp_nm', index: 'mnu_tp_nm', width: 80, align: "center" },
                { name: 'mnu_url', index: 'mnu_url', width: 200 },
                { name: 'view_odr', index: 'view_odr', width: 50, align: "center" },
                { name: 'use_yn_nm', index: 'use_yn_nm', width: 50, align: "center" },
                { name: 'mnu_tp', index: 'mnu_tp', hidden: true },
                { name: 'use_yn', index: 'use_yn', hidden: true },
            ],

            jsonReader: {
                // root: "rows",      // 🔹 지금 JSON 구조: { total: "...", rows: [ ... ] }
                repeatitems: false,
                id: "mnu_id"
            },

            treeReader: {
                parent_id_field: "mnu_pid",   // 🔴 부모 필드 지정 (중요)
                level_field: "level",         // 이미 JSON에 들어있음
                left_field: "lft",
                right_field: "rgt",
                leaf_field: "isLeaf",         // true / false (boolean 권장)
                expanded_field: "expanded",   // ROOT(M) 에만 true 있으면 됨
                icon_field: "iconCls"
            },


            sortname: "mnu_id",
            sortorder: "asc",

            loadComplete: function () {
                $("#menuList")
                    .jqGrid('setGridParam', { datatype: 'local' })
                    .trigger("reloadGrid");
            },
            onSelectRow: function (index, row) {

                var rowKey = $('#menuList').jqGrid('getGridParam', 'selrow');
                if (rowKey) {
                    var data = $('#menuList').jqGrid('getRowData', rowKey);

                    $("#frm_menu_info [name=level]").val(data.level);
                    $("#frm_menu_info [name=mnu_pid]").val(data.mnu_pid);
                    $("#frm_menu_info [name=mnu_id]").val(data.mnu_id);
                    $("#frm_menu_info [name=mnu_nm]").val(data.mnu_nm);
                    $("#frm_menu_info [name=mnu_url]").val(data.mnu_url);
                    $("#frm_menu_info [name=mnu_tp]").val(data.mnu_tp);
                    $("#frm_menu_info [name=view_odr]").val(data.view_odr);
                    $("#frm_menu_info [name=use_yn]").val(data.use_yn);

                }
            },
        });


        // 신규 btn click
        $("#btnNew").on("click", function () {
            const level = $("#frm_menu_info [name=level]").val();

            if (level === "2") {
                $("#frm_menu_info [name=depth]").val("DIR");
                // $("#frm_menu_info [name=level]").val("1");

                Swal.fire({
                    title: "하위 메뉴 생성 불가",
                    icon: "warning"
                });
                return;
            } else {
                let id = $("#frm_menu_info [name=mnu_id]").val();
                if (id === "M") id = "0";

                $("#frm_menu_info")[0].reset();
                $("#frm_menu_info [name=depth]").val("ROOT");
                $("#frm_menu_info [name=level]").val("1");
                $("#frm_menu_info [name=mnu_pid]").val(id);
            }

        });


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

            if ($("#frm_menu_info [name=mnu_id]").val() === "") {
                Swal.fire({
                    title: "메뉴아이디를 입력해 주세요.",
                    icon: "warning"
                });
                return;
            }

            if ($("#frm_menu_info [name=mnu_nm]").val() === "") {
                Swal.fire({
                    title: "메뉴명을 입력해 주세요.",
                    icon: "warning"
                });
                return;
            }

            if ($("#frm_menu_info [name=mnu_tp]").val() === "") {
                Swal.fire({
                    title: "메뉴유형을 선택해 주세요.",
                    icon: "warning"
                });
                return;
            }

            if ($("#frm_menu_info [name=mnu_url]").val() === "") {
                Swal.fire({
                    title: "경로를 입력해 주세요.",
                    icon: "warning"
                });
                return;
            }

            if ($("#frm_menu_info [name=view_odr]").val() === "") {
                Swal.fire({
                    title: "순서를 입력해 주세요.",
                    icon: "warning"
                });
                return;
            }


            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#ff0000",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/manage/menu/saveMenu',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_menu_info").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) {
                            tbl.ajax.reload();
                            clearForm();

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

                                });
                            } else {
                                Swal.fire({
                                    title: result.msg,
                                    icon: "error"
                                })
                            }
                        }
                    });
                }
            });

        });

    });


    // 폼초기화
    function clearForm() {
        $("#frm_menu_info")[0].reset();
        $("#frm_menu_info [name=depth]").val("ROOT");
        $("#frm_menu_info [name=level]").val("1");
        $("#frm_menu_info [name=mnu_pid]").val("0");
    }

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