<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>그룹별권한</title>
    <%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp" %>
</head>


<script>

    $(document).ready(function () {
            getOpr();
            getQueryString();
            getGroupAuthUpdateData();
            $("#Content").on("keyup", function (key) {
                if (key.keyCode == 13) {
                    getUserSearch()
                }
            });

            //유저조회
            $('#btnSearchUser').on('click', function () {
                getUserSearch()
                // $('#serviceInfo').reset();
            });

            //유저 선택 이벤트
            $('#selectorUser').change(function () {
                userAdd($(this).val(), $('#selectorUser option:selected').text())
            });


            $('#btnSave').on('click', function () {
                // console.log("저장클릭")
                ServiceGroupAuthModifyUpdate();
            });

            $('#btnDel').on('click', function () {
                // console.log("취소버튼");
                delBtn();
            });
        }
    );


    function delBtn() {
        listgo();
    }

    function listgo() {
        document.location.href = "<c:url value='/admin/common/system/groupAuth/manage.do'/>";
    }

    function getUserSearch() {

        getQueryString();
        var json = {};
        var searchText = $('#userSelBox').val();
        json.userSearchText = searchText;
        $('#selectorUser').html("");
        $('#selectorUser').niceSelect('update');
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            async: false,
            datatype: "JSON",
            // url: "/BotMain_VM/admin/common/system/groupAuth/userSearch" + "?authGroupSeq=" + getQueryString(),
            url: "<c:url value='/admin/common/system/groupAuth/userSearch'/>" + "?authGroupSeq=" + getQueryString(),
            data: JSON.stringify(json),
            success:
                function (data) {
                    // console.log("datasss " + JSON.stringify(data))
                    var html = "";
                    data.forEach(function (e, i) {
                        html += "<option value=" + e.userSeq + ">" + e.userName + ' (' + e.userId + ')' + "</option>";
                    });
                    $('#selectorUser').html(html);
                    $('#selectorUser').niceSelect('update');
                }
        })
    }

    function ServiceGroupAuthModifyUpdate() {

        var selectedElmsIds = [];
        var selectedElms = $("#tree_wrap").jstree("get_selected", true);
        $.each(selectedElms, function () {
            selectedElmsIds.push(this.id);
        });


        var userList = [];
        var delList = [];
        $("#list-user-group-box-ul-list").children('li').each(function (i, e) {
            var ids = $(this).find("div").find("a").attr("id").replaceAll("userseq", "")
            userList.push(ids)
            // console.log("3  = " + ids)
        })

        $("#list-user-group-box-ul-delete").children('li').each(function (i, e) {
            var ids = $(this).find("div").find("a").attr("id").replaceAll("userseq", "")
            delList.push(ids)
            // console.log("3  = " + ids)
        })


        // console.log("lasddlasldqwle  = " + JSON.stringify(lasddlasldqwle))
        var authSeq = $('#authGroupSeq').val();
        var json = {};
        json.custCode = $('#custCode').val();
        json.authGroupSeq = authSeq;
        json.policyGroupName = $('#updateGroupName').val();
        json.policyGroupDesc = $('#updateGroupDesc').val();
        json.theUser = userList;
        json.delUser = delList;
        json.thePolicy = selectedElmsIds;
        // console.log("saveData  = " + JSON.stringify(json))
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            // url: "/BotMain_VM/admin/common/system/groupAuth/modify/update",
            url: "<c:url value='/admin/common/system/groupAuth/modify/update'/>",
            data: JSON.stringify(json),
            success:
                function (data) {
                    // console.log("modfu suc - ");
                    // document.location.href = "/BotMain_VM/admin/common/system/groupAuth/update" + "?authGroupSeq=" + getQueryString();
                    document.location.href = "<c:url value='/admin/common/system/groupAuth/manage.do'/>";
                }
        })

    }


    function getQueryString() {
        var param = new URLSearchParams(location.search).get("authGroupSeq");
        // console.log(param)
        return param;
    }


    function getOpr() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            async: false,
            datatype: "JSON",
            url: "<c:url value='/adm/menu/oprmng'/>",
            success: function (data) {
                // console.log(JSON.stringify(data));
                data.forEach(function (e, f) {
                    $('#serviceGroup').append("<option value=" + e.serviceGroup + ">" + e.serviceGroupName + "</option>");
                    $('#serviceGroup').niceSelect('update');
                });
            }
        })
    };


    function getGroupAuthUpdateData() {
        var authGroupSeq = "authGroupSeq=" + getQueryString();
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            async: false,
            datatype: "JSON",
            data: authGroupSeq,
            url: "<c:url value='/admin/common/system/groupAuth/update/select'/>",
            success: function (data) {
                // console.log(data.authGroupSeq);
                // console.log(data.authPolicyVal);
                $('#custCode').val(data.custCode);
                $('#authGroupSeq').val(data.authGroupSeq);
                $('#updateGroupName').val(data.policyGroupName);
                $('#updateGroupDesc').val(data.policyGroupDesc);
                treeWrap(data.authPolicyVal, data.mainMenu, data.policyParent);
                $('#list-user-group-box-ul-list').html(userList(data.userList))
            }
        })
    };

    function userList(data) {
        // console.log(JSON.stringify(data));
        var html = '';
        data.forEach(function (e, i) {
            var setUserSeq = e.userSeq;
            var setUserIdName = e.userName;
            var setUserId = e.userId;
            html
                += ' <li class="select2-selection__choice" id="' + 'userLi' + setUserSeq + '">'
                + ' <div class="chk_box">'
                + '      <a  id="' + 'userseq' + setUserSeq + '"'
                + 'href="javascript:ListToDelete(' + setUserSeq + ')" >'
                + setUserIdName + ' (' + setUserId + ')' + '</a>'
                + '</div>'
                + ' </li>'
        });
        return html;
    }

    function userAdd(seq, val) {
        var html = '';
        var userlist = $('#list-user-group-box-ul-list').children('li').attr("id");

        html
            += ' <li class="select2-selection__choice" id="' + 'userLi' + seq + '">'
            + ' <div class="chk_box">'
            + '      <a  id="' + 'userseq' + seq + '"'
            + 'href="javascript:ListToDelete(' + seq + ')" >'
            + val + '</a>'
            + '</div>'
            + ' </li>'
        $('#userLi' + seq).remove();
        $('#list-user-group-box-ul-list').prepend(html);
        // $('#selectorUser').removeAttr(seq);
        $('#selectorUser' + 'option[value=' + seq + ']').remove();
        $('#selectorUser').niceSelect('update');


    }


    function ListToDelete(setUserSeq) {
        var setVal = $('#userseq' + setUserSeq).text();
        var html = '';
        html
            += ' <li class="select2-selection__choice" id="' + 'userLi' + setUserSeq + '">'
            + ' <div class="chk_box">'
            + '      <a  id="' + 'userseq' + setUserSeq + '"'
            + 'href="javascript:DeleteToList(' + setUserSeq + ')" >'
            + setVal + '</a>'
            + '</div>'
            + ' </li>';
        $('#userLi' + setUserSeq).remove();
        $('#list-user-group-box-ul-delete').append(html);

    }

    function DeleteToList(setUserSeq) {
        var setVal = $('#userseq' + setUserSeq).text();
        var html = '';
        html
            += ' <li class="select2-selection__choice" id="' + 'userLi' + setUserSeq + '">'
            + ' <div class="chk_box">'
            + '      <a  id="' + 'userseq' + setUserSeq + '"'
            + 'href="javascript:ListToDelete(' + setUserSeq + ')" >'
            + setVal + '</a>'
            + '</div>'
            + ' </li>';
        $('#userLi' + setUserSeq).remove();
        $('#list-user-group-box-ul-list').append(html);

    }


    function treeWrap(authPolicyVal, mainMenu, policyParent) {
        var treeData = [];
        mainMenu.forEach(function (e, i) {
            if (authPolicyVal.includes(e.authName)) {
                treeData[i] = {
                    id: e.authName,
                    parent: policyParent[e.authName],
                    text: e.menuName,
                    state: {
                        opened: false,
                        selected: true
                    }
                };
            } else {
                treeData[i] = {
                    id: e.authName,
                    parent: policyParent[e.authName],
                    text: e.menuName,
                    state: {
                        opened: false,
                        selected: false
                    }
                };
            }
        });
        setTimeout(() => {
            $('#tree_wrap').jstree({
                'core': {
                    'data': treeData
                },
                "checkbox": {
                    "keep_selected_style": false
                    , "three_state": false
                },
                "plugins": ["checkbox"]

            });
        }, "1");
    }


</script>


<body>

<h1>ICOMSYS ADMIN</h1>
<h1>대시보드</h1>
<div class="skip_navigation">
    <ul>
        <li>
            <a href="#Content" class="go_content">본문 바로가기</a>
        </li>
        <li>
            <a href="#Gnb">메뉴 바로가기</a>
        </li>
    </ul>
</div>

<header id="header">
    <%@ include file="/WEB-INF/jsp/adm/include/header.jsp" %>
</header>
<c:import url="/adm/menu/getLnbMenu.do"/>
<section id="Content" class="system_management">
    <div class="location">
        <ul>
            <li class="home"><a href="#">HOME</a></li>
            <li><a href="#">시스템관리</a></li>
            <li><a href="#">그룹별권한 관리</a></li>
        </ul>
    </div>

    <!-- TODO: 래부터 신규 컨텐츠 마크업 입니다. -->
    <div class="sub_cont">
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">권한그룹편집</h2>
                </div>
            </div>
            <div class="tbl">
                <table class="edit hght">
                    <colgroup>
                        <col width="150px">
                        <col width="auto">
                    </colgroup>
                    <tbody>
                    <input type="hidden" id="custCode">
                    <input type="hidden" id="authGroupSeq">
                    <tr>
                        <th class="tl">그룹명</th>
                        <td>
                            <div class="ipt_box">
                                <input type="text" id="updateGroupName" value="인텐트 조회권한" name="" class="">
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th class="tl">그룹설명</th>
                        <td>
                            <div class="ipt_box">
                                <input type="text" id="updateGroupDesc" value="인텐트를 조회만 할 수 있는 권한" name="" class="">
                            </div>
                        </td>
                    </tr>


                    <tr>
                        <th class="tl">소속사용자 <em class="red">*</em></th>
                        <td>
                            <%--                            <div class="ipt_box listen">--%>
                            <%--                                <input type="text" placeholder="유저명을 입력하세요" id="userSelBox" name="typeText">--%>
                            <%--                                <div class="btn_wrap fl">--%>
                            <%--                                    <a href="#" id="btnSearchUser" class="btn">조회</a>--%>
                            <%--                                </div>--%>
                            <%--                            </div>--%>
                            <div class="ipt_box listen type-flex">
                                <input type="text" placeholder="유저명을 입력하세요" id="userSelBox" name="typeText">
                                <a href="#" id="btnSearchUser" class="btn">조회</a>
                            </div>

                            <select id="selectorUser" class="wide">
                                <%--                                    <option value="ALL">분류 선택</option>--%>
                                <%--                                    <option value="major">대분류</option>--%>
                                <%--                                    <option value="minor">중분류</option>--%>
                            </select>


                            <div class="list-user-group-box">
                                <div class="list-user-group-item">
                                    <div class="group-item-title">소속사용자</div>
                                    <ul class="list-user-group-box-ul" id="list-user-group-box-ul-list">

                                    </ul>
                                </div>

                                <!-- 2단레이아웃 필요시 list-user-group-item부터 추가-->
                                <div class="list-user-group-item">
                                    <div class="group-item-title">소속제외</div>
                                    <ul class="list-user-group-box-ul" id="list-user-group-box-ul-delete">

                                    </ul>
                                </div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">권한</th>
                        <td class="tl">
                            <div class="content tree tree-maxHeight type-chk">
                                <div class="tree_wrap" id="tree_wrap">
                                </div>
                            </div>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </div>
        </div>

        <div class="cont_box">
            <div class="btn_wrap center">
                <%--                <a href="#" class="btn basic grey">삭제</a>--%>
                <a href="#" class="btn basic grey" id="btnDel">취소</a>
                <a href="#" class="btn basic" id="btnSave">저장</a>
            </div>
        </div>
    </div>

</section>


</body>
</html>