<%@ 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>
<body>

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

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

        // 권한 조회
        $('#btnSearchCust').on('click', function () {
            fncSearchCust();
        });

        //커스트코드 중복확인
        $('#btnCustCodeDoubleCheck').on('click', function () {
            // console.log("커스트 중복 클릭")
            fncCustDoubleCheck();
        });
        //서비스코드 중복확인
        $('#btnServiceGroupDoubleCheck').on('click', function () {
            // console.log("서비스 중복 클릭")
            fncServiceDoubleCheck();
        });

        $('#btnCancel').on('click', function () {
            // console.log("취소클릭")
            listgo()
        });
        $('#btnSave').on('click', function () {
            // console.log("저장클릭")
            fncCustSave();

        });

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

        $('#btnSaveCust').on('click', function () {
            addServiceGroup();
            // $('.tbl-card-li').each(function () {
            //     // console.log("???");
            //     $(this).find('.tbl-card-title').on('click', function () {
            //         $(this).parents('.tbl-card-li').toggleClass('on');
            //     })
            // });

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

        // $('#newServiceGroup').change(function () {
        //     ($(this).val())
        // });

    });

    function fncCustSave() {

        var custName = $('#newCustName').val();
        var custCode = $('#newCustCode').val().toUpperCase();
        var custCodeDoubleCheck = $('#newCustCodeDoubleCheck').val();
        var custUseYn = $('#newCustUseYn').val();

        var json = {};
        json.custName = custName;
        json.custCode = custCode;
        json.custCodeDoubleCheck = custCodeDoubleCheck;
        json.custUseYn = custUseYn;

        var addServiceAuthList = new Array();
        $(".tbl-card").children('li').each(function (i, e) {

            var addServiceAuth = {};
            var addServiceGroupName = $(this).find("input:eq(0)").attr("id").replaceAll("addServiceGroupName", "");
            var addServiceGroup = $(this).find("input:eq(1)").attr("id").replaceAll("addServiceGroup", "");
            // var addOprMngCode = $(this).find("input:eq(2)").attr("id").replaceAll("addOprMngCode", "");
            var addServiceGroupDesc = $(this).find("input:eq(2)").attr("id").replaceAll("addServiceGroupDesc", "");
            var addUseYn = $(this).find("input:eq(3)").attr("id");
            var authList = new Array();

            var selectedElms = $("#tree_wrap_" + addServiceGroup).jstree("get_selected", true);
            $.each(selectedElms, function () {
                authList.push(this.id);
            });

            // $('#tree_wrap_' + addServiceGroup).find('li').each(function (i, e) {
            //     var chkid = $(this).find('input').attr('id')
            //         // .replaceAll("tree_wrap_", "")
            //     // console.log(chkid);
            //     if ($(this).find('input').is(':checked')) {
            //         // console.log(chkid);
            //         authList.push(chkid);
            //     }
            // });

            addServiceAuth.addServiceGroupName = addServiceGroupName;
            addServiceAuth.addServiceGroup = addServiceGroup.toUpperCase();
            addServiceAuth.addOprMngCode = custCode + "_RCP_" + addServiceGroup.toUpperCase();
            addServiceAuth.addServiceGroupDesc = addServiceGroupDesc;
            addServiceAuth.addUseYn = addUseYn;
            addServiceAuth.authList = authList;
            addServiceAuthList.push(addServiceAuth);
            // listgo()
        });

        json.addServiceAuthList = addServiceAuthList;


        // console.log(JSON.stringify(json));
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            url: "<c:url value='/admin/common/system/cust/save'/>",
            data: JSON.stringify(json),
        })
            .complete(function (data) {
                // console.log(JSON.stringify(data));
                // console.log(data.status);
                if (data.status == 200) {
                    // console.log("저장하였습니다.")
                    listgo();
                } else if (data.status == 405){
                    $.utils.warning("NLP연결에 실패했습니다.");
                }
                else {
                    $.utils.warning("오류가 발생했습니다.");
                }
            })

    }

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

    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.warning("1글자이상 입력해주세요.");
            // $.utils.success('정상적으로 저장되었습니다.');
            return;
        }
        if (newServiceGroup.length > 20) {
            $.utils.warning("20글자이하로 입력해주세요.");
            return;
        }
        var space = /\s/g;

        if (space.match(newServiceGroup)) {
            $.utils.warning("공백은 입력 할 수 없습니다.");
            return;
        }

        if (RegExp(/[^a-zA-Z]/).test(newServiceGroup)) {
            $.utils.warning("영어문만 입력가능합니다.");
            return;
        } else {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                datatype: "JSON",
                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") {
                            // alert("사용가능합니다");
                            // $.utils.warning("1글자이상 입력해주세요.");
                            $.utils.success('사용가능합니다.');
                            return;
                        } else {
                            $.utils.warning("중복된코드입니다.");
                            return;
                        }
                    } else {
                    }
                })
            ;
        }
    }

    function addServiceGroup() {

        var custCode = $('#newCustCode').val();
        var serviceGroup = $('#newServiceGroup').val();
        var serviceGroupName = $('#newServiceGroupName').val();
        var serviceGroupDesc = $('#newServiceGroupDesc').val();
        var oprMngCode = $('#newOprMngCode').val();
        var uesYn = $('#newUseYn').val();
        if (custCode.length < 1) {
            // alert("커스트 코드를 입력해주세요");
            $.utils.warning("커스트 코드를 입력해주세요.");
            // $.utils.success('사용가능합니다.');
            return;
        }

        if ($('#newServiceGroup option:selected').val() === 'ALL') {
            $.utils.warning("서비스그룹을 선택해주세요.");
            return;
        }

        if (document.getElementById("addServiceGroup" + serviceGroup)) {
            $.utils.warning("이미 추가된 서비스그룹입니다.");
            return;
        }
        var html3 = '';

        var html2 = '';
        html2 += ''
            + ' <tr>'
            + '    <th class="tl">서비스그룹</th>'
            + '    <td>'
            + '        <div class="ipt_box">'
            + '            <input type="text" id="addServiceGroupName' + serviceGroupName + '" value="' + serviceGroupName + '" name="" readonly class="">'
            + '        </div>'
            + '    </td>'
            + '</tr>'
            + ' <tr>'
            + '    <th class="tl">서비스코드</th>'
            + '    <td>'
            + '        <div class="ipt_box">'
            + '            <input type="text" id="addServiceGroup' + serviceGroup + '" value="' + serviceGroup + '" name="" readonly class="">'
            + '        </div>'
            + '    </td>'
            + '</tr>'
            // + ' <tr>'
            // + '    <th class="tl">운영관리코드</th>'
            // + '    <td>'
            // + '        <div class="ipt_box">'
            // + '            <input type="text" id="addOprMngCode' + oprMngCode + '" value="' + serviceGroupName + '" name="" readonly class="">'
            // + '        </div>'
            // + '    </td>'
            // + '</tr>'
            + '    <th class="tl">서비스그룹설명</th>'
            + '    <td>'
            + '        <div class="ipt_box">'
            + '            <input type="text" id="addServiceGroupDesc' + serviceGroupDesc + '" value="' + serviceGroupDesc + '" name="" readonly class="">'
            + '        </div>'
            + '    </td>'
            + '</tr>'
            + ' <tr>'
            + '  <th class="tl">사용여부 <em class="red">*</em></th>'
            + '  <td>'
            + ' <div class="sel_box">'
            + '  <select class="wide" id="addUseYn">'
            + '        <option value="Y" selected>Y</option>'
            + '       <option value="N">N</option>'
            + '   </select>'
            + '  </div>'
            + ' </td>'
            + '<tr>'
            + '  <th class="tl">권한</th>'
            + '  <td class="tl">'
            + '  <div class="content tree tree-maxHeight type-chk">'
            + '  <div class="tree_wrap" id="tree_wrap_' + serviceGroup + '">'
            + '    </div>'
            + '   </div>'
            + '   </td>'
            + '</tr>'
        ;

        var html = '';
        html
            += '<li class="tbl-card-li" id="tbl-card-li' + serviceGroup + '">'
            + '<div class="tbl-card-li-inner">'
            + '  <div class="tbl-card-title" id="tbl-card-title' + serviceGroup + '">'
            + '     <div class="fl title-connected">' + serviceGroupName + '</div>'
            + '   </div>'
            + '         <div class="tbl-card-data">'
            + '         <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="150px">'
            + '                  <col width="auto">'
            + '           </colgroup>'
            + '          <tbody>'
            + html2
            + '          </tbody>'
            + '          </table>'
            + '      </div>'
            + '      </div>'
            + '      </div>'
            + '</li>';

        $('.tbl-card').append(html);
        $('#reg_modal').hide();
        removeDim();

        treeWrap(getMenuBase(), getPolicyParent(), serviceGroup);
    }

    function treeWrap(mainMenu, policyParent, serviceGroup) {
        // console.log("treeWrap mainMenu  -" + JSON.stringify(mainMenu));
        // console.log("treeWrap policyParent  -" + JSON.stringify(policyParent));
        var treeData = [];

        mainMenu.forEach(function (e, i) {
            treeData[i] = {
                id: e.authName,
                parent: policyParent[e.authName],
                text: e.menuName,
                state: {
                    opened: false,
                    selected: true
                }
            };
        });

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

            });
        }, "1");
    }

    function getPolicyParent() {
        var datas = new Array();
        datas = $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/adm/menu/jstree/policy/parent'/>",
            success: function (data) {
                return data;
            }
        });
        return datas.responseJSON;
    }

    function getMenuBase() {
        var datas = new Array();
        datas = $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/cust/policybase'/>",
            success: function (data) {
                return data;
            }
        });
        return datas.responseJSON;
    }

    function fncCustDoubleCheck() {
        var custCode = $('#newCustCode').val().toUpperCase();
        var regType = /^[A-Za-z0-9]*$/;
        // console.log(custCode.length)
        if (custCode.length < 1) {
            $.utils.warning('고객사코드를 입력해주세요.');
            return;
        }
        var regType = /^[A-Za-z0-9]*$/;
        if (!regType.test(custCode)) {
            $.utils.warning('영문, 숫자만입력가능합니다.');
            return;
        }

        var yn = $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/cust/doubleCheck'/>" + '?custCode=' + custCode,
            success: function (data) {

                if (data === 'Y') {
                    // alert("사용할수있는 코드입니다")
                    $.utils.success('사용할수있는 코드입니다.');
                    // $.utils.warning("사용할수없는 코드입니다.");
                } else {
                    $.utils.warning("사용할수없는 코드입니다.");
                    // alert("사용할수없는 코드입니다")
                }

                return data;
            }
        });
        // console.log(JSON.stringify(yn.responseText));

        $('#newCustCodeDoubleCheck').val(yn.responseText);

    };

    function fncServiceDoubleCheck() {
        var serviceGroup = $('#newServiceGroup').val().toUpperCase();

        if (serviceGroup.length < 1) {
            $.utils.warning('서비스코드를 입력해주세요.');
            return;
        }
        var regType = /^[A-Za-z0-9]*$/;
        if (!regType.test(serviceGroup)) {
            $.utils.warning('영문, 숫자만입력가능합니다.');
            return;
        }

        var yn = $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/cust/service/doubleCheck'/>" + '?serviceGroup=' + serviceGroup,
            success: function (data) {
                if (data === 'Y') {
                    // alert("사용할수있는 코드입니다")
                    $.utils.success('사용할수있는 코드입니다.');
                    // $.utils.warning("사용할수없는 코드입니다.");
                } else {
                    $.utils.warning("사용할수없는 코드입니다.");
                    // alert("사용할수없는 코드입니다")
                }
            }
        });
        // console.log(JSON.stringify(yn.responseText));
        $('#newCustCodeDoubleCheck').val(yn.responseText);
        $('#newServiceGroupDoubleCheck').val(yn);
    };

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


</script>
<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>
                    <tr>
                        <th class="tl">고객사명 <em class="red">*</em></th>
                        <td>
                            <div class="ipt_box">
                                <input id="newCustName" type="text" value="" name="" class="">
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th class="tl">고객사코드 <em class="red">*</em></th>
                        <td>
                            <div class="ipt_box type-flex">
                                <input id="newCustCode" type="text" value="" name="" class="">
                                <input id="newCustCodeDoubleCheck" type="hidden" value="N" name="" class="">
                                <a href="#" id="btnCustCodeDoubleCheck" class="btn basic">중복확인</a>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">사용여부 <em class="red">*</em></th>
                        <td>
                            <div class="sel_box">
                                <select class="wide" id="newCustUseYn">
                                    <option value="Y">Y</option>
                                    <option value="N">N</option>
                                </select>
                            </div>
                        </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 class="cont_box">
            <div class="btn_wrap center">
                <a href="#" class="btn basic grey" id="btnCancel">취소</a>
                <a href="#" class="btn basic" id="btnSave">저장</a>
            </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">서비스그룹명</th>
                            <td>
                                <div class="ipt_box">
                                    <input type="text" id="newServiceGroupName" value="" name="" class="title-connect">
                                </div>
                            </td>
                        </tr>

                        <tr>
                            <th class="tl">서비스코드</th>
                            <td>
                                <div class="ipt_box type-flex">
                                    <input type="text" id="newServiceGroup" value="" name="" class="">
                                    <input type="hidden" id="newServiceGroupDoubleCheck" value="N" name="" class="">
                                    <a href="#" class="btn grey" id="btnServiceGroupDoubleCheck">중복확인</a>
                                </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">서비스그룹 설명</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="newServiceUseYn">
                                        <option value="Y" selected>Y</option>
                                        <option value="N">N</option>
                                    </select>
                                </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>

