<%
/**
 * <pre>
 * @Class Name : listFaqs.jsp
 * 
 * @Description : 자주하는질문 목록 화면을 표출한다.
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 9. 15.    KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 9. 15.
 * @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" %>

<c:set var="pageTitle">자주하는질문(DB)</c:set>

 <!DOCTYPE html>
 <html lang="ko">
 <head>
 <title>${pageTitle}</title>

 <!-- GRID -->
 <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/js/jsgrid/nlib-jsgrid.css" />
 <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/js/jsgrid/nlib-jsgrid-theme.css" />
 <script src="${pageContext.request.contextPath}/js/jsgrid/nlib-jsgrid.js"></script>

 <script type="text/javaScript" language="javascript">
 
 $( document ).ready(function() {
     
     //=======================================================
     // 그리드 생성 환경설정 
     //=======================================================
     $("#jsGrid").jsGrid({
         pageSize : $("#pageSize").val(),
         scrollOffset:0,
         controller: {
             loadData: function (filter) { // 그리드에 데이터를 가져올 때 실팽되는 함수 
                 var data = $.Deferred();
                 //======================================
                 // 요청 정보 구성 : 시작  (각 요청에 맞게 조정)
                 //======================================
                 var reqUrl = "${pageContext.request.contextPath}/bbs/listFaqsAjax.do";
                 var pageIndex = ( filter && filter.pageIndex ? filter.pageIndex : $("#pageIndex").val());
                 var pageSize  = ( filter && filter.pageSize  ? filter.pageSize  : $("#pageSize").val());
                 
                 var searchType = $("#searchType").val();
                 var searchKeyword = $("#searchKeyword").val();
                 var searchQuestionType = $("#searchQuestionType").val();
                 
                 
                 $("#pageIndex").val(pageIndex);
                 

                 var inputData = {
                           "pageIndex"  : pageIndex
                         , "pageSize"   : pageSize
                         , "searchType" : searchType
                         , "searchKeyword"    : searchKeyword
                         , "searchQuestionType"     : searchQuestionType
                     };
                 
                 
                 //--------------------------------------
                 // 요청 처리 
                 //--------------------------------------
                 $.ajax({
                     type: "post",
                     contentType: "application/json; charset=utf-8",
                     url: reqUrl,
                     dataType: "json",
                     data: JSON.stringify(inputData),
                 }).done(function(response){
                     <%
                     // 그리드 데이터 예시 : 
                     // (1) 페이징 클라이언트에서 수행하는 경우(pageloading = false) : [{ "articleNo": 1, "articleType": "01" }, { "articleNo": 2, "articleType": "02" }]
                     // (2) 페이징 서버에서 수행하는 경우(pageloading = true) : {data: [{...}], itemsCount: 255}
                     %>
                     var jsonObj = JSON.parse(response);
                     //$("#itemsCount").val(jsonOjb.itemsCount);
                     console.log(jsonObj.itemsCount);
                     
                     if(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());
                         $("#listResult").hide();
                         $("#searchResult").show();
                     }
                     else {
                         $("#listResult").show();
                         $("#searchResult").hide();
                     }
                     
                     data.resolve(jsonObj);
                 });
                 return data.promise();
             } // loadData
         },
         
         rowClick: function(args) { // 행 클릭 시, 실행되는 이벤트 함수 
             
             // 클릭된 행의 자료 객체 
             var getData = args.item;
             
             // 추출할 컬럼의 데이터 가져오기 
             var articleId = getData["articleId"];
             var selectedRow = $("#jsGrid").find('table tr.jsgrid-selected-row');
             
             // 상세 내용 보기 
             fn_viewDetail(articleId, selectedRow);
         },
           
         //======================================
         // 그리드 컬럼 정의  (각 요청에 맞게 조정)
         //======================================
         fields: [
             { title:"TYPE",   name: "faqType" , type: "text", width: 30, align: "left", itemTemplate: function(value, item) {return "Q";}},
             { title:"ID",   name: "articleId" , type: "text", width: 160, align: "left" },
             { title:"유형",   name: "questionTypeName" , type: "text", width: 100, align: "left" },
             { title:"제목",   name: "title"      , type: "text", width: 200, align: "left" },
             { title:"첨부",   name: "attachYn"      , type: "text", width: 100, align: "center"}
         ]
     });

     // 검색 버튼 클릭 
     $("#btnSearch").on("click", function(e) {
         fn_searchArticle($("#pageSize").val(), 1);
     });
     
     //초기 자료 조회 
     fn_searchArticle();
     
 }); // document ready


 // 선택한 글 상세 보기로 이동
 function fn_viewDetail(articleId, selectedRow) {

     var $selectedRow = $(selectedRow);
     var reqUrl = "${pageContext.request.contextPath}/bbs/selectFaqArticleAjax.do";
     var inputData = { "articleId" : articleId };
     
     //--------------------------------------
     // 요청 처리 
     //--------------------------------------
     $.ajax({
         type: "post",
         contentType: "application/json; charset=utf-8",
         url: reqUrl,
         dataType: "json",
         data: JSON.stringify(inputData),
     }).done(function(response){
         var jsonObj = JSON.parse(response);
         $("#jsGrid").find('table tr.answer').remove();
         
        var answerHtml = "<tr class='answer'><td>A</td><td colspan='4'>" +
                 + "<br/>" + jsonObj.data.answer;
        if(jsonObj.data.attachFileCnt > 0) {
            answerHtml += "<br/>[첨부파일]<br/>";
            for(var i=0; i<jsonObj.data.attachFileCnt; i++) {
            	answerHtml += "<a href=\"javascript:void(0);\" onclick=\"fn_downloadFile('" + 
            			jsonObj.data.attachFiles[i].fileId + "', " + 
            			jsonObj.data.attachFiles[i].fileSeq + ", '" + 
            			jsonObj.data.attachFiles[i].fileName + "')\">" + 
            			jsonObj.data.attachFiles[i].fileName + " (" + 
            			jsonObj.data.attachFiles[i].fileSize + " byte(s))</a><br/>";
            }
        } 
        answerHtml += "</td></tr>";
        
        $selectedRow.after(answerHtml);
     });
     
     $("#jsGrid").closest('.ui-jqgrid-bdiv').width($("#jsGrid").closest('.ui-jqgrid-bdiv').width() + 1);
     
     
 }
 
 // 그리드 데이터 조회 호출 
 function fn_searchArticle(pageSize, pageIndex) {
     $("#jsGrid").jsGrid("search"
             , {'pageSize'  : (pageSize  ? pageSize  : fn_getIntValue("pageSize", ${searchArticle.pageSize}) ), 
                'pageIndex' : (pageIndex ? pageIndex : fn_getIntValue("pageIndex", ${searchArticle.pageIndex}))
               }
     );
 }
 

//파일 다운로드
function fn_downloadFile(fileId, fileSeq, fileName) {
  
  if(fileId == null || fileId.trim().length < 1) {
      alert("파일정보를 확인해 주시기 바랍니다.[1]");
      return;
  }

  if(fileSeq < 1) {
       alert("파일정보를 확인해 주시기 바랍니다.[2]");
       return;
  }
  
  if(fileName == null || fileName.trim().length < 1) {
       alert("파일정보를 확인해 주시기 바랍니다.[3]");
       return;
  }

  $("#fileId").val(fileId);
  $("#fileSeq").val(fileSeq);
  $("#fileName").val(fileName);
  $("#downloadFileForm").submit();
  
}

function fn_changeQuestionType(searchQuestionType) {
	$("#searchQuestionType").val(searchQuestionType);
	fn_searchArticle($("#pageSize").val(), 1);
}

</script>
</head>

 <body>

 <h1>${pageTitle }</h1>

 메시지 : ${message} 
 
<div name="listResult" id="listResult">
 총 <span name="itemsCount" id="itemsCount"></span>건<br>
</div>

<div style="display:none;" name="searchResult" id="searchResult">
 '<span name="searchKeywordPrt" id="searchKeywordPrt"></span>' 에 대한 검색결과는 총 <span name="searchItemsCount" id="searchItemsCount"></span>건 입니다.<br>
</div>
 
 &nbsp;<br/>
 

<!-- 유형선택 --> 
<table>
    <tr>
        <td><a href="javascript:void(0);" onclick="fn_changeQuestionType('')">전체</a></td>
		<c:forEach var="qTypeItem" items="${questionTypeList }">
		    <td><a href="javascript:void(0);" onclick="fn_changeQuestionType('${qTypeItem.sCodeId}')">${qTypeItem.sCodeNm}</a></td>
		</c:forEach>
    </tr>
</table>
<br>

 <form name="articleForm" id="articleForm" method="post" action="${pageContext.request.contextPath}/bbs/selectFaqArticle.do"> 
     
     <!-- 검색조건 -->
     <input type="text" name="pageSize" id="pageSize" value="${searchArticle.pageSize }" />
     
     <input type="text" name="pageIndex" id="pageIndex" title="페이지번호" value="${searchArticle.pageIndex }" size="5" maxlength="5" />
     
     <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>
     <input type="text" name="searchKeyword" id="searchKeyword" title="검색어" value="${searchArticle.searchKeyword }" maxlength="20" />
     <input type="text" name="articleId" id="articleId" title="게시글번호" value="" readonly />
     <input type="button" name="btnSearch" id="btnSearch" title="검색" value="검색" />
     <br/>
          
     <div id="jsGrid" name="jsGrid" style="height: 100%"></div>
     
     
     <input type="text" name="searchQuestionType" id="searchQuestionType" value="" title="유형코드" readonly />
     <input type="text" name="articleNo" id="articleNo" value="" title="선택글번호" readonly />

 </form>


<!-- 첨부파일 다운로드용 폼 -->
<form name="downloadFileForm" id="downloadFileForm"
      action="${pageContext.request.contextPath}/fileupload/downloadAttachFile.do"
      method="post">
      <input type="text" name="subPathKey" id="subPathKey" value="fileupload.bbs.ancmnt.subpath" readonly />
      <input type="text" name="fileId" id="fileId" value="" readonly />
      <input type="text" name="fileSeq" id="fileSeq" value="" readonly />
      <input type="text" name="fileName" id="fileName" value="" readonly />
</form>

 </body>
 </html>

