package nlib.sch.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cmm.Constant;
import cmm.util.CmmUtil;
import kccf.res.service.ResourcesService;
import kccf.sch.service.SearchService;
import nlib.cmm.NlibCommonController;
import nlib.cmm.service.CodeService;
import nlib.cmm.service.NlibProperty;
import nlib.cmm.service.PagingVO;
import nlib.col.service.CartService;
import nlib.col.service.CollectionService;
import nlib.col.service.CollectionVO;
import nlib.col.service.InterestService;
import nlib.col.service.RisService;
import nlib.sch.service.NlibSearchService;
import nlib.sch.service.NlibSearchVO;
import nlib.util.StringUtil;

@Controller
public class NlibSearchController extends NlibCommonController {

    private static final Logger log = LoggerFactory.getLogger(NlibSearchController.class);
    static final String DEFUALT_PAGE_SIZE = NlibProperty.getProperty("list.paging.page.size");
    
    @Resource(name = "cartService")
    private CartService cartService;

    @Resource(name = "codeService") 
	private CodeService codeService;
	
	@Resource(name="risService")
	private RisService risService;

	@Resource(name = "interestService")
	private InterestService interestService;
	
	@Resource(name = "nlibProperty")
    protected NlibProperty nlibProperty;
	
	@Resource(name = "searchService")
    private SearchService searchService;
	
	@Resource(name = "collectionService")
	private CollectionService collectionService;
	
	@Resource(name = "nlibSearchService")
	private NlibSearchService nlibSearchService;
	
	/** resourcesService */
	@Resource(name = "resourcesService")
	private ResourcesService resourcesService;
	
	/**
	 * 소장자료 화면을 호출한다.
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/search/searchList.do")
	public String searchList(
			HttpServletRequest req
			, Authentication authentication
			, ModelMap model
			, @ModelAttribute("searchVO") NlibSearchVO searchVO
  			, HttpServletRequest request
			, HttpServletResponse res) throws Exception {
		List<CollectionVO> operList = new ArrayList();
		// 페이징 사이즈 코드 목록 조회 (DB방식으로 변경 2021.08.06 KNKIM)
		List<Map<String,String>> pageSizeCodes = codeService.listCodes("PAGE_SIZE_OPTION");
		
		if(searchVO.getPageIndex() < 1) searchVO.setPageIndex(1);
		if(searchVO.getPageSize() < 1) searchVO.setPageSize(DEFUALT_PAGE_SIZE);
		
		  	//검색엔진 
	  	try{ 	
	  		searchVO.setQuery(StringUtil.getString(searchVO.getQuery(), ""));
			searchVO.setReQuery(StringUtil.getString(searchVO.getReQuery(), ""));
			
			//결과내재검색만 입력했을경우
			if(searchVO.getQuery().length() == 0 && searchVO.getReQuery().length() > 0)
			{
				searchVO.setQuery(searchVO.getReQuery());
				searchVO.setReQuery("");
				searchVO.setReQueryChk("query");
			}
			
			searchVO = nlibSearchService.getSearch(searchVO);
			
			//페이지 셋팅
			PagingVO pageVO = new PagingVO();
		  	pageVO.setPagingVO(Integer.parseInt(searchVO.getTotalCount()), searchVO.getPageIndex(), searchVO.getPageSize());
		  	
			String mbInfoId = getMbInfoId(request);
			
			if(StringUtil.isEmpty(mbInfoId)) {
				// 검색엔진에서 받아온 masterId로 상세정보 조회
				operList = collectionService.setDetailInfoForList(searchVO.getResultList(), null, NlibProperty.getString("thumbnail.image.url.small"));
			} else {
				// 검색엔진에서 받아온 masterId로 상세정보 조회
				operList = collectionService.setDetailInfoForList(searchVO.getResultList(), getMbInfoId(request), NlibProperty.getString("thumbnail.image.url.small"));
			}
			
			//결과 데이터 담기
			searchVO.setResultList(operList);
			
			// 경로
			CmmUtil.setNfsPathModelMap(request,model);
	
			model.addAttribute("pageVO", pageVO);
			model.addAttribute("searchVO", searchVO);
		}catch(Exception e){
			e.printStackTrace();
		}
	  	//주제분야 목록 조회
  		List<Map<String,String>> clsf = codeService.listCtClsfs();
	  	//자료유형
	  	List<Map<String, String>> firstClassList = codeService.listCodes(Constant.CODE_ID_MASTER_TYPE_DIV_CD);
	  	List<Map<String, String>> secondClassList = codeService.listCodes(Constant.CODE_ID_DTLS_TYPE_DIV_CD);
	  	
	  	//검색엔진 주제분야 카운트
	  	List<HashMap<String, String>> subject= searchVO.getSubjectCountList();
	  	List<HashMap<String, String>> type= searchVO.getTypeCountList();
	  	
	  	int count = 0;
	  	// 검색엔진 건수 자료 조합 
	  	for(int i=0; i<clsf.size(); i++) {
	  		count = 0;
	  		for(int j=0; j<subject.size(); j++)
	  		{
	  			//if(String.valueOf(clsf.get(i).get("CLSF_ID")).equals(String.valueOf(subject.get(j).get("category_nm"))))
	  			if(String.valueOf(clsf.get(i).get("clsfId")).equals(String.valueOf(subject.get(j).get("category_nm"))))
	  			{
	  				count += Integer.parseInt(subject.get(j).get("category_cnt"));
	  			}
	  			if(String.valueOf(clsf.get(i).get("clsfId")).equals(String.valueOf(subject.get(j).get("category_nm_up"))))
	  			{
	  				count += Integer.parseInt(subject.get(j).get("category_cnt"));
	  			}
	  		}
	  		clsf.get(i).put("cnt", Integer.toString(count));	  		
	  	}
	  	
	  	for(int i=0; i<firstClassList.size(); i++) {
	  		count = 0;
	  		for(int j=0; j<type.size(); j++)
	  		{
	  			if(String.valueOf(firstClassList.get(i).get("sCodeId")).equals(String.valueOf(type.get(j).get("class_nm_up"))))
	  			{
	  				count += Integer.parseInt(type.get(j).get("class_cnt"));
	  			}
	  		}
	  		firstClassList.get(i).put("cnt", Integer.toString(count));	  		
	  	}
	  	
	  	for(int i=0; i<secondClassList.size(); i++) {
	  		count = 0;
	  		for(int j=0; j<type.size(); j++)
	  		{
	  			if(String.valueOf(secondClassList.get(i).get("column1")).equals(String.valueOf(type.get(j).get("class_nm"))))
	  			{
	  				count += Integer.parseInt(type.get(j).get("class_cnt"));
	  			}
	  		}
	  		secondClassList.get(i).put("cnt", Integer.toString(count));	  		
	  	}
		// 반환 정보 
	  	model.addAttribute("pageSizeCodes", pageSizeCodes);
	  	//주제분야
	  	model.addAttribute("firstCategoryList", clsf);
	  	model.addAttribute("secondCategoryList", clsf);
	  	//자료유형
  		model.addAttribute("firstClassList", firstClassList);
  	    model.addAttribute("secondClassList", secondClassList);
	  	
		
		searchVO.setQuery(searchVO.getQuery().replaceAll("\\\"", "&quot;"));
		return "nlib/collection/searchList";
	}
		
	/**
	 * 소장자료 상세조회
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/search/searchItemDetail.do")
	public String searchItemDetail(
			HttpServletRequest req
			, Authentication authentication
			, @RequestParam Map<String, String> paramMap
			, ModelMap model
			, @ModelAttribute("searchVO") NlibSearchVO searchVO
  			, HttpServletRequest request
			, HttpServletResponse res
			) throws Exception {
		String masterId = request.getParameter("masterId");
		String mbInfoId = getMbInfoId(request);
		
		CollectionVO vo = new CollectionVO();
		vo.setMasterId(masterId);
		vo.setMbInfoId(mbInfoId);
		System.out.println(NlibProperty.getString("thumbnail.image.url.big"));
		vo = collectionService.getItemInfo(vo,NlibProperty.getString("thumbnail.image.url.big"));
		
		//반납예정일 편집
		if(!StringUtil.getString(vo.getRtnExpctDd(),"").equals(""))
		{
			String strDate = vo.getRtnExpctDd();
			SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat newDtFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date formatDate = dtFormat.parse(strDate);
			String strNewDtFormat = newDtFormat.format(formatDate);
			vo.setRtnExpctDd(strNewDtFormat);
		}
		model.addAttribute("result", vo);
		return "nlib/collection/searchItemDetail";
	}
	/**
	 * 소장자료를 조회한다.
	 * 
	 * @param req
	 * @return
	 *//*
	@RequestMapping(value="/collection/listItemsAjax.do", method = RequestMethod.POST)
	public ResponseEntity<String> listItemsAjax(HttpServletRequest req, 
			Authentication authentication, @RequestBody CollectionVO searchCollectionVO)  {
	
		//String searchKeyword = paramMap.get("searchKeyword");
		if(searchCollectionVO.getPageIndex() < 1) searchCollectionVO.setPageIndex(1);
		if(searchCollectionVO.getPageSize() < 1) searchCollectionVO.setPageSize(DEFUALT_PAGE_SIZE);
		
		
		int totalCount= 0;
		//사용자 정보를 가져온다.
		NlibLoginVO loginVO = getNlibLoginVO(authentication);
				
		searchCollectionVO.setPageStart(searchCollectionVO.getPageIndex(), searchCollectionVO.getPageSize());
	  	List<CollectionVO> List = new ArrayList();
	  	
	  	// 요청 
	  	List = risService.listItems(searchCollectionVO);
	  	totalCount = risService.countListItems(searchCollectionVO);
	  	
	  	PagingVO pageVO = new PagingVO();
	  	pageVO.setPagingVO(totalCount, searchCollectionVO.getPageIndex(), searchCollectionVO.getPageSize());
	  	
		//-------------------------------
		// REQ VO 구성 
		//-------------------------------
	  	DataApiReqVO reqVO = new DataApiReqVO();
	  	reqVO.setPageIndex(pageIndex);
	  	reqVO.setPageSize(pageSize);
	  	reqVO.putInfoItem("searchKeyword", searchKeyword);
	
	  	// 요청 
	  	//DataApiResVO resVO = collectionService.listItems(reqVO);
	  	
		//-------------------------------
		// JSON변환 응답 처리
		//-------------------------------
	  	// JS-GRID 페이징 처리를 포함한 응답값 처리
	  	// {data: [{...}], 
	  	//  itemsCount: 255
	  	// }
	  	HashMap<String, Object> retMap = new HashMap<String, Object>();
	  	retMap.put("data", resVO.getList(DataApiVO.XML_EL_NAME_RECORD));
	  	retMap.put("itemsCount", resVO.getRecordTotCount());
	  	retMap.put("data", List);
	  	retMap.put("pageVO", pageVO);
	  	
	  	return makeResponseEntityJson(retMap);
	}*/
	
	/**
	 * 상세검색 팝업.
	 *  
	 * (2021.10.19 YJS 추가)
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/search/getDetailedSearchFormPopup.do")
	public String getDetailedSearchFormPopup(HttpServletRequest request, ModelMap model) throws Exception {
		
		//주제분야 목록 조회
		List<Map<String,String>> clsf = null;
  		clsf = codeService.listCtClsfs();
  		model.addAttribute("firstCategoryList", clsf);
  		model.addAttribute("secondCategoryList", clsf);

  		List<Map<String,String>> firstClassList = null;
  		firstClassList = codeService.listCodes(Constant.CODE_ID_MASTER_TYPE_DIV_CD);
  		
  		List<Map<String,String>> secondClassList = null;
  		secondClassList =  codeService.listCodes(Constant.CODE_ID_DTLS_TYPE_DIV_CD);
  		//자료유형
  		model.addAttribute("firstClassList", codeService.listCodes(Constant.CODE_ID_MASTER_TYPE_DIV_CD));
  	    model.addAttribute("secondClassList", codeService.listCodes(Constant.CODE_ID_DTLS_TYPE_DIV_CD));
  	    
    	
        return "nlib/search/getDetailedSearchFormPopup";
	}
	
	/**
	 * 소장자료 상세 내용 조회한다.
	 * 
	 * @param req
	 * @return
	 *//*
	@RequestMapping("/search/selectItemInfo.do")
	public String selectItemInfo(HttpServletRequest req, Authentication authentication, @RequestParam Map<String, String> paramMap, ModelMap model)  {
		// 목록 이동시 전달할 매개변수 
				String searchKeyword = paramMap.get("searchKeyword");
				String pageIndex = paramMap.get("pageIndex");
				String pageSize = paramMap.get("pageSize");
				String message = paramMap.get("message");
				
				// 게시물 번호 
				String articleNo = paramMap.get("articleNo");
				
				log.debug("selectQnA > pageIndex = " + pageIndex);
				log.debug("selectQnA > pageSize = " + pageSize);
				log.debug("selectQnA > searchKeyword = " + searchKeyword);
				log.debug("selectQnA > articleNo = " + articleNo);
				log.debug("selectQnA > message = " + message);
	
				//-------------------------------
				// REQ VO 구성 
				//-------------------------------
		    	DataApiReqVO reqVO = new DataApiReqVO();
		    	reqVO.setPageIndex(pageIndex);
		    	reqVO.setPageSize(pageSize);
		    	reqVO.addInfoItem("boardNo", "QNA");       // 게시판ID
		    	reqVO.addInfoItem("articleNo", articleNo); // 게시물번호
	
		    	// 요청 
		    	DataApiResVO resVO = collectionService.selectItemInfo(reqVO);
		    	
		    	// 반환 정보 
		    	model.addAttribute("articleNo"    , articleNo);
		    	model.addAttribute("article"      , resVO.getInfo()); // 게시물 상세 
		    	model.addAttribute("message"      , message);
		    	model.addAttribute("pageIndex"    , pageIndex);
		    	model.addAttribute("pageSize"     , pageSize);
		    	model.addAttribute("searchKeyword", searchKeyword);
	
				return "nlib/collection/selectItemInfo";
	}*/
}
