<%@page import="kr.co.kihyun.text.html.TagFilter"%>
<%
/**********************************************************************************
	프로그램명		: board_list.jsp
	프로그램설명	:
	작 성 자			:
	작 성 일			:
	최신변경일		:
***********************************************************************************/
%>
<%@ page contentType="text/html; charset=UTF-8"
	import="java.net.URLEncoder" import="java.text.SimpleDateFormat"
	import="java.util.Date" import="java.util.List"
	import="javax.jdo.PersistenceManager" import="javax.jdo.Transaction"
	import="javax.jdo.Query" import="kr.co.kihyun.beans.entity.*"
	import="kr.co.kihyun.beans.entity.util.*"
	import="kr.co.kihyun.beans.user.HttpSSOLogin"
	import="kr.co.kihyun.beans.user.User"
	import="kr.co.kihyun.lang.Encoder" import="kr.co.kihyun.lang.MString"
       import="kr.co.kihyun.service.*" import="kr.co.kihyun.service.vo.*" import="java.util.*"
       import="java.text.SimpleDateFormat"
	import="kr.co.kihyun.moumi.Moumi"%>

<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>

<%
response.setBufferSize(1024*8);
PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
Transaction tx = pm.currentTransaction();
try{
	String usID = HttpSSOLogin.getLoginID(request);
	int sysAuth = HttpSSOLogin.getSysAuth(request);
	String dtID = HttpSSOLogin.getDeptID(request);

	/************ Parameter ************/
	String boardGroupID = request.getParameter("boardGroupID");
	String strPage = clearXSS(request.getParameter("strPage"),"");
	String findOption = clearXSS(request.getParameter("findOption"),null);
	String findWord = clearXSS(Encoder.toJava(request.getParameter("findWord")),null);
	String boardType = "";
	Category category = pm.getObjectById(Category.class, boardGroupID);

        ////////////////////////


        String method = clearXSS(request.getParameter("method"),"");
        if(method.equals("GET")) findWord = URLDecoder.decode(MString.checkNull(request.getParameter("findWord")), "UTF-8");
        //String uri = URLEncoder.encode("board_list.jsp?boardGroupID="+boardGroupID+"&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], "");
            }
        }
        /************ 리스트 페이지 구성 ************/
	int endPage=0;
	int pageSize=0;
	int currentPage=0;
	int absolutePage=0;
	int currentPageSetUp=0;
	int recordSize=10;


	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.out.println(ex);
            }
	}

        //======================================================================
        BoardService boardService = new BoardService(pm);
        //검색조건파라미터
        Map params = new HashMap();
        params.put("findOption",    findOption);
        params.put("findWord",      findWord);
        params.put("groupId",       boardGroupID);

        //검색메인쿼리와 레코드갯수조회쿼리를 생성 후 멤버변수로 저장
        boardService.createBoardListQuery(params);

        //레코드갯수조회쿼리를 실행하여 레코드갯수를 구함
        int count = boardService.getCountFromMainQuery();

        if((count%recordSize) == 0) {
            pageSize = (int)(count/recordSize);
        } else {
            pageSize = (int)(count/recordSize)+1;
        }
        
        if( currentPage > pageSize ) currentPage = pageSize;
        currentPageSetUp = (int)(currentPage/10)*10;
	if (currentPage%10 == 0){
		currentPageSetUp-=10;
	}

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

        List list = null;

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

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

            //만족하는 레코드가 존재하면 조회
            list = boardService.executeQuery(BoardVO.class);
        }
        //======================================================================
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	session.setAttribute("envTagetURL", "/totsys/common/inc/sysadm/top/top.jsp");
	session.setAttribute("homeTagetURL", "/totsys/sysadm/board/board_list.jsp");

	if("ID_SYSTEM_NOTICE".equals(boardGroupID)){
		boardType = Moumi.getMessageBundle().getString("moumi.message.board.notice");
	}else if("ID_FAQ".equals(boardGroupID)){
		boardType = Moumi.getMessageBundle().getString("moumi.message.board.faq");
	}else if("ID_QNA".equals(boardGroupID)){
		boardType = Moumi.getMessageBundle().getString("moumi.message.board.qna");
	}else if("ID_PDS".equals(boardGroupID)){
		boardType = Moumi.getMessageBundle().getString("moumi.message.board.pds");
	}
%>


<%@page import="java.net.URLDecoder"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<title><%=Moumi.getTitle()%></title>
<meta charset="UTF-8">
<link rel="stylesheet" href="/totsys/common/css/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="/totsys/common/js/jquery-1.12.4.min.js"></script>
<script src="/totsys/common/js/rollover.js"></script>
<script src="/totsys/common/js/mouse.js"></script>
<script>
	$(document).ready(function() {
	    var frm = $('#form');
	    frm.submit(function (ev) {
	        $.ajax({
	            type: frm.attr('method'),
	            url: frm.attr('action'),
	            data: frm.serialize(),
	            success: function (data) {
	                alert('ok');
	            }
	        });
	        ev.preventDefault();
	    });
	});


    function find(){
               
    	var word = document.search.findWord.value.length;
        var option = document.search.select.options[document.search.select.selectedIndex].value;

        document.search.findOption.value = option;

        if(search.findWord.value == ""){
            alert("검색 단어를 입력해 주세요");
            return;
        }

        if(document.search.findOption.value!="id" && word < 2){
            alert("검색어는 2글자 이상이어야 합니다.!");
            return;
        }
        document.search.submit();
    }
    
    /*
    * 페이지이동처리함수
    */
    function fn_goToPage(p_page) {
        document.search.strPage.value = p_page;
        document.search.submit();
    }
    
    /*
    * 상세보기페이지로 이동처리하는 함수
    * @param {type} p_boardId
    * @returns {undefined}
    */
   function fn_goToView(p_boardId) {
       document.f_view.boardID.value = p_boardId;
       document.f_view.submit();
   }
</script>
</head>

<body>
<form name="f_view" method="post" action="./board_view.jsp">
    <input type="hidden" name="boardID" value="">
    <input type="hidden" name="strPage" value="<%= currentPage %>">
    <input type="hidden" name="boardGroupID" value="<%= boardGroupID %>">
    <input type="hidden" name="findWord" value="<%= findWord %>">
    <input type="hidden" name="findOption" value="<%= findOption %>">
    <input type="hidden" name="tmpFind" value="<%=findOption%>">
</form>
<table>
    <jsp:include page="/totsys/common/inc/sysadm/top/top.jsp" flush="true" />
    <tr>
        <td></td>
        <td>
            <table>
                <jsp:include page="/totsys/common/inc/title/title.jsp" flush="true">
                    <jsp:param value='<%= URLEncoder.encode(boardType, "UTF-8")%>' name="title" />
                </jsp:include>
                <tr class="toolbar">
                    <td>
                        <table>
                            <tr>
                                <td>
                                    <FORM name="search" action="./board_list.jsp" onsubmit="find();" method="post" style="margin: 0px">
                                        <input type="hidden" name="strPage" value="<%= currentPage %>">
                                        <input type="hidden" name="boardGroupID" value="<%= boardGroupID %>">
                                        <select id="select" name="select" class="inputtxt" onchange="showMSG()">
                                            <option value="title">제목</option>
                                            <!--//<option value="mUser.name">작성자</option>//-->
                                        </select>
                                        <label for="select" class="blind">검색옵션</label>
                                        <input type="text" name="findWord" class="inputtxt" size="30" maxlength="30" value="<%= MString.checkNull(findWord) %>" style="ime-mode: active;" />
                                        <input type="hidden" name="findOption" value="<%= findOption %>"> <!-- 검색 끝 -->
                                        <a href="#" onclick="find();" title="검색">
                                            <!--<img src="/totsys/common/images/bt_search.gif" border="0" style="MARGIN: 2px 0px 0px 0px">-->
                                            <img alt="검색" src="/totsys/common/images/bt_search_inquiry2.gif" />
                                        </a>
                                    </FORM>
                                </td>
                                <td>
                                    <span id="msg" class="kecttep_date_search" style="display: none; padding-top: 5px">
                                        &nbsp;&nbsp;&nbsp;날짜검색시 10-12-01 형식으로 입력
                                    </span>
                                </td>
                                <td class="tar">
                                    <%if(sysAuth == Moumi.TOTPER && ("ID_QNA".equals(boardGroupID) )){ %>
                                    <!--<a class="simplebutton" href="./board_write.jsp?boardGroupID=<%=boardGroupID%>&strPage=<%=strPage%>">
                                        <span class="regist" style="width: 82px; cursor: pointer">
                                            <%= Moumi.getMessageBundle().getString("moumi.message.button.boardRegist") %>
                                        </span>
                                    </a>-->
                                    <a href="./board_write.jsp?boardGroupID=<%=boardGroupID%>&strPage=<%=strPage%>">
                                        <img alt="게시물작성" src="/totsys/common/images/bt_write.gif" />
                                    </a>
                                    <%}else if(sysAuth == Moumi.SYSADM){%>
                                    <!--<a class="simplebutton" href="./board_write.jsp?boardGroupID=<%=boardGroupID%>&strPage=<%=strPage%>">
                                        <span class="regist" style="width: 82px; cursor: pointer">
                                            <%= Moumi.getMessageBundle().getString("moumi.message.button.boardRegist") %>
                                        </span>
                                    </a>-->
                                    <a href="#" onclick="fn_goWritePage();" title="게시물작성">
                                        <img alt="게시물작성" src="/totsys/common/images/bt_write.gif" />
                                    </a>
                                        <form name="f_write" method="post" action="./board_write.jsp">
                                            <input type="hidden" name="strPage" value="<%= currentPage %>">
                                            <input type="hidden" name="boardGroupID" value="<%= boardGroupID %>">
                                            <input type="hidden" name="findWord" value="<%= findWord %>">
                                            <input type="hidden" name="findOption" value="<%= findOption %>">
                                        </form>
                                        <script>
                                            /**
                                             * 게시물작성페이지로 이동처리하는 함수
                                             * @returns {undefined}
                                             */
                                            function fn_goWritePage() {
                                                document.f_write.submit();
                                            }
                                        </script>
                                    <%}%>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <!--  리스트 시작 -->
                <tr>
                    <td>
                        <table class="kecttep_list_table tableLine">
                            <tr>
                        <% if("ID_SYSTEM_NOTICE".equals(boardGroupID)) { %>
                                <td class="kecttep_tdmenu center" style="width: 7%;">팝업공지</td>
                        <% } %>
                                <td class="kecttep_tdmenu center" style="width: 10%;">번호</td>
                                <td class="kecttep_tdmenu center" style="width: 40%;">제목</td>
                                <td class="kecttep_tdmenu center" style="width: 10%;">작성자</td>
                                <!--td width="10%" class="kecttep_tdmenu">기관/부서</td-->
                                <td class="kecttep_tdmenu center" style="width: 18%;">날짜</td>
                                <td class="kecttep_last_tdmenu center" style="width: 5%;">조회수</td>
                            </tr>
                    <%
                        //[이전][이후]의 페이지별 이동을 위해 구해진 PAGE값에 1 값을 빼주고 10을 곱한 결과에
                        //1을 더해 줌으로서 10개의 레코드에 대한 부분을 리스트로 보여줍니다.
                        /*int nextCount = 0;
                        int index = 0;
                        if(currentPage > 1){
                                nextCount = ((currentPage-1)*recordSize);
                        }*/
                    %>
                    <!-- start board 글목록 -->
                    <%
                        tx.begin();
                        //for(int i = 0; (i < recordSize) && ((nextCount+i) < getCount); i++){
                            //index = nextCount+i;
                    if( count > 0 ) {    
                        int listCount = list.size();
                        for(int i = 0; i < listCount; i++){
                            BoardVO boardVO = (BoardVO)list.get(i);
                    %>
                            <tr style="padding-top: 3px;" onmouseover="this.style.backgroundColor='F9F9F9'" onmouseout="this.style.backgroundColor='white'" bgColor=#ffffff>
                    <% if("ID_SYSTEM_NOTICE".equals(boardGroupID)) { %>                                
                                <td class="kecttep_graytd tac">
                                    <input type="checkbox" disabled<% if("Y".equals(boardVO.getPopupYn())){ %> checked <%}%>>
                                </td>
                    <% } %>                                
                                <td  class="kecttep_graytd tac">&nbsp;<%=boardVO.getId() %></td>				
                                <td  class="kecttep_graytd">
                                    &nbsp;
                                    <a onmouseover="balloon_on('<%= boardVO.getTitle() %>',this,10,4)" onmouseout="balloon_off()" href="javascript:fn_goToView('<%=boardVO.getId()%>');">
                                        <%=MString.getEllipsis( TagFilter.unconvertedMeta(boardVO.getTitle()) , 60 )%>
                                    </a>
                                </td>
                                <td  class="kecttep_graytd tac">&nbsp;<%if("ID_SYSTEM_NOTICE".equals(boardGroupID) ||"ID_FAQ".equals(boardGroupID) || "ID_PDS".equals(boardGroupID)){%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.sysadm") %><%}else{%><%= boardVO.getUserName()%><%}%></td>
						<!--td class="kecttep_graytd">&nbsp;<%=boardVO.getDeptName()%></td-->
                                <td  class="kecttep_graytd tac">&nbsp;<%=sdf.format(boardVO.getWriteDate())%></td>
                                <td class="kecttep_last_graytd tac"><%=boardVO.getVisit()%></td>
                            </tr>
                    <%	}
                    }
                    tx.rollback();
                    %>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td></td>
                </tr>
                <%if(count > 0){%>
                <tr style="padding-top: 3px">
                    <td class="kecttep_board" colspan="6"><!-- 페이지수 나오는 부분 시작 -->
                        <table>
                            <tr>
                                <td>
                                    <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>
                                </td>
                            </tr>
                        </table>
                    </td><!-- 페이지수 나오는 부분 끝 -->
                </tr>
                <%}else{%>
                <tr>
                    <td class="kecttep_none_tdmenu center">
                        게시된 <%= Moumi.getMessageBundle().getString("moumi.message.doc") %>가 없습니다.
                    </td>
                </tr>
                <%}%>
                <!--  리스트 끝  -->
                <!--1픽셀 띄우기-->
                <tr>
                    <td></td>
                </tr>

                <script>
                    function showMSG(){
                        if(search.select.value == "regDate"){
                            msg.style.display="block";
                        }else{
                            msg.style.display="none";
                        }
                    }
                </script>

            </table>
        </td>
        <td>&nbsp;</td>
    </tr>
    <!--검색후 검색조건 선택하기위한 스크립트(히든값포함)-->
    <script>
        if($("[name=tmpFind]").value == "title"){
            search.select.selectedIndex=0;
        }else if($("[name=tmpFind]").value == "mUser.name"){
            search.select.selectedIndex=1;
        }
    </script>
    <!--검색후 검색조건 선택하기위한 스크립트 끝-->
    <!-- buttom menu start -->
    <!--include file="/totsys/common/inc/buttom/buttom.jsp"-->
    <!--include file="/totsys/common/inc/buttom/buttom.jsp"-->
    <!--buttom menu end -->
</table>
</BODY>
</HTML>
<%
}catch(Exception ex){
        //38.오류메세지를 통한 정보 노출(getMessage)_CWE-209 : Update by YOUNGJUN,CHO
	ex.printStackTrace();
	//out.println(ex);//앤개
	//out.println("<html><body style='overflow=auto' bgcolor='white'><h1>Can't contact servlet runner</h1><br><br>Message : "+ex.getMessage()+"</body></html>");
	//out.println("<META HTTP-EQUIV='refresh' CONTENT='0.1; URL=/error/exception.jsp'>");
        //================================================
}finally{
	if(tx.isActive())
		tx.rollback();
	pm.close();
}
%>
