
<%
/**
 * <pre>
 * @Class Name : listReadItems.jsp
 * 
 * @Description : 열람 목록을 조회한다.
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021.11. 09.    KNKIM       최초 생성
 * 
 * @author 이씨플라자 * DIGITALSHIP JSYOO
 * @since 2021.11. 09.
 * @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">방문열람관리</c:set>

<script>
 
 $( document ).ready(function() {
     
     // 메시지 표출 
     if(!fn_isEmpty('${message}')) {
         alert("${message}");
     }

     $("#mngOrgCd").on("change", function(e) {
    	 fn_searchArticle($("#pageSize").val(), 1);
     });

     <sec:authorize access="isAuthenticated()">
     //초기 자료 조회 
     fn_searchArticle(1);
     </sec:authorize>
     
 }); // document ready

function fn_search(reqStatusDivCd) {
	$("#reqStatusDivCd").val(reqStatusDivCd);
	fn_searchArticle(1);
}
 
 // 선택한 글 상세 보기로 이동
 function fn_viewDetail(masterId) {
     $("#masterId").val(masterId);
     $("#frm").attr("action", "/search/searchItemDetail.do");
     $("#frm").attr("target", "_blank");
     $("#frm").submit();
 }
 
 // 그리드 데이터 조회 호출 
 function fn_searchArticle(pageIndex) {
     
     if(fn_isEmpty(pageIndex)) pageIndex = $("#pageIndex").val();
     if(fn_isEmpty(pageIndex)) pageIndex = "1";
     $("#pageIndex").val(pageIndex);
     
     var reqUrl = "${pageContext.request.contextPath}/read/listReadItemsAjax.do";
     
     var inputData = {
               "pageIndex"  : $("#pageIndex").val()
             , "pageSize"   : $("#pageSize").val()
             , "reqStatusDivCd" : $("#reqStatusDivCd").val()
             , "mngOrgCd"    : $("#mngOrgCd").val()
     };
     
     //--------------------------------------
     // 요청 처리 
     //--------------------------------------
     $.ajax({
         type: "post",
         contentType: "application/json; charset=utf-8",
         url: reqUrl,
         dataType: "json",
         data: JSON.stringify(inputData),
     }).done(function(data){
         <%
         // 그리드 데이터 예시 : 
         // (1) 페이징 클라이언트에서 수행하는 경우(pageloading = false) : [{ "articleNo": 1, "articleType": "01" }, { "articleNo": 2, "articleType": "02" }]
         // (2) 페이징 서버에서 수행하는 경우(pageloading = true) : {data: [{...}], itemsCount: 255}
         %>
         
         var jsonObj = JSON.parse(data);
         
         // 건수 
         if(typeof jsonObj.itemsCount == 'undefined') {
             $("#itemsCount").text("0");
         }
         else {
             $("#itemsCount").text(jsonObj.itemsCount);
         }
         
         // 기존 데이터 CLEAR
         $("div.list-data div.list").not('.t-tit-line').not('.no-result').remove();
         
         if(!jsonObj.data || jsonObj.data.length <= 0 ) {
             $("div.list-data div.no-result").show();
         } else {
             $("div.list-data div.no-result").hide();
             
             // 출력
             $.each(jsonObj.data,function(key,obj) {
            	 
                 var div = $(document.createElement('div'));
                 div.attr('class', 'list');
                 div.append($('<div />').attr('class', 'n-cultural').html("[" + obj.mngOrgNm + "]"));
                 div.append($('<div />').attr('class', 'n-data').html("<a href=\"javascript:void(0)\" onclick=\"fn_viewDetail('" + obj.masterId + "')\">" + obj.title + "</a>"));
                 div.append($('<div />').attr('class', 'n-subscription').html('<span class="date">' + gfn_formatDateStr(obj.reqDd,"-") + '</span>')); /* 신청일자 */          
                 div.append($('<div />').attr('class', 'n-visit').html(
                		 '<span class="date">' + gfn_formatDateStr(obj.hopeReqPridDtmFrom,"-") + '</span><span class="date">' + gfn_formatDateStr(obj.hopeReqPridDtmTo,"-") + '</span>'
                		 )); /* 희망열람기간 */  
                 div.append($('<div />').attr('class', 'n-return').html(
                         '<span class="date">' + gfn_formatDateStr(obj.reqPsblDtmFrom,"-") + '</span><span class="date">' + gfn_formatDateStr(obj.reqPsblDtmTo,"-") + '</span>'
                         )); /* 방문예정일자 */  
                 
                 var statusHtml1 = "";
                 var statusHtml2 = "";
                 var statusHtml3 = "";
                 if(obj.reqStatusDivCd == null) {
                	 statusHtml1 = '<span class="ti imposs">-<span class="da"></span></span>';
                 } else if(obj.reqStatusDivCd == "A0") { // 신청 
                	 statusHtml1 = '<span class="ti imposs">' + obj.reqStatusDivNm + '<span class="da"></span></span>';
                	 statusHtml2 = '<button type="button" onclick="fn_cancel(\'' + obj.title + '\',\'' + obj.mngOrgCd + '\', \'' + obj.reqId + '\', \'' + obj.masterId + '\')">취소</button>';
                 } else if(obj.reqStatusDivCd == "A1") { // 승인 
                	 statusHtml1 = '<span class="ti   poss">' + obj.reqStatusDivNm + '<span class="da">' + gfn_formatDateStr(obj.modDd,"-") + '</span></span>';
                     statusHtml2 = '<button type="button" onclick="fn_cancel(\'' + obj.title + '\',\'' + obj.mngOrgCd + '\', \'' + obj.reqId + '\', \'' + obj.masterId + '\')">취소</button>';
                 } else if(obj.reqStatusDivCd == "A2") { // 반려 
                     statusHtml1 = '<span class="ti   poss">' + obj.reqStatusDivNm + '<span class="da">' + gfn_formatDateStr(obj.modDd,"-") + '</span></span>';
                     statusHtml2 = '<button type="button" onclick="fn_reson(\'' + obj.reqId + '\')">사유</button>';
                     statusHtml3 = '<div id="rejected_reason_' + obj.reqId + '" style="display:none;">' + obj.rtnCont + '</div>';
                 } else if(obj.reqStatusDivCd == "R") { // 열람완료 
                     statusHtml1 = '<span class="ti imposs">' + obj.reqStatusDivNm + '<span class="da">' + gfn_formatDateStr(obj.modDd,"-") + '</span></span>';
                     statusHtml2 = '';
                 } else if(obj.reqStatusDivCd == "C" || obj.reqStatusDivCd == "D") { // 취소, 미열람 
                     statusHtml1 = '<span class="ti imposs">' + obj.reqStatusDivNm + '<span class="da">' + gfn_formatDateStr(obj.modDd,"-") + '</span></span>';
                     statusHtml2 = '';
                 }
                 
                 div.append($('<div />').attr('class', 'n-state').html(statusHtml1 + statusHtml2 + statusHtml3));
                 
                 $("div.list-data").append(div);
                 
             });
         }
         
         pageLoad("fn_searchArticle", jsonObj.pagingPageIndex, jsonObj.pagingTotRecordCount, jsonObj.pagingStartPage, jsonObj.pagingEndPage, jsonObj.pagingLastPage); 

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

 function fn_reson(reqId) {
	$("#divRejectedReasonDetail").html($("#rejected_reason_" + reqId).text());
	$("#divRejectedReason").fadeIn();
 }
 
 function fn_closeReason() {
	 $("#divRejectedReason").fadeOut();
	 $("#divRejectedReasonDetail").html("");
 }
 
 function fn_cancel(title, mngOrgCd, reqId, masterId) {
	 
	 if(!confirm(title + " 방문열람을 취소하시겠습니까?")) return;
	 
     var reqUrl = "${pageContext.request.contextPath}/read/cancelReadItemAjax.do";
     
     var inputData = {
               "mngOrgCd" : mngOrgCd
             , "reqId" : reqId
             , "masterId" : masterId
     };
     
     //--------------------------------------
     // 요청 처리 
     //--------------------------------------
     $.ajax({
         type: "post",
         contentType: "application/json; charset=utf-8",
         url: reqUrl,
         dataType: "json",
         data: JSON.stringify(inputData),
     }).done(function(data){
         <%
         // 그리드 데이터 예시 : 
         // (1) 페이징 클라이언트에서 수행하는 경우(pageloading = false) : [{ "articleNo": 1, "articleType": "01" }, { "articleNo": 2, "articleType": "02" }]
         // (2) 페이징 서버에서 수행하는 경우(pageloading = true) : {data: [{...}], itemsCount: 255}
         %>
         var jsonObj = JSON.parse(data);
         // 자료 신청(or 예약)이 취소되었습니다.
         if(jsonObj.resultCode == "S") {
        	 fn_searchArticle(1);
        	 alert(jsonObj.resultMessage);
         } else {
        	 alert(jsonObj.resultMessage);
         }
         
     }).fail(function (jqXHR, textStatus, errorThrown) {
         alert("처리에 실패하였습니다. 관리자에게 문의 바랍니다.");
     });
 
 }
 </script>


    <!-- 방문열람 섹션 -->
    <div class="location visit-data">
        <h2 class="blind">방문열람 섹션영역</h2>
        <div class="inner">
            <div class="row-top">
                <div class="location-box">
                    <ul class="loc">
                        <li>HOME</li>
                        <li>마이페이지</li>
                        <li class="on">${pageTitle }</li>
                    </ul>
                    <ul class="tit">
                        <li><span>방문열람</span>관리</li>
                    </ul>
                </div>
                <div class="arr"><img src="/images/icon/icon-join-arr2.png" alt="화살표 아이콘"></div>
            </div>
            <div class="contents row-bottom">
                <div class="list-box visit-box">
                    <form name="frm" id="frm" method="post">
                    <input type="hidden" name="reqStatusDivCd" id="reqStatusDivCd" value="${reqStatusDivCd }" />
                    <input type="hidden" name="pageIndex" id="pageIndex" title="페이지번호" value="${pageIndex }" />
                    <input type="hidden" name="pageSize" id="pageSize" title="페이지크기" value="${pageSize }" />
                    <input type="hidden" name="masterId" id="masterId" title="페이지크기" value="" />
                
                    <div class="tab">
                        <ul class="tabs">
                            <li><a href="javascript:void(0);" onclick="fn_search('A')">신청</a></li>
                            <li><a href="javascript:void(0);" onclick="fn_search('C')"><!-- <img src="/images/icon/icon-new.png" alt="뉴 아이콘">-->취소</a></li>
                            <li><a href="javascript:void(0);" onclick="fn_search('R')">열람완료</a></li>
                            <li><a href="javascript:void(0);" onclick="fn_search('D')">미열람</a></li>
                        </ul>
                    
                        <div class="title">
                            <span class="count">총 <em id="itemsCount">0</em>건</span>
                            <div class="list-search-wrap list-top">
                                <div class="list-select">
                                    <select name="mngOrgCd" id="mngOrgCd" title="문화원 선택">
                                        <option value="">문화원 전체</option>
                                        <c:forEach var="orgItem" items="${rentMngOrgList}" varStatus="status">
                                        <option value="<c:out value="${orgItem.mngOrgCd }" />"
                                                <c:if test="${orgItem.mngOrgCd == mngOrgCd }">selected</c:if>><c:out
                                                value="${orgItem.mngOrgNm }" /></option>
                                        </c:forEach>
                                    </select>
                                    <label for="mngOrgCd" style="display:none">문화원 선택</label>
                                </div>
                            </div>
                        </div>

                        <div class="tab_content">
                            <div class="tabs_item">
                                <div class="inner">

                                    <div class="list-wrap">
                                        <div class="list-data">
                                            <div class="list t-tit-line">
                                                <div class="n-cultural">문화원</div>
                                                <div class="n-data">자료정보</div>
                                                <div class="n-subscription">신청</div>
                                                <div class="n-visit">희망방문일</div>
                                                <div class="n-return">반납예정일</div>
                                                <div class="n-state">신청상태</div>
                                            </div>
                                            <div class="no-result" style="display:none;">
                                                <span>자료가 없습니다.</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <ul id="paging" class="paging"></ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    </form>      
                </div>
            </div>
        </div>
    </div>


    <!-- 소장자료 반려 팝업 -->
    <div id="divRejectedReason" class="pop-return" style="display:none;">
        <div class="row Title">
            <p>지방문화원 소장자료</p>
            <h3>반려사유</h3>
        </div>
        <div class="inner">
            <div class="row Text">
                <div class="text-box mCustomScrollbar" data-mcs-theme="dark-2" id="divRejectedReasonDetail"></div>
            </div>
            <div class="row btn-box">
                <button type="button" class="btn btn-color" onclick="fn_closeReason()">확인</button>
            </div>
            <button type="button" class="return-close" onclick="fn_closeReason()"></button>
        </div>
        <div class="Bg"></div>
    </div>
