package nlib.col.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import nlib.cmm.NlibCommonController;
import nlib.cmm.service.CodeService;
import nlib.cmm.service.NlibProperty;
import nlib.cmm.service.PagingVO;
import nlib.col.service.RisService;
import nlib.col.service.CollectionService;
import nlib.col.service.CollectionVO;
import nlib.col.service.DeptVO;
import nlib.col.service.InterestService;
import nlib.col.service.RentService;
import nlib.user.service.NlibLoginVO;
import nlib.util.StringUtil;

/**
 * <pre>
 * @Class Name : InterestController.java
 * 
 * @Description : 관심자료 컨트롤러
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 10. 01.    JSYOO       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP JSYOO
 * @since 2021. 10. 01.
 * @version 1.0
 *
 */
@Controller
public class InterestController extends NlibCommonController
{
	private static final Logger log = LoggerFactory.getLogger(InterestController.class);
	static final String DEFUALT_PAGE_SIZE = NlibProperty.getProperty("list.paging.page.size");
	
	@Resource(name = "interestService")
	private InterestService interestService;
	
	@Resource(name = "risService")
	private RisService risService;

	@Resource(name = "codeService") 
	private CodeService codeService;
	
	@Resource(name = "collectionService")
	private CollectionService collectionService;
	
	/**
	 * 관심 자료 화면을 호출한다.
	 * 
	 * @param req
	 * @return
	 */
	@Secured("ROLE_USER")
	@RequestMapping("/interest/listInterests.do")
	public String listInterests(HttpServletRequest req, HttpServletRequest request, Authentication authentication,
			@RequestParam Map<String, String> paramMap,
			CollectionVO searchCollectionVO, ModelMap model) throws Exception  {
		String message = "";
		String mbInfoId = getMbInfoId(request);
    	
    	if(StringUtil.isEmpty(mbInfoId)) {
    		message = "로그인하신 후, 이용바랍니다.";
    		model.addAttribute("message", message);
    		model.addAttribute("url", "/login/loginForm.do");
    		return "nlib/cmm/alert";
    	}
		List<DeptVO> vo = new ArrayList();
		
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		
		searchCollectionVO.setMbInfoId(loginVO.getMbInfoId());
				
		//문화원 목록 조회
		vo = interestService.selectOrgList(searchCollectionVO);
		model.addAttribute("pdfUri",NlibProperty.getProperty("pdf.uri"));
		model.addAttribute("deptList",vo);
    	model.addAttribute("searchCollection", searchCollectionVO);
		return "nlib/collection/listInterests";
	}

	/**
	 * 관심 자료를 조회한다.
	 * 
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/interest/listInterestsAjax.do")
	public ResponseEntity<String> listInterestsAjax(HttpServletRequest req, HttpServletRequest request,
			Authentication authentication, @RequestBody CollectionVO searchCollectionVO) throws Exception  {

		if(searchCollectionVO.getPageIndex() < 1) searchCollectionVO.setPageIndex(1);
		if(searchCollectionVO.getPageSize() < 1) searchCollectionVO.setPageSize(DEFUALT_PAGE_SIZE);
		
		List<CollectionVO> operList = new ArrayList();
		
		int totalCount= 0;
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
				
		searchCollectionVO.setMbInfoId(loginVO.getMbInfoId());
		searchCollectionVO.setPageStart(searchCollectionVO.getPageIndex(), searchCollectionVO.getPageSize());
    	
    	// 요청 
		List<CollectionVO> interestList = interestService.listInterests(searchCollectionVO);
    	totalCount = interestService.countListInterests(searchCollectionVO);
    	
    	String mbInfoId = getMbInfoId(request);
		operList = collectionService.setDetailInfoForList(interestList, getMbInfoId(request), NlibProperty.getString("thumbnail.image.url.small"));
		//-------------------------------
		// JSON변환 응답 처리
		//-------------------------------
    	// JS-GRID 페이징 처리를 포함한 응답값 처리
    	// {data: [{...}], 
    	//  itemsCount: 255
    	// }
    	HashMap<String, Object> retMap = new HashMap<String, Object>();
    	retMap.put("data", operList);
    	retMap.put("itemsCount", totalCount);
    	
    	PagingVO pageVO = new PagingVO();
	  	pageVO.setPagingVO(totalCount, searchCollectionVO.getPageIndex(), searchCollectionVO.getPageSize());
	  	retMap.put("pagingPageIndex"     , pageVO.getPageIndex());
	  	retMap.put("pagingTotRecordCount", pageVO.getTotRecordCount());
	  	retMap.put("pagingStartPage"     , pageVO.getStartPage());
	  	retMap.put("pagingEndPage"       , pageVO.getEndPage());
	  	retMap.put("pagingLastPage"      , pageVO.getLastPage());
	  	
    	return makeResponseEntityJson(retMap);
	} 
	
	/**
	 * 관심자료 목록 삭제
	 * @param masterIdList
	 */
	@RequestMapping(value="/interest/deleteInterests.ajax")
	@ResponseBody
	public String deleteInterests(@RequestParam(value="masterIdList[]") List<String> masterIdList,Authentication authentication)  {
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		String message="";
		
		if(loginVO.getMbInfoId() == null)
		{
			message="로그인 후 이용하실 수 있습니다.";
			return message;
		}
		
		interestService.deleteInterests(masterIdList,loginVO.getMbInfoId());
		message ="선택하신 관심자료가 삭제되었습니다.";
		return message;
	}

	/**
	 * 관심자료 추가
	 * @param masterIdList
	 */
	@RequestMapping(value="/interest/insertInterest.ajax")
	@ResponseBody
	public String insertInterest(@RequestParam(value="masterId") String masterId,HttpServletResponse response,Authentication authentication,HttpServletRequest request)  {
		int count = 0;
		String message = "";
		
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
		
		CollectionVO vo = new CollectionVO();
		vo.setMbInfoId(loginVO.getMbInfoId());
		vo.setMasterId(masterId);
		
		if(vo.getMbInfoId() == null)
		{
			message="로그인 후 이용하실 수 있습니다.";
			return message;
		}
		
		count = interestService.countInterest(vo);
		
		if(!StringUtil.getString(masterId,"").equals(""))
		{
			//중복된 관심자료가 있을시
			if(count > 0)
			{
				message="이미 추가된 관심자료입니다.";
			}else {
				interestService.insertInterest(vo);
				message="관심자료에 추가되었습니다.";
			}
		}else {
			message="관심자료에 추가할 수 없습니다.";
		}
		return message;
	}
	
}