<%@page import="java.net.URLDecoder"%>
<%@ page contentType="text/html; charset=UTF-8"
         import="java.net.URLEncoder" import="java.util.Date"
         import="java.text.SimpleDateFormat" import="kr.co.kihyun.util.MDate"
         import="kr.co.kihyun.lang.MLong" import="kr.co.kihyun.lang.MString"
         import="kr.co.kihyun.moumi.Moumi" import="kr.co.kihyun.moumi.MoumiUtil"
         import="kr.co.kihyun.beans.user.HttpSSOLogin"
         import="kr.co.kihyun.beans.user.UserGroup"
         import="kr.co.kihyun.beans.user.User"
         import="kr.co.kihyun.beans.user.UserGroupList"
         import="kr.co.kihyun.beans.user.Dept"
         import="kr.co.kihyun.lang.Encoder"
         import="kr.co.kihyun.beans.entity.MUser" import="java.util.List"
         import="javax.jdo.PersistenceManager" import="javax.jdo.Transaction"
         import="kr.co.kihyun.beans.entity.*"
         import="kr.co.kihyun.beans.entity.util.*"
         import="kr.co.kihyun.beans.entity.UserPart" import="java.util.HashMap"
         import="java.util.Map" import="kr.co.kihyun.service.*" import="kr.co.kihyun.service.vo.*"
         %>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%    PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
    Transaction tx = pm.currentTransaction();
    try {
        /**
         * ******** session내의 userId *********
         */
        String usID = HttpSSOLogin.getLoginID(request);
        String dtID = HttpSSOLogin.getDeptID(request);
        int sysAuth = HttpSSOLogin.getSysAuth(request);

        /**
         * **** Parameter ******
         */
        String strPage = clearXSS(request.getParameter("strPage"), "");
        String findOption = clearXSS(request.getParameter("findOption"), "0");
        String findWord = clearXSS(Encoder.toJava(request.getParameter("findWord")), null);

//        String envTagetURL = (String) session.getAttribute("envTagetURL");
//        String dirPath = URLEncoder.encode("<a href=\"/totsys/login/envsetting/group_setup.jsp\" class=\"d11_blue\">" + Moumi.getMessageBundle().getString("moumi.message.tot_doc.configuration") + "</a>", "UTF-8");
        //String uri = URLEncoder.encode("group_setup.jsp?findOption="+MString.checkNull(findOption)+"&findWord="+MString.checkNull(findWord), "UTF-8");

        String method = clearXSS(request.getParameter("method"), "");
        if (method.equals("GET")) {
            findWord = URLDecoder.decode(MString.checkNull(request.getParameter("findWord")), "UTF-8");
        }
//        String uri = URLEncoder.encode("group_setup.jsp?findOption=" + MString.checkNull(findOption), "UTF-8") + "&method=GET";

        if(findWord != null){
            String[] filter_word= {"--", "\\(", "\\)", "\\'", "\\\""};
            for(int ii=0; ii< filter_word.length;ii++){
                findWord = findWord.replaceAll(filter_word[ii], " ");
            }
        }
        boolean isChanged = false;
        //사용여부수정시 사용되는 파라메터
        String mode = clearXSS(request.getParameter("mode"), "");
        if (mode.equals("modify")) {
            tx.begin();
            String[] groupId = request.getParameterValues("groupId");
            String[] orgUseYn = request.getParameterValues("orgUseYn");
            String[] modUseYn = request.getParameterValues("modUseYn");

            for (int i = 0; i < groupId.length; i++) {
                String id = groupId[i];
                String originalUseYn = orgUseYn[i];
                String useYn = modUseYn[i];
                UserPart userPart = (UserPart) pm.getObjectById(UserPart.class, id);
                if (!originalUseYn.equals(useYn)) {
                    userPart.setUseYn(useYn);
                    userPart.setModDate(new Date());
                    isChanged = true;
                    pm.makePersistent(userPart);
                }
                //System.out.println("==============" + i + "=id:" + id + "," + useYn + "-" + originalUseYn);
            }
            if (isChanged) {
                tx.commit();
            } else {
                tx.rollback();
            }
        }

        tx.begin();
        int count = 0;
        /*
         List<UserPart> groupList = null;
         MUser mUser = pm.getObjectById(MUser.class, usID);

         if(mUser.getSysAuth() == SysAuth.SYSADM){//시스템 관리자일경우
         Object filterValue = findWord;
         if(findOption != null && findOption.endsWith("Date"))
         filterValue = new SimpleDateFormat("yy-MM-dd").parse(findWord);

         Map<String, Object> filterMap = new HashMap<String, Object>(1);
         filterMap.put(findOption, filterValue);

         QueryImpl q = new QueryImpl(pm, UserPart.class);
         q.setSearchFilter(filterMap);
         q.setOrdering("id DESC");
         groupList = (List<UserPart>) q.execute();

         }else{
         Object filterValue = findWord;
         if(findOption != null && findOption.endsWith("Date"))
         filterValue = new SimpleDateFormat("yy-MM-dd").parse(findWord);
         groupList = mUser.getGroupList(pm, findOption, filterValue);
         }
         count = groupList.size();
         */
        SimpleDateFormat formatYMD = new SimpleDateFormat("yyyy-MM-dd");
        String findDate = null;
        if (findOption != null && findOption.endsWith("Date")) {
            Date filterValue = new SimpleDateFormat("yy-MM-dd").parse(findWord);
            findDate = formatYMD.format(filterValue);
        }

        /**
         * ********** 리스트 페이지 구성 2***********
         */
        int endPage = 0;
        int pageSize = 0;
        int currentPage = 0;
        int absolutePage = 0;
        int currentPageSetUp = 0;
        int recordSize = 12;

        if (strPage == null || strPage.length() <= 0) {
            currentPage = 1;
        } else if (strPage.equals("null")) {
            currentPage = 1;
        } else {
            try {
                currentPage = Integer.parseInt(strPage);
            } catch (NumberFormatException ex) {
                System.err.println(ex);
            }
        }

        Map params = new HashMap();
        //검색조건 설정
        params.put("type", findOption);
        params.put("partName", findWord);
        params.put("regDate", findDate);
        params.put("usrName", findWord);
        params.put("sysAuth", sysAuth);
        params.put("dtID", dtID);

        if (sysAuth != SysAuth.SYSADM.ordinal()) {
            params.put("usrId", usID);

        }

        UserPartService userPartService = new UserPartService(pm);
        //검색메인쿼리와 레코드갯수조회쿼리를 생성 후 멤버변수로 저장
        userPartService.createUserPartListSearchQuery(params);
        //레코드갯수조회쿼리를 실행하여 레코드갯수를 구함
        count = userPartService.getCount();

        //tx.rollback();
        if ((count % recordSize) == 0) {
            pageSize = (int) (count / recordSize);
        } else {
            pageSize = (int) (count / recordSize) + 1;
        }

        if( currentPage > pageSize ) currentPage = pageSize;

        int startNo = (currentPage - 1) * recordSize + 1;
        int endNo = currentPage * recordSize;

        currentPageSetUp = (int) (currentPage / 10) * 10;
        if (currentPage % 10 == 0) {
            currentPageSetUp -= 10;
        }

        List<UserPartVO> groupList = null;

        //검색목록조회쿼리 실행
        if( count > 0 ) {
            //페이징처리 파라미터 설정
            params.put("startNo", startNo);
            params.put("endNo", endNo);

            //검색메인쿼리를 페이징처리를 위한 쿼리로 변환
            userPartService.convertToPagenatingQuery();

            //만족하는 레코드가 존재하면 조회
            groupList = userPartService.executeQuery(UserPartVO.class);;
        }
        tx.rollback();
%>

<!DOCTYPE html>
<html lang="ko">
	<head>
        <title><%=Moumi.getTitle()%></title>
		<meta charset="UTF-8">
        <link rel="stylesheet" href="images/text.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/kecttep.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/SquareButtons.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/contentStyle.css" type="text/css">
		<link rel="stylesheet" href="/totsys/common/css/basic.css" type="text/css">
        <script src="images/rollover.js"></script>
        <script src="/totsys/common/js/find.js"></script>
        <script src="/totsys/common/js/jquery-1.12.4.min.js"></script>
        <script src="/totsys/common/js/jquery.custom.indicator.js"></script>
        <script>
            function groupAdd() {
                var height = screen.height;
                var width = screen.width;
                var leftpos = width / 2 - 350;
                var toppos = height / 2 - 350;

                var urlname = "/totsys/common/web/report_dept/newgroup_dept_list2.jsp";
                post = window.open(urlname, "post", "width=900,height=600, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,left=" + leftpos + ",top=" + toppos);
                post.focus();
            }
            function modify(partID, partName) {
                var height = screen.height;
                var width = screen.width;
                var leftpos2 = width / 2 - 350;
                var toppos2 = height / 2 - 350;

                var urlname = "/totsys/common/web/report_dept/group_dept_list2.jsp?groupID=" + partID + "&groupName=" + partName;
                post2 = window.open(urlname, "post", "width=900, height=620, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,left=" + leftpos2 + ",top=" + toppos2);
                post2.focus();
            }
            function groupDel(userID, partID) {
                if (confirm("<%=Moumi.getMessageBundle().getString("moumi.message.popup.deletion")%>")) {
                    //location.href = "/servlet/kr.co.kihyun.beans.user.HttpGroupDelete?partID=" + partID + "&userID=" + userID;
                    $.customIndicator.show(window.self);
                    document.f_group_del.partID.value = partID;
                    document.f_group_del.userID.value = userID;
                    document.f_group_del.target = "hiddenFrame";
                    document.f_group_del.submit();
                }
            }
            function showMSG() {
                if (searchForm.findOption.value == "regDate") {
                    msg.style.display = "block";
                } else {
                    msg.style.display = "none";
                }
            }
            /**
             * 그룹의 사용여부에 대한 변경사항을 확인하여 수정요청하는 함수
             * @returns {undefined}
             */
            function fn_groupModify() {
                var isChanged = false;
                if (document.modForm.useYn.length) {
                    for (var i = 0; i < document.modForm.useYn.length; i++) {
                        if (document.modForm.modUseYn[i].value != document.modForm.orgUseYn[i].value) {
                            isChanged = true;
                            break;
                        }
                    }
                } else {
                    if (document.modForm.modUseYn.value != document.modForm.orgUseYn.value) {
                        isChanged = true;
                    }
                }
                if (isChanged) {
                    if (confirm("설정하신 정보로 적용(수정)하시겠습니까?")) {
                        document.modForm.submit();
                    }
                } else {
                    alert("변경사항이 존재하지 않습니다. \n\n설정하신 정보를 확인해 주십시요.");
                }
            }

            /**
             * 사용여부에 대한 체크여부를 확인하여 사용여부값(Y.사용, N.미사용)을 설정하는 함수
             * @param {type} index
             * @param {type} objChk
             * @returns {undefined}
             */
            function fn_changeUseYn(index, objChk) {
                if (document.modForm.useYn.length) {
                    document.modForm.modUseYn[index].value = objChk.checked ? "Y" : "N";
                } else {
                    document.modForm.modUseYn.value = objChk.checked ? "Y" : "N";
                }
            }

            /**
            * 검색조건폼에 대한 submit처리함수
            * @param {type} p_findForm
            * @returns {Boolean}
            */
            function fn_onFindSubmit(p_findForm) {
                if( !findCheck(p_findForm) ) return false;
                p_findForm.strPage.value = 1;
                return true;
            }

            /**
             * 페이지이동처리함수
             * @param {type} p_page
             * @returns {undefined}
             */
            function fn_goToPage(p_page) {
                document.searchForm.strPage.value = p_page;
                document.searchForm.submit();
            }

            /**
             * 현재페이지 reloading 처리하는 함수
             * @returns {undefined}
             */
            function fn_reload() {
                document.searchForm.submit();
            }

            window.onload = showMSG;
        </script>
    </head>
    <body>
        <%--jsp:include page="<%= envTagetURL%>" flush="true">
            <jsp:param name="dirPath" value="<%= dirPath%>" />
        </jsp:include--%>

        <table>
            <jsp:include page="/totsys/common/inc/title/title.jsp" flush="true" />
            <tr class="toolbar">
                <td>
                    <table>
                        <tr>
                            <td style="text-align: left; width: 470px;">
                                <form name="searchForm" method="post" action="./group_setup.jsp" onsubmit="return fn_onFindSubmit(this);" style="margin: 0px">
                                    <input type="hidden" name="strPage" value="<%= currentPage %>">
                                    <input type="hidden" name="accAuth">
                                    <select name="findOption" class="inputtxt" onchange="showMSG()">
                                        <option value="name"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.name")%></option>
                                        <option value="regDate"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.registrition")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.day")%></option>
                                        <option value="regPerson"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.become")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.person")%></option>
                                    </select>
                                    <input name="findWord" value="<%= MString.checkNull(findWord)%>" type="text" class="inputtxt" size="30" maxlength="30" style="ime-mode: active;" />
                                    <input type="image" src="/totsys/common/images/bt_search_inquiry2.gif" border="0" align="middle" alt="검색" />
                                    <a href="group_setup.jsp">
                                        <img src="/totsys/common/images/bt_list_big.gif" alt="전체목록" />
                                    </a>
                                    <a href="#" onclick="javascript:fn_groupModify();">
                                        <img src="/totsys/common/images/bt_modify.gif" alt="<%= Moumi.getMessageBundle().getString("moumi.message.tot_doc.modify")%>" />
                                    </a>
                                </form>
                            </td>
                            <td style="text-align: left; vertical-align: top;">
                                <span id="msg" class="kecttep_date_search" style='display: none; padding-top: 5'>&nbsp;&nbsp;&nbsp;<%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.daySearchForm")%></span>
                            </td>
                            <td style="width: 8%; vertical-align: top;">
                                <a href="#" onclick="javascript:groupAdd();">
                                    <img src="/totsys/common/images/bt_grup.gif" alt="<%= Moumi.getMessageBundle().getString("moumi.message.button_small.groupRegist")%>" />
                                </a>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>

            <tr>
                <td style="vertical-align: top;">
                    <form name="modForm" method="post">
                        <input type="hidden" name="mode" value="modify"/>
                        <input type="hidden" name="findOption" value="<%= MString.checkNull(findOption)%>"/>
                        <input type="hidden" name="findWord" value="<%= MString.checkNull(findWord)%>"/>
                        <input type="hidden" name="strPage" value="<%= currentPage%>"/>
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                                <td>
                                    <table class="kecttep_list_table">
                                        <tr style="padding-top: 3px; vertical-align: middle;">
<!--						<td width="110" align="center" nowrap class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%>ID</td>-->
                                            <td style="width: 60px; text-align: center;" class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.group.useYN")%></td>
                                            <td style="width: 30%; text-align: center;" class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.name")%></td>
                                            <td style="text-align: center;" nowrap class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.become")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.person")%></td>
                                            <td style="width: 90px; text-align: center;" class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.become")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.day")%></td>
                                            <td style="width: 90px; text-align: center;" class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.change")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.day")%></td>
                                            <td style="width: 70px; text-align: center;" class="kecttep_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.group")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_report.delete")%></td>
                                            <td style="width: 80px; text-align: center;" class="kecttep_last_tdmenu"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.remark")%></td>
                                        </tr>
                                        <%
                                            //[이전][이후]의 페이지별 이동을 위해 구해진 PAGE값에 1 값을 빼주고 10을 곱한 결과에
                                            //1을 더해 줌으로서 10개의 레코드에 대한 부분을 리스트로 보여줍니다.
                                                                /*int nextCount = 0;
                                             if(currentPage > 1){
                                             nextCount = ((currentPage-1)*recordSize);
                                             }
                                             tx.begin();
                                             for(int i=0; (i<recordSize) && ((nextCount+i)<count); i++){
                                             int index = (nextCount+i); */
                                        if( count > 0 ) {
                                            int listCount = groupList.size();
                                            for (int i = 0; i < listCount; i++) {
                                                UserPartVO userPartVO = (UserPartVO) groupList.get(i);
                                        %>
                                        <tr style="padding-top: 3px; vertical-align: middle;" onmouseover="this.style.backgroundColor = 'F9F9F9'" onmouseout="this.style.backgroundColor = 'white'">
                                        <input type="hidden" name="groupId" value="<%=userPartVO.getId()%>"/>
                                        <input type="hidden" name="orgUseYn" value="<%= userPartVO.getUseYn()%>"/>
                                        <input type="hidden" name="modUseYn" value="<%= userPartVO.getUseYn()%>"/>
<!--						<td align="center" nowrap class="kecttep_graytd"><%=userPartVO.getId()%></td>-->
                                        <td style="text-align: center;" class="kecttep_graytd">
                                            <input type="checkbox" name="useYn" onclick="fn_changeUseYn(<%=i%>, this)" <%= userPartVO.getUseYn().equals("Y") ? "checked" : ""%>>
                                        </td>
                                        <td style="height: 25px; text-align: center;" class="kecttep_graytd">&nbsp;&nbsp;
                                            <% if (userPartVO.getUseYn().equals("Y")) {%>
                                            <a href="#" onclick="javascript:modify('<%=userPartVO.getId()%>', '<%=URLEncoder.encode(userPartVO.getName(), "UTF-8")%>');"><%=userPartVO.getName()%>(<%--= new UserGroupList().groupCount(userPartVO.getId())--%><%= userPartVO.getGroupCount()%>)</a>
                                            <% } else {%>
                                            <%=userPartVO.getName()%>(<%= userPartVO.getGroupCount()%>)
                                            <%}%>
                                        </td>
                                        <td class="kecttep_graytd center">&nbsp;&nbsp;<%= userPartVO.getDeptName()%> - <%=userPartVO.getUserName()%></td>
                                        <td class="kecttep_graytd center"><%=formatYMD.format(userPartVO.getRegDate())%></td>
                                        <td class="kecttep_graytd center"><%=formatYMD.format(userPartVO.getModDate())%></td>

                                        <td class="kecttep_graytd center pt_0">
                                            <%if (userPartVO.getUserId().equals(usID) || sysAuth > Moumi.TOTPER) {%>
                                            <a href="#" onclick="javascript:groupDel('<%=usID%>', '<%=userPartVO.getId()%>');">
                                                <img src="images/bt_del.gif" border="0">
                                            </a>
                                            <%} else {%>
                                            &nbsp;
                                            <%}%>
                                        </td>
                                        <td class="kecttep_last_graytd center">
                                            <%--if(new UserGroupList().getUserUserEffectiveness(userPartVO.getId())){%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.modification")--%>
                                            <%--}else{%>&nbsp;<%}--%>
                                            &nbsp;
                                        </td>
                                    </tr>
                                <%}     //end of for
                            }       //end of if
                                %>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 15px;"></td>
                        </tr>
                        <%if (count > 0) {%>
                        <tr style="vertical-align: middle;">
                            <td colspan="9" align="center" class="kecttep_board"><!---- 페이지수 나오는 부분 시작 ---->
                                <table style="width: 40%; height: 20px;">
                                    <tr>
                                        <jsp:include page="/totsys/common/inc/board/page_module.jsp" flush="true">
                                            <jsp:param name="pageFunction" value="fn_goToPage" />
                                            <jsp:param name="pageSize" value="<%= pageSize%>" />
                                            <jsp:param name="currentPage" value="<%= currentPage%>" />
                                            <jsp:param name="currentPageSetUp" value="<%= currentPageSetUp%>" />
                                        </jsp:include>
                                    </tr>
                                    <%} else {%>
                                    <tr>
                                        <td class="kecttep_none_tdmenu" style="height: 25px; text-align: center;"><%=Moumi.getMessageBundle().getString("moumi.message.popup.notGroup")%></td>
                                    </tr>
                                        <%}%>
                                </table>
                            </td>
                        </tr>
                    </table>
                </form>
            </td>
        </tr>
<input type="hidden" id="tmpFind" name="tmpFind" value="<%=findOption%>">
<script>
    if (tmpFind.value == "name") {
        searchForm.findOption.selectedIndex = 0;
    } else if (tmpFind.value == "regDate") {
        searchForm.findOption.selectedIndex = 1;
    } else if (tmpFind.value == "regPerson") {
        searchForm.findOption.selectedIndex = 2;
    }
</script>
<!------------------------------- top menu start ------------------------------->
<%@ include file="/totsys/common/inc/buttom/buttom.jsp"%>
<!------------------------------- top menu end ------------------------------->
</table>
<form name="f_group_del" action="/servlet/kr.co.kihyun.beans.user.HttpGroupDelete" method="post">
    <input type="hidden" name="partID" value="">
    <input type="hidden" name="userID" value="">
    <input type="hidden" name="callbackFunc" value="parent.fn_reload()">
</form>
<iframe name="hiddenFrame" frameborder="0" width="0" height="0" src="" style="display: none" />
</body>
</html>
<%
    } catch (Exception ex) {
        ex.printStackTrace();
        out.println(kr.co.kihyun.text.html.ServletUtil.getJavaScript("location='/servlet/kr.co.kihyun.beans.user.HttpSSOLogin?mode=logout';"));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
%>
