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


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

        getOpr();

        getQueryString();
        getViewPageData();
        authChoice($('#newServiceGroup option:selected').val());

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

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

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

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

        function delBtn() {
            listgo();
        }

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

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


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

    });

    function getUv(){
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            data: data,
            url: "<c:url value='/admin/common/system/user/chk/reset'/>",
        }).complete(function (data) {
            // console.log(data.status);
            var result = data.status;
            if (result == 200) {
                // alert("성공하였습니다. 리스트로 돌아갑니다.")
                $('#updateLoginCheck').val(0);
            } else {
                $.utils.warning("실패하였습니다.");
            }
        });
    }

    function failCheckBtn() {
        var data = {};
        data.userSeq = getQueryString();
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            data: data,
            url: "<c:url value='/admin/common/system/user/chk/reset'/>",
        }).complete(function (data) {
            // console.log(data.status);
            var result = data.status;
            if (result == 200) {
                // alert("성공하였습니다. 리스트로 돌아갑니다.")
                $('#updateLoginCheck').val(0);
                $.utils.success("초기화 하였습니다.");

            } else {
                // alert("실패하였습니다.")
                $.utils.warning("실패하였습니다.");
            }
        });
    }



    function saveBtn() {

        var userSeq = $('#updateUserSeq').val();
        var userId = $('#updateUserId').val();
        var userName = $('#updateUserName').val();
        var userPass = $('#updateUserPass').val();
        var mobileNo = $('#updateMobile').val();
        var useYn = $('#updateUseYn option:selected').val();
        var loginCheck = $('#updateLoginCheck').val();
        var email = $('#updateEmail').val();
        var roleVal = $('#updateRoleVal option:selected').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.userSeq = userSeq;
        json.userId = userId;
        json.userName = userName;
        json.userPass = userPass;
        json.mobileNo = mobileNo;
        json.useYn = useYn;
        json.loginCheck = loginCheck;
        json.email = email;
        json.roleVal = roleVal;
        json.addServiceAuthList = addServiceAuthList;
        // console.log(JSON.stringify(json));

        // $.utils.success("사용가능합니다.");
        // $.utils.warning("1글자 이상 입력해주세요.");
        if ($('#newUserIdYn').val() === 'N') {
            // alert("중복확인을 해주세요");
            // $.utils.warning("중복확인을 해주세요.");
            return;
        }
        if ($('#newUserPassDoubleChkVal').val() === 'N') {
            // alert("비밀번호가 일치하지 않습니다.");
            $.utils.warning("비밀번호가 일치하지 않습니다.");
            return;
        }
        if(userPass.length > 0){
            var reg = /(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$/;
            if (false === reg.test(userPass)) {
                $.utils.warning("비밀번호를 확인해주세요.");
                return;
            }
        }

        if (userName < 1) {
            $.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/update'/>",
            data: JSON.stringify(json)
        }).complete(function (data) {
            // console.log(data.status);
            var result = data.status;
            if (result == 200) {
                // alert("성공하였습니다. 리스트로 돌아갑니다.")
                $.utils.success("성공하였습니다. 리스트로 돌아갑니다.");
                // $.utils.warning("1글자 이상 입력해주세요.");
                document.location.href = "<c:url value='/admin/common/system/user/manage.do'/>";
            } else {
                // alert("실패하였습니다.")
                $.utils.warning("실패하였습니다.");
            }
        });
    }



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

    function getViewPageData() {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "JSON",
            async: false,
            url: "<c:url value='/admin/common/system/user/viewData'/>" + "?userSeq=" + getQueryString(),
            success: function (data) {
                // console.log("getData---");
                // console.log(JSON.stringify(data));
                $('#updateUserSeq').val(data.userSeq);
                $('#updateUserId').val(data.userId);
                $('#updateUserName').val(data.userName);
                $('#updateMobile').val(data.mobileNo);
                $('#updateUseYn').val(data.useYn).prop('selected',true);
                $('#updateLoginCheck').val(data.loginCheck);
                $('#updateEmail').val(data.email);
                var role = data.roleVal;
                if (role == "SYSTEMADMIN") {
                    $('#updateRoleVal').html('<option value="' + role + '">' + "시스템어드민" + '</option>');
                } else {
                    $('#updateRoleVal').val(role).prop("selected", true);
                }
                $('#updateUseYn').niceSelect('update');
                $('#updateRoleVal').niceSelect('update');
                // $('#updateUserPass').val();
                dataAddServiceGroup(data.useServiceGroup, data.useAuthSeq);
            }
        })
    };

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

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

        if (document.getElementById("addServiceGroup" + serviceGroup)) {
            // alert("이미 추가된 서비스그룹입니다.");
            $.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 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>';
                });
            }
        });

        var html2 = '';
        html2 += ' <tr>'
            + '    <th class="tl">시나리오그룹</th>'
            + '    <td>'
            + '        <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 dataAddServiceGroup(serviceList, useAuthSeq) {

        serviceList.forEach(function (e) {
            var serviceGroup = e.serviceGroup;
            var serviceGroupName = e.serviceName;
            // if (document.getElementById("addServiceGroup" + serviceGroup)) {
            //     alert("이미 추가된 서비스그룹입니다.");
            //     return;
            // }

            var html3 = '';
            e.baseAuthGroup.forEach(function (f, i) {
                // console.log(JSON.stringify(f));
                if (useAuthSeq.includes(f.authGroupSeq)) {
                    html3
                        += ' <li class="select2-selection__choice" >'
                        + '     <input type="checkbox" checked name="checkbox" id="chk' + f.authGroupSeq + '">'
                        + ' <label for="chk01">' + f.policyGroupName + '</label>'
                        + ' </li>';
                } else {
                    html3
                        += ' <li class="select2-selection__choice" >'
                        + '     <input type="checkbox" name="checkbox" id="chk' + f.authGroupSeq + '">'
                        + ' <label for="chk01">' + f.policyGroupName + '</label>'
                        + ' </li>';
                }
            });


            var html2 = '';
            html2 += ' <tr>'
                + '    <th class="tl">시나리오그룹</th>'
                + '    <td>'
                + '        <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();
        });

        //마지막건 토글
        // $('.tbl-card').find('.tbl-card-title').last()
        //     .on('click', function () {
        //             $(this).parents('.tbl-card-li').toggleClass('on')
        //         }
        //     );

        //전체 토글
        $('.tbl-card-li').each(function () {
            // console.log("???");
            $(this).find('.tbl-card-title').on('click', function () {
                $(this).parents('.tbl-card-li').toggleClass('on');
            })
        });

    }


    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)

        }
        ;

    }


</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>
        </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">사용자 ID <em class="red">*</em></th>
                        <td>
                            <div class="ipt_box type-flex">
                                <input type="hidden" id="updateUserSeq" name="" class="" readonly>
                                <input type="text" id="updateUserId" value="아이디아이이" name="" class="" readonly>
                            </div>
                        </td>
                    </tr>

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

                    <tr>
                        <th class="tl">비밀번호 오류회수<em class="red">*</em></th>
                        <td>
                            <div class="ipt_box type-flex">
                                <input type="text" id="updateLoginCheck" value="" name="" class="" readonly>
                                <a href="#" id="failCheckBtn" class="btn basic">오류회수 초기화</a>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">이름 <em class="red">*</em></th>
                        <td>
                            <div class="ipt_box">
                                <input type="text" id="updateUserName" value="홍길동" name="" class="">
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="tl">사용여부 <em class="red">*</em></th>
                        <td>
                            <div class="sel_box">
                                <select class="wide" id="updateUseYn">
                                    <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" value="" id="updateEmail" name="" class="">
                            </div>
                        </td>
                    </tr>

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

                    <tr>
                        <th class="tl">등급선택</th>
                        <td>
                            <div class="sel_box">
                                <select class="wide" id="updateRoleVal">
                                    <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>


