<%@ 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 () {
            getCust();
            getOpr();
            authChoice($('#newServiceGroup option:selected').val());
            $("#Content").on("keyup", function (key) {
                if (key.keyCode == 13) {
                    fnCustSearchBtn();
                }
            });

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

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

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


            //서비스그룹 추가 -> 적용버튼
            $('#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')
                        }
                    );
            });

            $('#btnSave').on('click', function () {
                // console.log("저장버튼");
                saveBtn();
            });
            $('#btnDel').on('click', function () {
                // console.log("삭제버튼");
                delBtn();
            });
            $('#doubleCheckBtn').on('click', function () {
                // console.log("중복확인버튼");
                userDoubleCheck();
            });

            $('#newUserPass').keyup(function (e) {
                newUserPassCheck(e.keyCode)
            });

            $('#newUserPassChk').keyup(function (e) {
                newUserDoublePassCheck(e.keyCode)
            });
            $('.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);
                    }
                })
            });
        }
    );

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

    function delBtn() {
        listgo();
    }

    function saveBtn() {
        var mainOpr = $('#mainOpr option:selected').val()
        var userId = $('#newUserId').val();
        var pas = $('#newUserPass').val();
        var pasChk = $('#newUserPassChk').val();
        var userName = $('#newUserName').val();
        var useYn = $('#newUseYn option:selected').val();
        var userMail = $('#newUserMail').val();
        var userMobile = $('#newUserMobile').val();
        var userRoleVal = $('#newUserRoleVal').val();
        var json = {};
        var addServiceAuthList = new Array();
        // $("#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)
        // })

        $(".tbl-card").children('li').each(function (i, e) {
            var addServiceAuth = {};
            var ids = $(this).find("input:eq(0)").attr("id").replaceAll("addServiceGroup", "");
            var authList = new Array();
            $('#newAuthChk' + ids).find('li').each(function (i, e) {
                var chkid = $(this).find('input').attr('id').replaceAll("chk", "")
                if ($(this).find('input').is(':checked')) {
                    authList.push(chkid);
                }
            });
            addServiceAuth.addService = ids;
            addServiceAuth.authList = authList;
            addServiceAuthList.push(addServiceAuth);
        })

        json.lastUseServiceGroup = mainOpr;
        json.userId = userId;
        json.pass = pas;
        json.userName = userName
        json.useYn = useYn;
        json.userMail = userMail;
        json.userMobile = userMobile;
        json.roleVal = userRoleVal;
        json.addServiceAuthList = addServiceAuthList;
        // console.log(JSON.stringify(json));

        var reg = /(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{10,}$/;
        if (pas.length < 10 || pas.length > 20) {
            $.utils.warning("10자리 ~ 20자리 이내로 입력해주세요.");
            return false;
        }
        if (pas.search(/\s/) != -1) {
            $.utils.warning("비밀번호는 공백 없이 입력해주세요.");
            return false;
        }
        if (false === reg.test(pas)) {
            $.utils.warning('비밀번호는 8자 이상이어야 하며, 숫자/문자/특수문자를 모두 포함해야 합니다.');
            return false;
        }

        if ($('#newUserIdYn').val() === 'N') {
            // $.utils.success("사용가능합니다");
            $.utils.warning("중복확인을 해주세요.");
            return;
        }
        if ($('#newUserPassDoubleChkVal').val() === 'N') {
            $.utils.warning("비밀번호가 일치하지 않습니다.");
            return;
        }

        if (json.addServiceAuthList.length < 1) {
            $.utils.warning("서비스그룹을 추가해주세요.");
            return;
        }
        //밸류체크는안하는걸로,
        json.addServiceAuthList.forEach(function (e, i) {
            // console.log("e" + JSON.stringify(e))
            // console.log("i" + JSON.stringify(i))
            // console.log($(e).length)
        })

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/user/save'/>",
            data: JSON.stringify(json)
        }).complete(function (data) {
            // console.log(data.status);
            var result = data.status;
            if (result == 200) {
                // alert("성공하였습니다. 리스트로 돌아갑니다.")
                $.utils.success("성공하였습니다. 리스트로 돌아갑니다.");
                // $.utils.warning("중복확인을 해주세요.");
                listgo();
            } else {
                // alert("실패하였습니다.")
                $.utils.warning("실패하였습니다.");
            }
        });

    }


    function addServiceGroup() {
        var serviceGroup = $('#newServiceGroup option:selected').val();
        var serviceGroupName = $('#newServiceGroup option:selected').text();
        if ($('#newServiceGroup option:selected').val() === 'ALL') {
            // $.utils.success("성공하였습니다. 리스트로 돌아갑니다.");
            $.utils.warning("시나리오그룹을 선택해주세요.");
            // alert("시나리오그룹을 선택해주세요");
            return;
        }

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

        var html3 = '';
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/user/authlist'/>" + "?serviceGroup=" + serviceGroup,
            success: function (data) {
                data.forEach(function (e, i) {
                    html3
                        += ' <li>'
                        + '     <input type="checkbox" name="checkbox" id="chk' + e.authGroupSeq + '">'
                        + ' <label for="chk01">' + e.policyGroupName + '</label>'
                        + ' </li>';
                });
            }
        });

        var html2 = '';
        html2 += ' <tr>'
            + '    <th class="tl">시나리오그룹</th>'
            + '    <td class="tl">'
            + '        <div class="ipt_box">'
            + '            <input type="text" id="addServiceGroup' + serviceGroup + '" value="' + serviceGroupName + '" name="" readonly class="">'
            + '        </div>'
            + '    </td>'
            + '</tr>'
            + '<tr>'
            + '    <th class="tl">권한선택</th>'
            + '    <td class="tl">'
            + '             <ul class="list-user-group-box-ul" id="newAuthChk' + serviceGroup + '">'
            + html3
            + '             </ul>'
            + '    </td>'
            + '</tr>';

        var html1 = '';
        html1
            += '<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(html1);
        $('#reg_modal').hide();
        removeDim();

    }

    function authChoice(servoceGroup) {

        var html1 = '';
        if (servoceGroup === 'ALL') {
            html1
                += ' <li class="select2-selection__choice" id="defaultChkId">'
                + ' <div class="chk_box">'
                + '     <input type="checkbox" name="checkbox" id="chk01">'
                + ' <label for="chk01">시나리오그룹을선택해주세요</label>'
                + '</div>'
                + ' </li>';
            setTimeout(function () {
                $('#newAuthChk').html(html1);
            }, 1)
            // setTimeout($('#newAuthChk').html(html), 1);
        } else {

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "JSON",
                url: "<c:url value='/admin/common/system/user/authlist'/>" + "?serviceGroup=" + servoceGroup,
                success: function (data) {
                    data.forEach(function (e, i) {
                        html1
                            += ' <li class="select2-selection__choice" >'
                            + ' <div class="chk_box">'
                            + '     <input type="checkbox" name="checkbox" id="chk' + e.authGroupSeq + '">'
                            + ' <label for="chk01">' + e.policyGroupName + '</label>'
                            + '</div>'
                            + ' </li>';
                    });
                }
            });
            setTimeout(function () {
                $('#newAuthChk').html(html1);
            }, 100)

        }
        ;

    }

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


    function getCust() {
        var html1 = '';
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/user/cust/select'/>",
            success: function (data) {
                // console.log(JSON.stringify(data));

                data.forEach(function (e, f) {
                    html1 += '<option value="' + e.custCode + '">' + e.custName + '</option>';
                });
            }
        })

        // console.log("== "+html1);
        $('#newCustUser').html(html1);
        $('#newCustUser').niceSelect('update');

        var custCode = $('#newCustUser option:selected').val();
        // console.log(custCode)
        SelectServiceGroupUpdate(custCode);
    }
    ;

    function SelectServiceGroupUpdate(custCode){
        var html1 = '';
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/userAdmin/service/select'/>" + "?custCode="+custCode,
            success: function (data) {
                // console.log(JSON.stringify(data));
                data.forEach(function (e, f) {
                    // console.log("data"+ JSON.stringify(e))
                    // html += '<option value="' + e.serviceGroup + '">' + e.serviceGroupName + '</option>';
                    // console.log("data"+ JSON.stringify(e))
                    html1 += '<option value="' + e.serviceGroup + '">' + e.serviceGroupName + '</option>';
                });
            }
        })
        $('#newServiceGroup').html(html1);
        $('#newServiceGroup').niceSelect('update');
    }


    function userDoubleCheck() {

        var userId = $('#newUserId').val()

        if (userId.length < 1) {
            // alert("1글자 이상 입력해주세요");
            // $.utils.success("성공하였습니다. 리스트로 돌아갑니다.");
            $.utils.warning("1글자 이상 입력해주세요.");
            return;
        }
        if (userId.length > 20) {
            // alert("20글자 이하로 입력해주세요");
            $.utils.warning("20글자 이하로 입력해주세요.");
            return;
        }

        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/user/doubleCheck'/>" + "?userId=" + userId,
            success: function (data) {
                // console.log(data);
                if (data == "Y") {
                    // alert("사용가능합니다");
                    $.utils.success("사용가능합니다.");
                    // $.utils.warning("1글자 이상 입력해주세요.");
                    $('#newUserIdYn').val("Y");
                } else {
                    $.utils.warning("사용중인 아이디입니다.");
                }
            }
        });
    }

    function newUserPassCheck() {
        var text1 = $('#newUserPass').val();
        var text2 = $('#newUserPassChk').val();
        // console.log("key " + text1);

        var htmlY = '<div class="ipt_box"><p class="status-txt"><em class="green">사용가능합니다.</em></p>'
            + '<input type="hidden" id="newUserPassChkVal" value="Y" name="" class=""></div>';
        var htmlN = '<div class="ipt_box"><p class="status-txt"><em class="red">사용할수 없습니다.</em></p>'
            + '<input type="hidden" id="newUserPassChkVal" value="N" name="" class=""></div>';
        var regDesc = '<div class="ipt_box"><p class="status-txt"><em class="red">비밀번호는 8자 이상이어야 하며, 숫자/문자/특수문자를 모두 포함해야 합니다.</em></p>'
            + '<input type="hidden" id="newUserPassChkVal" value="N" name="" class=""></div>';
        // '비밀번호는 8자 이상이어야 하며, 숫자/문자/특수문자를 모두 포함해야 합니다.'

        var reg = /(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{10,}$/;

        if(text2.length > 7){
            if (text1 === text2) {
                $('#passDoubleCheckUi').html(htmlY)
            }
            else {
                $('#passDoubleCheckUi').html(htmlN)
            }
        }

        if (text1.length < 10 || text1.length > 20) {
            $('#passCheckUi').html(htmlN)
            return;
        }
        else if (text1.search(/\s/) != -1) {
            $('#passCheckUi').html(htmlN)
            return false;
        }
        else if (false === reg.test(text1)) {
            $('#passCheckUi').html(regDesc)
            return false;
        }
        else  if ($('#newUserPassDoubleChkVal').val() == "Y") {
            newUserDoublePassCheck()
        }
        else {
            $('#passCheckUi').html(htmlY)
            return true;
        }
        return;
    }

    function newUserDoublePassCheck() {
        var text1 = $('#newUserPass').val();
        var text2 = $('#newUserPassChk').val();


        var htmlY = '<div class="ipt_box"><p class="status-txt"><em class="green">사용가능합니다.</em></p>'
            + '<input type="hidden" id="newUserPassDoubleChkVal" value="Y" name="" class=""></div>';
        var htmlN = '<div class="ipt_box"><p class="status-txt"><em class="red">일치하지 않습니다.</em></p>'
            + '<input type="hidden" id="newUserPassDoubleChkVal" value="N" name="" class=""></div>';
        // console.log("key " + text1);
        // console.log("key " + text2);
        if (text1 === text2) {
            $('#passDoubleCheckUi').html(htmlY)
            $('#passCheckUi').html(htmlY)
            ;
        } else {
            $('#passDoubleCheckUi').html(htmlN)
            return;
        }

        return;
    }


</script>


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

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

<section id="Content" class="bot_common">
    <div class="location">
        <ul>
            <li class="home"><a href="#">HOME</a></li>
            <li><a href="#">시스템관리</a></li>
            <li><a href="#">운영자관리</a></li>
            <li><a href="#">운영자생성</a></li>
        </ul>
    </div>

    <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="sel_box">
                                <select class="wide" id="newCustUser">
                                    <option value="ALL">전체</option>
                                </select>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">운영자 ID <em class="red">*</em></th>
                        <td>
                            <div class="ipt_box type-flex">
                                <input type="text" id="newUserId" name="" class="">
                                <input type="hidden" id="newUserIdYn" value="N" name="" class="">
                                <a href="#" id="doubleCheckBtn" class="btn basic">중복확인</a>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">비밀번호<em class="red">*</em></th>
                        <td>
                            <div class="ipt_box">
                                <input type="password" id="newUserPass" value="" name="" class="">
                            </div>
                            <span id="passCheckUi"></span>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">비밀번호 확인<em class="red">*</em></th>
                        <td>
                            <div class="ipt_box">
                                <input type="password" id="newUserPassChk" value="" name="" class="">
                            </div>
                            <span id="passDoubleCheckUi"></span>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">이름 <em class="red">*</em></th>
                        <td>
                            <div class="ipt_box">
                                <input type="text" id="newUserName" 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">Y</option>
                                    <option value="N">N</option>
                                </select>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">이메일 주소</th>
                        <td>
                            <div class="ipt_box">
                                <input type="text" id="newUserMail" value="" name="" class="">
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">핸드폰 번호</th>
                        <td>
                            <div class="ipt_box">
                                <input type="text" id="newUserMobile" value="" name="" class="">
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">등급선택</th>
                        <td>
                            <div class="sel_box">
                                <select class="wide" id="newUserRoleVal">
<%--                                    <option value="USER">일반사용자</option>--%>
                                    <option value="USERADMIN">운영자</option>
                                </select>
                            </div>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="cont_box">

            <div class="box_title">
                <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="btnDel">취소</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>
                        <span id="copySpan">
                        <tr>
                            <th class="tl">시나리오그룹</th>
                            <td>
                                <div class="sel_box">
                                    <select id="newServiceGroup" class="wide">
                                        <option value="ALL">전체</option>
                                    </select>
                                </div>
                            </td>
                        </tr>

<%--                        <tr>--%>
<%--                            <th class="tl">권한선택</th>--%>
<%--                            <td>--%>
<%--                                <ul class="list-user-group-box-ul" id="newAuthChk">--%>
<%--                                </ul>--%>
<%--                            </td>--%>
<%--                        </tr>--%>
                        </span>
                        </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>


