<%
/**
 * <pre>
 * @Class Name : listQnas.jsp
 * 
 * @Description : 묻고답하기 목록 화면을 표출한다.
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 9. 16.    KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 9. 16.
 * @version 1.0
 *
 */
 %>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="validator" uri="http://www.springmodules.org/tags/commons-validator" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

<c:set var="pageTitle">Q&A</c:set>

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

	 fn_setPageTitle("<c:out value='${pageTitle}'/>");
	 
     // 검색 수행 이벤트  
     $("#btnSearch").on("click", function(e) {
         fn_searchArticle(1);
     });
     $("#searchKeyword").on("keydown", function(e) {
         if(e.keyCode == 13) {
             fn_searchArticle(1);    
         }
     });
     
     // 메시지 표출 
     if(!gfn_isEmpty("<c:out value='${message}'/>") || !gfn_isEmpty("<c:out value='${searchArticle.resultMessage}'/>")) {
         setTimeout(function() {
        	 alert("<c:out value='${message}'/>" + " <c:out value='${searchArticle.resultMessage}'/>");
         }, 700); // 화면 표출되도록 딜레이 줌 
     }

     //초기 자료 조회 
     fn_searchArticle();

 }); // document ready


 // 선택한 글 상세 보기로 이동
 function fn_viewDetail(articleId, secretYn, myQnaYn) {
	 
     // 비밀글인 경우, 본인에 한하여 조회 가능 
     if(secretYn == "Y" && myQnaYn == "N") {
         alert("비공개 게시물은 작성자만 확인할 수 있습니다.");
         return;
     }
     
     $('#articleForm').removeAttr('onsubmit');
     $("#articleForm").attr("action", "${pageContext.request.contextPath}/bbs/selectQnaArticle.do");
     $("#articleId").val(articleId);
     $("#articleForm").submit();
 }
 
 // 그리드 데이터 조회 호출 
 function fn_searchArticle(pageIndex) {
     
     if(gfn_isEmpty(pageIndex)) pageIndex = $("#pageIndex").val();
     if(gfn_isEmpty(pageIndex)) pageIndex = "1";
     $("#pageIndex").val(pageIndex);
     
     var reqUrl = "${pageContext.request.contextPath}/bbs/listQnasAjax.do";
     
     var inputData = {
               "pageIndex"  : $("#pageIndex").val()
             , "pageSize"   : $("#pageSize").val()
             , "searchType" : $("#searchType").val()
             , "searchKeyword"    : $("#searchKeyword").val()
             , "searchQuestionType"     : $("#searchQuestionType").val()
     };
     
     //--------------------------------------
     // 요청 처리 
     //--------------------------------------
     $.ajax({
         type: "post",
         contentType: "application/json; charset=utf-8",
         url: reqUrl,
         dataType: "json",
         data: JSON.stringify(inputData),
     }).done(function(data){
         var jsonObj = JSON.parse(data);

         // 탭선택 처리 
         $("[id^=tabQna]").removeClass();
         //$("[id^=tabQna]").attr("title", "");
         var selectedTab = "tabQnaAll";
         if($("#searchQuestionType").val() == "USER") {
        	 selectedTab = "tabQnaUser";
         }
         $("#" + selectedTab).addClass("current");
         //$("#" + selectedTab).attr("title", "선택됨");

         
         // 건수
         if(typeof jsonObj.itemsCount == 'undefined') {
             $("#itemsCount").text("0");
             $("#searchItemsCount").text("0");
         }
         else {
             $("#itemsCount").text(jsonObj.itemsCount);
             $("#searchItemsCount").text(jsonObj.itemsCount);
         }
         
         // 검색결과 
         if($("#searchKeyword").val() != "") {
             $("#searchKeywordPrt").text("'" + $("#searchKeyword").val() + "'");
             $("#searchResult").show();
             $("#cntResult").hide();
         }
         else {
             $("#searchResult").hide();
             $("#cntResult").show();
         }
         
         // 기존 데이터 CLEAR
         $(".list-notice tbody tr").filter('.tableTrData').remove();

         if(!jsonObj.data || jsonObj.data.length <= 0 ) {
             $(".list-notice tbody tr.no-result").show();
         } else {
             $(".list-notice tbody tr.no-result").hide();

             // 출력
             $.each(jsonObj.data,function(key,obj) {
                 var li = $('<tr class="tableTrData" />');
                 li.append($('<td />').attr('class', 't-num').html(obj.rno));   
                 li.append($('<td />').attr('class', 't-tit').html("<a href=\"javascript:void(0)\" onclick=\"fn_viewDetail('" + obj.articleId + "','" + obj.secretYn + "','" + obj.myQnaYn + "')\">" +
                         obj.title + 
                         (obj.secretYn == "Y" ? '<img src="/images/icon/icon-password.png" alt="자물쇠 아이콘">&nbsp;' : '') +
                         "</a>"));
                 li.append($('<td />').attr('class', 't-writer').html(obj.regNmSec));
                 li.append($('<td />').attr('class', 't-date').html(obj.regDd));
                 li.append($('<td />').attr('class', 't-answer').html((obj.answerYn == "Y" ? '<span class="compl">답변완료</span>' : '<span class="wait">답변대기</span>')));
                 
                 $( ".list-notice").append(li);
                 
             });
         }
         

         if(!gfn_isEmpty(jsonObj.message)) {
             alert(jsonObj.message);
         }
         
         gfn_makePaging("fn_searchArticle", jsonObj.pagingPageIndex, jsonObj.pagingTotRecordCount, jsonObj.pagingStartPage, jsonObj.pagingEndPage, jsonObj.pagingLastPage); 

     }).fail(function (jqXHR, textStatus, errorThrown) {
         alert("조회에 실패하였습니다. 관리자에게 문의 바랍니다.");
     });
 }

 function fn_changeTabAllQuestion() {

     $("#searchQuestionType").val("");
     $("#searchKeyword").val("");
     fn_searchArticle(1);
 }
 
 function fn_changeTabMyQuestion() {

     <sec:authorize access="not isAuthenticated()">
     location.href = "/bbs/listMyQnas.do";
     </sec:authorize>
 
     <sec:authorize access="isAuthenticated()">
     $("#searchQuestionType").val("USER");
     $("#searchKeyword").val("");
     fn_searchArticle(1);
     </sec:authorize>
     
 }

 //게시글 작성으로 이동
 function fn_newArticle() {
	 
     $("#articleNo").val("");
     $("#articleForm").attr("action", "${pageContext.request.contextPath}/bbs/insertQnaForm.do");
     $('#articleForm').removeAttr('onsubmit');
     $("#articleForm").submit();
 }
 
 </script>

    <!-- Q&amp;A 섹션 -->
    <div class="location qna">
        <h2 class="blind"><c:out value='${pageTitle }'/> 섹션영역</h2>
        <div class="inner">
            <div class="row-top">
                <div class="location-box">
                    <ul class="loc">
                        <li>HOME</li>
                        <li>고객지원</li>
                        <li class="on"><c:out value='${pageTitle }'/></li>
                    </ul>
                    <div class="tit">
                        <h2><span><c:out value='${pageTitle }'/></span></h2>
                    </div>
                </div>
                <div class="arr"><img src="/images/icon/icon-join-arr2.png" alt=""></div>
            </div>
            <div class="contents row-bottom">
                <div class="list-box qna-box">
                    <div class="tab">
                        <ul class="tabs">
                            <li id="tabQnaAll"><a href="javascript:void(0);" onclick="fn_changeTabAllQuestion()">전체</a></li>
                            <li id="tabQnaUser"><a href="javascript:void(0);" onclick="fn_changeTabMyQuestion()">내 질문</a></li>
                        </ul>
                        <div class="title">
                            <div class="list-search-wrap list-top">
                                <form name="articleForm" id="articleForm" method="post" onsubmit="return false;"> 
                                <div class="left">
                                     <div class="total-count" id="cntResult"><span class="count">총 <em id="itemsCount">0</em>건</span></div>
                                     <div class="total-count" style="display: none;" id="searchResult">
                                     <span class="count"><em id="searchKeywordPrt"></em>에 대한 검색결과는 총 <em id="searchItemsCount">4</em>건 입니다.</span>
                                     </div>
                                </div>
	
	                            <div class="right">
	                                      <div class="list-select type">
	                                          <label for="searchType" class="blind">검색조건
	                                          </label>
	                                           <select name="searchType" id="searchType">
	                                              <option value="T" <c:if test='${searchArticle.searchType == "T" }'>selected</c:if> >제목</option>
	                                              <option value="C" <c:if test='${searchArticle.searchType == "C" }'>selected</c:if> >내용</option>
	                                           </select>
	                                          
	                                      </div>
	                                      <div class="list-input">
	                                          <input type="text" id="searchKeyword" name="searchKeyword" placeholder="검색어를 입력하세요" title="검색어" value="<c:out value='${searchArticle.searchKeyword }'/>" maxlength="20" >
	                                          <label for="searchKeyword" class="blind">검색어</label>
	                                          <button name="btnSearch" id="btnSearch" type="button" title="검색">검색</button>
	                                      </div>
	                                  </div>
	                                   
							     <input type="hidden" name="pageSize" id="pageSize" value="<c:out value='${searchArticle.pageSize }'/>" />
							     <input type="hidden" name="pageIndex" id="pageIndex" title="페이지번호" value="<c:out value='${searchArticle.pageIndex }'/>" />
							     <input type="hidden" name="articleId" id="articleId" title="게시글번호" value="" />
							     <input type="hidden" name="searchQuestionType" id="searchQuestionType" value="<c:out value='${searchArticle.searchQuestionType }'/>" title="유형코드" />
							     <input type="hidden" name="articleNo" id="articleNo" value="" title="선택글번호" />
	                                  
                                </form>                               
                            </div>
                        </div>

                        <div class="tab_content">
                            <div class="tabs_item">
                               
                                <div id="contents" class="community notice">
                                    <div class="contents-frame inner-center">

                                        <div class="list-table-wrap">
                                            <table class="list-notice">
                                            	<caption>Q&A 목록 표 – NO, 제목, 등록자, 등록일, 답변으로 구성</caption>
                                                <thead class="t-tit-line">
                                                	<tr>
	                                                    <th class="t-num">NO</th>
	                                                    <th class="t-tit">제목</th>
	                                                    <th class="t-writer">등록자</th>
	                                                    <th class="t-date">등록일</th>
	                                                    <th class="t-answer">답변</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                	<tr class="no-result" style="display:none;">
							                            <td colspan="5">검색결과가 없습니다.</td>
							                        </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <div class="btn-box">
                                            <button type="button" class="btn btn-color" onclick="fn_newArticle()">질문하기</button>
                                        </div>

                                        <ul id="paging" class="paging"></ul>

                                    </div>
                                    <!-- //contents-frame -->
                                </div>
                                
                            </div>

                        </div>
                    </div>
                            
                </div>
            </div>
        </div>
    </div>    
