<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<%--<script src="<c:url value='/lib/assets/js/diagram/dx-diagram.min.js' />"></script>--%>
<%--<script src="<c:url value='/lib/assets/js/diagram/dx-all.min.js' />"></script>--%>
<%--<link rel="stylesheet" href="<c:url value='/lib/assets/css/diagram/dx.custom.css' />">--%>
<%--<link rel="stylesheet" href="<c:url value='/lib/assets/css/diagram/dx-diagram.css' />">--%>
<%--<link rel="stylesheet" href="<c:url value='/lib/assets/css/diagram/indigo-pink.css' />">--%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>서비스그룹 관리</title>
    <%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp" %>
</head>

<script>
    $(document).ready(function () {

        $('.tbl-card-li').each(function () {
            $(this).find('.tbl-card-title').on('click', function () {
                $(this).parents('.tbl-card-li').toggleClass('on');
            })
        });

        $('.tbl-card').find('.tbl-card-li .title-connect').each(function () {
            const submitVal = $(this).val();
            if (submitVal.length > 0) {
                $(this).parents('.tbl-card-li').find('.title-connected').text(submitVal);
            }
            $(this).on('keyup', function () {
                const thisVal = $(this).val();

                if (thisVal.length === 0) {
                    $(this).parents('.tbl-card-li').find('.title-connected').text('새로운 시나리오 그룹');
                } else {
                    $(this).parents('.tbl-card-li').find('.title-connected').text(thisVal);
                }
            })
        });

        getServiceGroupQueryString();
        getServiceGroupViewData();

        $('#btnRegModal').on('click', function () {
            // console.log("생성클릭")
            newTreeWrap();
            // $('#serviceInfo').reset();
        });

        // 신규 시나리오그룹 저장
        $('#btnSaveCust').on('click', function () {
            // console.log("저장클릭")
            fncCreateServiceInfo();
        });

        //중복확인
        $('#btnDoubleCheck').on('click', function () {
            // console.log("저장클릭")
            fncNewDoubleCheck();
        });

        // $('#newServiceGroup').keydown(function (e) {
        $('#newServiceGroup').keyup(function (e) {
            // newOprCreate(e.keyCode)
        });


    });

    function fncNewDoubleCheck() {
        var custCode = $("#custCode").val();
        var newServiceGroup = $("#newServiceGroup").val();
        var checkJson = {};
        checkJson.custCode = custCode;
        checkJson.subServiceGroup = newServiceGroup;
        // console.log(newServiceGroup)
        if (newServiceGroup.length < 1) {
            // $.utils.success("사용가능합니다");
            $.utils.warning("1글자이상 입력해주세요.");
            // alert("1글자이상 입력해주세요.");
            return;
        }
        if (newServiceGroup.length > 20) {
            // alert("20글자이하로 입력해주세요.");
            $.utils.warning("20글자이하로 입력해주세요.");
            return;
        }

        var regType = /^[A-Za-z0-9]*$/;
        if (!regType.test(newServiceGroup)) {
            $.utils.warning('영문, 숫자만입력가능합니다.');
            return;
        } else {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "JSON",
                async: false,
                url: "<c:url value='/admin/common/system/serviceGroup/doubleCheck'/>",
                data: JSON.stringify(checkJson),
            })
                .complete(function (data) {
                    // console.log(JSON.stringify(data));
                    // console.log(data.status);
                    if (data.status == 200) {
                        $('#newDoubleCheck').val(data.responseText);
                        var yn = data.responseText;
                        if (yn === "Y") {
                            $.utils.success("사용가능합니다");
                            // $.utils.warning("1글자이상 입력해주세요.");
                            return;
                        } else {
                            $.utils.warning("중복된코드입니다.");
                            return;
                        }
                    } else {
                    }
                })
            ;
        }
    }

    function newOprCreate(e) {
        var expression = RegExp(/[^a-zA-Z]/);
        var text = String.fromCharCode(e);
        // console.log("key " + e);
        // console.log("key " + text);
        var cust = $("#custCode").val();
        var sol = "_RCP_";
        if (e === 8) {
            // setTimeout(() => {
                var outText = cust + sol + $('#newServiceGroup').val();
                $('#newOprDiv').html('<input type="text" id="newOprMngCode" value="' + outText.toUpperCase() + '" name="" class=" title-connect" readonly>')
            // }, "100")
        } else {
            var temp = $('#newOprMngCode').val().replace(cust + sol, "");
            $('#newOprMngCode').val(cust + sol + temp + text);
        }
    }

    function fncCreateServiceInfo() {
        var newServiceGroup = $("#newServiceGroup").val();
        var newServiceGroupName = $("#newServiceGroupName").val();
        var newServiceGroupDesc = $("#newServiceGroupDesc").val();
        var newUseYn = $("#newUseYn").val();
        var mainServiceGroup = $("#mainServiceGroup").val();
        var custCode = $("#custCode").val();
        var newDoubleCheck = $("#newDoubleCheck").val();
        // console.log(newServiceGroup);
        // console.log(newServiceGroupDesc);
        // console.log(newUseYn);

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

        if (newDoubleCheck == 'N') {
            // alert("중복확인을해주세요");
            // $.utils.success("사용가능합니다");
            $.utils.warning("중복확인을해주세요.");
            return;
        }
        if (newServiceGroupName.length < 1) {
            $.utils.warning("시나리오명을 입력해주세요");
            return;
        }

        var insertJson = {};
        insertJson.custCode = custCode;
        insertJson.mainServiceGroup = mainServiceGroup;
        insertJson.subServiceGroup = newServiceGroup;
        insertJson.subServiceGroupName = newServiceGroupName;
        insertJson.subServiceGroupDesc = newServiceGroupDesc;
        insertJson.subUseYn = newUseYn;
        insertJson.subPolicyVal = selectedElmsIds;

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            async: false,
            datatype: "JSON",
            url: "<c:url value='/admin/common/system/serviceGroup/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/serviceGroup/view" + "?serviceGroup=" + mainServiceGroup;
                    document.location.href = "<c:url value='/admin/common/system/serviceGroup/view'/>" + "?serviceGroup=" + mainServiceGroup;
                } else if (data.status == 405){
                    $.utils.warning("NLP연결에 실패했습니다.");
                }
                else {
                    $.utils.warning("오류가 발생했습니다.");
                }
            })
        ;

    }

    function getServiceGroupQueryString() {
        var param = new URLSearchParams(location.search).get("serviceGroup");
        return param;
    }


    //https://stackoverflow.com/questions/18268306/how-to-get-checked-nodes-in-jquery-jstree
    function testUpdate(idx) {
        var subServiceGroup = $("#subServiceGroup" + idx).val();
        var subServiceGroupDesc = $("#subServiceGroupDesc" + idx).val();
        var subServiceGroupName = $("#subServiceGroupName" + idx).val();
        var subUseYn = $("#subUseYn" + idx).val();
        var mainServiceGroup = $("#mainServiceGroup").val();
        var custCode = $("#custCode").val();

        var selectedElmsIds = [];
        var selectedElms = $("#treeWrap" + idx).jstree("get_selected", true);
        $.each(selectedElms, function () {
            if (idx.toString().length == '1') {
                selectedElmsIds.push(this.id.slice(0, this.id.length - 1));
            }
            if (idx.toString().length == '2') {
                selectedElmsIds.push(this.id.slice(0, this.id.length - 2));
            }
        });

        var updateJson = {};
        updateJson.custCode = custCode;
        updateJson.mainServiceGroup = mainServiceGroup;
        updateJson.subServiceGroup = subServiceGroup;
        updateJson.subServiceGroupDesc = subServiceGroupDesc;
        updateJson.subServiceGroupName = subServiceGroupName;
        updateJson.subUseYn = subUseYn;
        updateJson.subPolicyVal = selectedElmsIds;
        // console.log("jsondata - " + JSON.stringify(updateJson));
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            async: false,
            datatype: "JSON",
            url: "<c:url value='/admin/common/system/serviceGroup/update'/>",
            data: JSON.stringify(updateJson),
        })
            .complete(function (data) {
                // console.log(JSON.stringify(data));
                // console.log(data.status);
                if (data.status == 200) {
                    // document.location.href = "/BotMain_VM/admin/common/system/serviceGroup/view" + "?serviceGroup=" + mainServiceGroup;
                    document.location.href = "<c:url value='/admin/common/system/serviceGroup/view'/>" + "?serviceGroup=" + mainServiceGroup;
                } else if (data.status == 405){
                    $.utils.warning("NLP연결에 실패했습니다.");
                }
                else {
                    $.utils.warning("오류가 발생했습니다.");
                }
            })
        ;
    }


    function getServiceGroupViewData() {

        if (getServiceGroupQueryString() == null) {
            //유저어드민
            setUrl = "<c:url value='/admin/common/system/serviceGroup/select'/>";
        } else {
            //시스템어드민
            setUrl = "<c:url value='/admin/common/system/serviceGroup/select'/>" + "?serviceGroup=" + getServiceGroupQueryString();
        }
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            url: setUrl,
            success: function (data) {
                // console.log(JSON.stringify(data));
                var html = '';
                $('#mainServiceGroup').val(data.mainServiceGroup);
                $('#mainServiceGroupName').val(data.mainServiceGroupName);
                $('#mainUseYn').val(data.mainUseYn);
                $('#mainOprMngCode').val(data.mainOprMngCode);
                $('#custCode').val(data.custCode);

                var mainMenu = data.mainMenu;
                var mainPolicyVal = data.mainPolicyVal;
                var policyParent = data.policyParent;
                // mainMenu.push(data.mainMenu);
                // mainPolicyVal.push(data.mainPolicyVal);

                data.subService.forEach(function (e, i) {
                    // console.log(JSON.stringify(e));
                    html
                        += '<li class="tbl-card-li" id="tbl-card-li' + i + '">'
                        + '<div class="tbl-card-li-inner">'
                        + '<div class="tbl-card-title" id="tbl-card-title' + i + '">'
                        + '     <div class="fl title-connected">' + e.subServiceGroupName + '</div>'
                        + '  </div>'
                        + '     <div class="tbl-card-data">'
                        + ' <div class="box-title">'
                        + '<div class="btn_wrap fr">'
                        + '<a href="javascript:testUpdate(' + i + ')" class="btn grey">저장</a>'
                        + '</div>'
                        + '</div>'
                        + '     <div class="box-title">'
                        // + '      <div class="btn_wrap fr">'
                        // + '           <a href="#" class="btn grey">-삭제</a>'
                        // + '       </div>'
                        + '     </div>'
                        + '     <div class="tbl">'
                        + '        <table class="edit hght">'
                        + '          <colgroup>'
                        + '      <col width = "160px" >'
                        + '      <col width = "auto" >'
                        + '                  </colgroup>'
                        + '              <tbody>'
                        + '             <tr>'
                        + '                  <th class="tl">시나리오 그룹명</th>'
                        + '                  <td>'
                        + '                      <div class="ipt_box">'
                        + '                          <input type="text" id="subServiceGroupName' + i + '" value="' + e.subServiceGroupName + '" name=""'
                        + '                                 class="title-connect" >'
                        + '                      </div>'
                        + '                  </td>'
                        + '              </tr>'
                        + '             <tr>'
                        + '                  <th class="tl">서비스코드</th>'
                        + '                  <td>'
                        + '                      <div class="ipt_box">'
                        + '                          <input type="text" id="subServiceGroup' + i + '" value="' + e.subServiceGroup + '" name=""'
                        + '                                 class="title-connect" readonly>'
                        + '                      </div>'
                        + '                  </td>'
                        + '              </tr>'
                        + '              <tr>'
                        + '                  <th class="tl">시나리오 그룹코드</th>'
                        + '                  <td>'
                        + '                      <div class="ipt_box type-flex">'
                        + '                          <input type="text" id="subOprMngCode' + i + '" value="' + e.subOprMngCode + '" name="" class="" readonly>'
                        + '                      </div>'
                        + '                      <div class="ipt_box ">'
                        + '                          <div class="create-code-list">'
                        + '                          </div>'
                        + '                      </div>'
                        + '                  </td>'
                        + '              </tr>'
                        + '              <tr>'
                        + '                  <th class="tl">시나리오그룹 설명</th>'
                        + '                  <td>'
                        + '                      <div class="ipt_box">'
                        + '                          <input type="text" id="subServiceGroupDesc' + i + '" value="' + e.subServiceGroupDesc + '" name="" class="">'
                        + '                      </div>'
                        + '                  </td>'
                        + '              </tr>'
                        + '              <tr>'
                        + '                  <th class="tl">사용여부</th>'
                        + '                  <td>'
                        + '                      <div class="sel_box">'
                        + '                          <select class="wide" id="subUseYn' + i + '">'
                    if (e.subUseYn == 'Y') {
                        html += '                              <option value="Y" selected>Y</option>'
                            + '                              <option value="N">N</option>'
                    } else if (e.subUseYn == 'N') {
                        html += '                              <option value="N" selected>N</option>'
                            + '                              <option value="Y">Y</option>'
                    }
                    html += '                          </select>'
                        + '                      </div>'
                        + '                  </td>'
                        + '              </tr>'
                        + '              <tr>'
                        + '                  <th class="tl">권한부여</th>'
                        + '                  <td class="tl">'
                        + '                      <div class="content tree tree-maxHeight type-chk">'
                        + '                          <div id="treeWrap' + i + '"  class="tree_wrap' + i + '">  '
                        + '                          </div>'
                        + '                      </div>'
                        + '                  </td>'
                        + '              </tr>'
                        + '              </tbody>'
                        + '          </table>'
                        + '          </div>'
                        + '          </div>'
                        + '          </div>'
                        + '          </li>';
                    $('.tbl-card').html(html);
                    // $('.tree_wrap').html(treeWrap(data.mainMenu));

                    $('.tbl-card-li').each(function () {
                        $(this).find('.tbl-card-title').on('click', function () {
                            $(this).parents('.tbl-card-li').toggleClass('on');
                        })
                    });
                    treeWrap(e, mainMenu, mainPolicyVal, policyParent, i);
                });
            }
        })
    }

    function treeWrap(subService, mainMenu, mainPolicyVal, policyParent, idx) {
        var treeData = [];
        mainMenu.forEach(function (e, i) {
            var setId = e.authName + idx;
            if (policyParent[e.authName] == '#') {
                var setParent = policyParent[e.authName];
            } else {
                var setParent = policyParent[e.authName] + idx;
            }

            if($('#mainServiceGroup').val() == subService.subServiceGroup){
                if (subService.subPolicyVal.includes(e.authName)) {
                    treeData[i] = {
                        id: setId,
                        parent: setParent,
                        text: e.menuName,
                        state: {
                            opened: true
                            ,selected: true
                            ,disabled: true
                        }

                    };
                } else {
                    treeData[i] = {
                        id: setId,
                        parent: setParent,
                        text: e.menuName,
                        state: {
                            opened: false
                            ,selected: false
                            ,disabled: true
                        }
                    };
                }
            }
            else {
                if (subService.subPolicyVal.includes(e.authName)) {
                    treeData[i] = {
                        id: setId,
                        parent: setParent,
                        text: e.menuName,
                        state: {
                            opened: true
                            ,selected: true
                        }

                    };
                } else {
                    treeData[i] = {
                        id: setId,
                        parent: setParent,
                        text: e.menuName,
                        state: {
                            opened: false
                            ,selected: false
                        }
                    };
                }
            }


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

    function newTreeWrap() {
        var treeData = [];

        $("#newServiceGroup").val("");
        $("#newServiceGroupName").val("");
        $("#newServiceGroupDesc").val("");
        $("#newUseYn").val("Y");
        $("#newDoubleCheck").val("N");
        $("#newOprMngCode").val("");

        if (getServiceGroupQueryString() == null) {
            //유저어드민
            setUrl = "<c:url value='/admin/common/system/serviceGroup/select'/>";
        } else {
            //시스템어드민
            setUrl = "<c:url value='/admin/common/system/serviceGroup/select'/>" + "?serviceGroup=" + getServiceGroupQueryString();
        }
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            async: false,
            datatype: "JSON",
            url: setUrl,
            success: function (data) {
                // console.log(JSON.stringify(data));
                var html = '';
                $('#mainServiceGroup').val(data.mainServiceGroup);
                $('#mainServiceGroupName').val(data.mainServiceGroupName);
                $('#mainUseYn').val(data.mainUseYn);
                $('#mainOprMngCode').val(data.mainOprMngCode);
                $('#custCode').val(data.custCode);
                var mainMenu = data.mainMenu;
                var mainPolicyVal = data.mainPolicyVal;
                var policyParent = data.policyParent;
                // mainMenu.push(data.mainMenu);
                // mainPolicyVal.push(data.mainPolicyVal);
                mainMenu.forEach(function (e, i) {
                    treeData[i] = {
                        id: e.authName,
                        parent: policyParent[e.authName],
                        text: e.menuName,
                        state: {
                            opened: false,
                            selected: true
                        }
                    };
                });

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


    }
    ;


</script>


<header id="header">
    <%@ include file="/WEB-INF/jsp/adm/include/header.jsp" %>
</header>
<c:import url="/adm/menu/getLnbMenu.do"/>

<body>
<h1>ICOMSYS ADMIN</h1>

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

<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">
                    <tr>
                        <th class="tl">서비스그룹명</th>
                        <td>
                            <div class="ipt_box">
                                <%--                                <input type="text" id="mainServiceGroupName" value="mainServiceGroup" name="" class="" readonly>--%>
                                <input type="text" id="mainServiceGroupName" name="" class="" readonly>
                            </div>
                        </td>
                    </tr>


                    <tr>
                        <th class="tl">서비스코드</th>
                        <td>
                            <div class="ipt_box type-flex">
                                <input type="text" id="mainServiceGroup" value="codecode" name="" class="" readonly>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">시나리오코드</th>
                        <td>
                            <div class="ipt_box type-flex">
                                <input type="text" id="mainOprMngCode" value="codecode" name="" class="" readonly>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">사용여부</th>
                        <td>
                            <input type="text" id="mainUseYn" value="Y" name="" class="" readonly>
                        </td>
                    </tr>

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


        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">시나리오 그룹 <em class="red">*</em></h2>
                </div>
                <div class="btn_wrap fr">
                    <a href="#" id="btnRegModal" rel="reg_modal" class="btn line modalLoad">추가</a>
                </div>
            </div>


            <div class="tbl-card-wrap">
                <ul class="tbl-card">
                </ul>
            </div>
        </div>
    </div>

</section>


<div class="modal" id="reg_modal">
    <div class="modal_header">
        <h3>시나리오그룹 신규등록</h3>
    </div>
    <div class="modal_body">
        <div class="modal_cont">
            <form id="serviceInfo">
                <div class="tbl">
                    <table class="edit hght">
                        <colgroup>
                            <col width="150px">
                            <col width="auto">
                        <tbody>
                        <tr>
                            <th class="tl">시나리오 그룹명<em class="red">*</em></th>
                            <td>
                                <div class="ipt_box">
                                    <input type="text" id="newServiceGroupName" value="" name="" class="title-connect">
                                </div>
                            </td>
                        </tr>


                        <tr>
                            <th class="tl">서비스코드<em class="red">*</em></th>
                            <td>
                                <div class="ipt_box type-flex">
                                    <input type="text" id="newServiceGroup" value="" name="" class="">
                                    <a href="#" class="btn grey" id="btnDoubleCheck">중복확인</a>
                                </div>
                                <div class="ipt_box ">
                                    <div class="create-code-list">
                                        <input type="hidden" id="newDoubleCheck" value="N" name="" class="">
                                    </div>
                                </div>
                            </td>
                        </tr>

                        <%--                        <tr>--%>
                        <%--                            <th class="tl">시나리오 그룹코드</th>--%>
                        <%--                            <td>--%>
                        <%--                                <div class="ipt_box" id="newOprDiv">--%>
                        <%--                                    <input type="text" id="newOprMngCode" value="" name=""--%>
                        <%--                                           class=" title-connect" readonly>--%>
                        <%--                                </div>--%>
                        <%--                            </td>--%>
                        <%--                        </tr>--%>

                        <tr>
                            <th class="tl">시나리오그룹 설명<em class="red">*</em></th>
                            <td>
                                <div class="ipt_box">
                                    <input type="text" id="newServiceGroupDesc" value="" name="" class="">
                                </div>
                            </td>
                        </tr>

                        <tr>
                            <th class="tl">사용여부 <em class="red">*</em></th>
                            <td>
                                <div class="sel_box">
                                    <select class="wide" id="newUseYn">
                                        <option value="Y" selected>Y</option>
                                        <option value="N">N</option>
                                    </select>
                                </div>
                            </td>
                        </tr>

                        <tr>
                            <th class="tl">권한부여<em class="red">*</em></th>
                            <td class="tl">
                                <div class="content tree tree-maxHeight type-chk">
                                    <div id="newTreeWrap" class="tree_wrap">
                                    </div>
                                </div>
                            </td>
                        </tr>

                        </tbody>
                    </table>
                </div>
            </form>
        </div>
    </div>
    <div class="modal_footer">
        <div class="btn_wrap fr">
            <a href="#" class="btn" id="btnSaveCust">저장</a>
        </div>
    </div>
    <div class="modal_controller">
        <a href="#" class="close">close</a>
    </div>
</div>


</body>
</html>

