<%@ 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();
            PagingDataTable();
            // newTreeWrap();
            $('#listTable tbody').on('dblclick', 'tr', function () {
                var data = $('#listTable').DataTable().row(this).data()
                // console.log(JSON.stringify(data))
                viewPage(data);
            });

            $('#btnSearchOpr').on('click', function () {
                fnCustSearchBtn();
            });

            $("#Content").on("keyup", function (key) {
                if (key.keyCode == 13) {
                    fnCustSearchBtn();
                }
            });

            //모달창 저장버튼
            $('#btnRegModal').on('click', function () {
                fnInsertBtn();
            });


            //선택 이벤트
            $('#insertServiceGroup').change(function () {
                getRoleAndOpr($(this).val());
            });
    }
    );



    function getRoleAndOpr() {
        var role = '';
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/adm/menu/role'/>",
            success: function (data) {
                role = data;
            }
        })
        // console.log("aaaa - "+role)
        var service = $('#insertServiceGroup option:selected').val();
        // console.log(service);
        newTreeWrap(service);
        return role;



    };


    function getOpr() {

        var setUrl = '';
        var role = getRoleAndOpr();
        // console.log(role)
        if(role ==='SYSTEMADMIN'){
            setUrl =  "<c:url value='/adm/menu/oprmng'/>" ;
        }
        else {
            setUrl =  "<c:url value='/adm/menu/oprmng'/>"
                // + "?serviceType=S"
            ;
        }

        var html = '<option value="' + "ALL" + '">' + "전체" + '</option>';
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: setUrl,
            success: function (data) {
                // console.log(JSON.stringify(data));
                data.forEach(function (e, f) {
                    html += '<option value="' + e.serviceGroup + '">' + e.serviceGroupName + '</option>';
                });
            }
        })
        $('#serviceGroup').html(html);
        $('#serviceGroup').niceSelect('update');
        $('#insertServiceGroup').html(html);
        $('#insertServiceGroup').niceSelect('update');
    };

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

    <%--function insertOpr() {--%>
    <%--    var html = '';--%>
    <%--    $.ajax({--%>
    <%--        type: "GET",--%>
    <%--        contentType: "application/json; charset=utf-8",--%>
    <%--        datatype: "JSON",--%>
    <%--        async: false,--%>
    <%--        url: "<c:url value='/admin/common/system/groupAuth/insert/opr'/>",--%>
    <%--        success: function (data) {--%>
    <%--            data.forEach(function (e, f) {--%>
    <%--                // console.log("aaaaa"+e.serviceGroup)--%>
    <%--                html += '<option value="' + e.serviceGroup + '">' + e.serviceGroupName + '</option>';--%>
    <%--            });--%>
    <%--        }--%>
    <%--    })--%>
    <%--};--%>


    function viewPage(rowData) {
        document.location.href = "<c:url value='/admin/common/system/groupAuth/update'/>" + "?authGroupSeq=" + rowData.authGroupSeq;
        // document.location.href = "/BotMain_VM/admin/common/system/groupAuth/update" + "?authGroupSeq=" + rowData.authGroupSeq;
    }


    function fnInsertBtn() {
        // document.location.href = "/BotMain_VM/admin/common/system/groupAuth/insert";

        var insertServiceGroup = $('#insertServiceGroup').val();
        var insertGroupName = $('#insertGroupName').val();
        var insertGroupDesc = $('#insertGroupDesc').val();
        var selectedElms = $("#newTreeWrap").jstree("get_selected", true);

        var selectedElmsIds = []
        $.each(selectedElms, function () {
            selectedElmsIds.push(this.id);
        });
        // console.log(insertServiceGroup);
        // console.log(insertGroupName);
        // console.log(insertGroupDesc);
        // console.log(selectedElmsIds.length);

        if (insertServiceGroup === "ALL") {
            // $.utils.success("사용가능합니다");
            $.utils.warning("시나리오그룹을 선택해주세요.");
            return;
        }

        if (insertGroupName.length < 1) {
            $.utils.warning("권한그룹명을 선택해주세요.");
            return;
        }

        if (selectedElmsIds.length < 1) {
            $.utils.warning("정책을 1개이상 선택해주세요.");
            return;
        }
        var insertJson = {};
        insertJson.insertServiceGroup = insertServiceGroup;
        insertJson.insertGroupName = insertGroupName;
        insertJson.insertGroupDesc = insertGroupDesc;
        insertJson.subPolicyVal = selectedElmsIds;
        insertJson.subUseYn = 'Y';
        // console.log("jsondata - " + JSON.stringify(insertJson));
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/groupAuth/insert'/>",
            data: JSON.stringify(insertJson),
        })
            .complete(function (data) {
                // console.log(JSON.stringify(data));
                // console.log(data.status);
                if (data.status == 200) {
                    // document.location.href = "/BotMain_VM/admin/common/system/groupAuth/manage.do";
                    document.location.href = "<c:url value='/admin/common/system/groupAuth/manage.do'/>";
                } else {
                    // console.log(JSON.stringify(this));
                }
            })
        ;
    }



    ///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!수정!!!!!!!!!
    function newTreeWrap(serviceGroup) {

        if(serviceGroup === 'ALL'){
            return;
        }
        var treeData = [];

        setUrl = "<c:url value='/admin/common/system/groupAuth/newTree'/>"+"?serviceGroup="+serviceGroup;
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            url: setUrl,
            async: false,
            success: function (data) {
                var mainMenu = data.mainMenu;
                var policyParent = data.policyParent;
                mainMenu.forEach(function (e, i) {
                    treeData[i] = {
                        id: e.authName,
                        parent: policyParent[e.authName],
                        text: e.menuName,
                        state: {
                            opened: false,
                            selected: true
                        }
                    };
                });

                // $('#newTreeWrap').jstree(true).settings.core.data = treeData;
                // $('#newTreeWrap').jstree(true).refresh();

                setTimeout(() => {
                    $('#newTreeWrap').jstree({
                        'core': {
                            'data': treeData
                        },
                        "checkbox": {
                            "keep_selected_style": false
                            , "three_state": false
                        },
                        "plugins": ["checkbox"]
                    });
                }, "1")

                // $('#newTreeWrap').jstree(true).settings.core.data = treeData;
                $('#newTreeWrap').jstree('refresh');

            }
        });


    }


    var PagingDataTable = function () {
        // console.log("log - " + JSON.stringify({"page": "0", "size": "10"}));
        var paging = JSON.stringify({'page': 0, 'size': 10})
        $('#listTable').DataTable(
            {
                ajax: {
                    url: "<c:url value='/admin/common/system/groupAuth/list'/>",
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    dataType: "JSON",
                    async: false,
                    data: function (data) {
                        var json = {};
                        if (data) {
                            json.page = data.start / data.length;
                            json.size = 10;
                            json.serviceGroup = $("#serviceGroup option:selected").val();
                            json.codeText = $('#codeText').val();
                        } else {
                            json = JSON.stringify({'page': 0, 'size': 10});
                        }
                        return JSON.stringify(json);
                    }
                    ,
                    dataFilter: function (data) {
                        var jsons = jQuery.parseJSON(data);
                        // console.log(JSON.stringify(data));
                        var json = {};
                        json.recordsTotal = jsons.getTotal;
                        json.recordsFiltered = jsons.getTotal;
                        json.data = jsons.getList;
                        // console.log(json);
                        return JSON.stringify(json);
                    }
                },
                order: [0, "asc"],
                scrollX: false,
                scrollY: false,
                autoWidth: false,
                searching: false,
                bProcessing: true,
                sProcessing: true,
                bServerSide: true,
                sDom: '<"row view-filter"<"col-sm-12"<"pull-left"><"pull-right"><"clearfix">>>t<"row view-pager"<"col-sm-12"<"text-center"pi>>>',
                columns: [
                    {data: "serviceGroup"},
                    {data: "serviceGroupName"},
                    {data: "authGroupSeq"},
                    {data: "policyGroupName"},
                    {data: "policyGroupDesc"},
                    {data: "custCode"},
                    {data: "registDate"}

                ],
                columnDefs: [
                    {
                        targets: 0,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;" onclick="click()">' + data + '</a>';
                        },
                    },
                    {
                        targets: 1,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 2,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 3,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 4,
                        orderable: false,
                        render: function (data) {
                            return '<a style="display: block;text-align: center;">' + data + '</a>';
                        }
                    },
                    {
                        targets: 5,
                        visible: false,
                        searchable: false,
                        orderable: false,
                        render: function (data) {
                            return '<a hidden="hidden">' + data + '</a>';
                        }
                    },
                    {
                        targets: 6,
                        orderable: false,
                        render: function (data, type, full, meta) {
                            // var arr = data.slice();
                            // return '<a style="display: block;text-align: center;">' + arr[0] + "-" + arr[1] + "-" + arr[2] + '</a>';
                            return '<a style="display: block;text-align: center;">' + $.utils.sliceDateTimeFormat(data) + '</a>';
                        }
                    }
                ]
            }
        )
    };

    function fnCustSearchBtn() {
        $('#listTable').DataTable().ajax.reload();
    };

</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>

    <div class="sub_cont menu06_01_03">
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">그룹별권한 조회</h2>
                </div>
                <div class="fr">
                    <div class="btn_wrap fl">
                        <a href="#" id="btnSearchOpr" class="btn">조회</a>
                    </div>
                </div>
            </div>

            <div class="tbl">
                <table class="search block">
                    <colgroup>
                        <col width="160px">
                        <col width="5%">
                        <col width="140px">
                        <col width="15%">
<%--                        <col width="140px">--%>
<%--                        <col width="25%">--%>
                    </colgroup>
                    <tbody>
                    <tr>
                        <th class="tl">시나리오그룹</th>
                        <td colspan="5">
                            <div class="sel_box">
                                <select id="serviceGroup" class="wide">
                                    <option value="ALL">전체</option>
                                </select>
                            </div>
                        </td>
                        <th class="tl">권한명</th>
                        <td colspan="5">
                            <div class="ipt_box listen">
                                <input type="text" placeholder="검색어를 입력하세요" id="codeText" name="typeText">
                            </div>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </div>
        </div>
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">그룹별권한 리스트</h2>
                </div>
                <div class="btn_wrap fr">
                    <%--                    <a href="#" class="btn grey" id="btnDelCust">삭제</a>--%>
                    <a href="#" rel="createGroupModal" class="btn line modalLoad">등록</a>
                </div>
            </div>

            <div class="tbl">
                <form id="custListForm">
                    <table id="listTable" class="">
                        <colgroup>
                            <col width="auto">
                            <col width="auto">
                            <col width="auto">
                            <col width="auto">
                            <col width="auto">
                            <col width="auto">
                        </colgroup>
                        <thead>
                        <tr>
                            <th>서비스코드</th>
                            <th>시나리오그룹명</th>
                            <th>권한번호</th>
                            <th>권한명</th>
                            <th>권한설명</th>
                            <th>고객사코드</th>
                            <th>생성일</th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </form>
            </div>
        </div>
    </div>
</section>

<!--  modal :: 권한그룹생성  -->
<div class="modal" id="createGroupModal">
    <div class="modal_header">
        <h3>권한그룹 생성</h3>
    </div>
    <div class="modal_body">
        <div class="modal_cont">
            <input type="hidden" id="custCode">
            <dl>
                <dt>
                    <h4><em class="">시나리오그룹</em></h4>
                </dt>
                <dd>
                    <div class="sel_box">
                        <select id="insertServiceGroup" class="wide">
                            <option value="ALL">전체</option>
                        </select>
                    </div>
                </dd>
            </dl>

            <dl>
                <dt>
                    <h4><em class="">그룹명</em></h4>
                </dt>
                <dd>
                    <div class="ipt_box">
                        <input type="text" id="insertGroupName" placeholder="그룹명을 입력해주세요.">
                    </div>
                </dd>
            </dl>
            <dl>
                <dt>
                    <h4><em class="">그룹설명</em></h4>
                </dt>
                <dd>
                    <div class="ipt_box">
                        <input type="text" id="insertGroupDesc" placeholder="그룹 설명을 입력해주세요.">
                    </div>
                </dd>
            </dl>
            <dl>
                <dt>
                    <h4><em class="">권한선택</em></h4>
                </dt>
                <dd>
                    <div class="content tree tree-maxHeight type-chk">
                        <div class="newTreeWrap" id="newTreeWrap">
                        </div>
                    </div>
                </dd>
            </dl>
        </div>

    </div>
    <div class="modal_footer">
        <div class="btn_wrap fr">
            <a href="#" id="btnRegModal" class="btn">저장</a>
        </div>
    </div>
    <div class="modal_controller">
        <a href="#" class="close">close</a>
    </div>
</div>


</body>
</html>
