package nlib.sch.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.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cmm.Constant;
import cmm.util.CmmUtil;
import cmm.util.DataMap;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import kccf.res.service.ResourcesService;
import kccf.sch.service.SearchCollectionResult;
import kccf.sch.service.SearchService;
import kccf.sch.service.vo.SearchCollectionVO;
import kccf.sch.service.vo.SearchVO;
import kccf.sch.service.vo.Sf1VO;
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.DeptVO;
import nlib.col.service.InterestService;
import nlib.col.service.RisService;
import nlib.restful.service.DataApiReqVO;
import nlib.restful.service.DataApiResVO;
import nlib.user.service.NlibLoginVO;
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;
	
	/** resourcesService */
	@Resource(name = "resourcesService")
	private ResourcesService resourcesService;
	
	/**
	 * 소장자료 화면을 호출한다.
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/collection/listItems.do")
	public String listItems(
			HttpServletRequest req
			, Authentication authentication
			, @RequestParam Map<String, String> paramMap
			, ModelMap model
			, @ModelAttribute("searchVO") SearchVO searchVO
  			, String all_totalCount
  			, HttpServletRequest request
			, HttpServletResponse res) throws Exception {
		String searchKeyword = paramMap.get("searchKeyword");
		String pageIndex = StringUtil.getString(paramMap.get("pageIndex"), "1");
		String pageSize  = StringUtil.getString(paramMap.get("pageSize") , DEFUALT_PAGE_SIZE);
		List<DeptVO> vo = new ArrayList();
		List<CollectionVO> list = new ArrayList();
		
		// 페이징 사이즈 코드 목록 조회 (DB방식으로 변경 2021.08.06 KNKIM)
		List<HashMap<String,String>> pageSizeCodes = codeService.listCodes("PAGE_SIZE_OPTION");
		
		// 자료유형 코드 목록 조회
		List<HashMap<String,String>> masterType = codeService.listCodes("MASTER_TYPE_DIV_CD");
		List<HashMap<String,String>> dtlsType = codeService.listCodes("DTLS_TYPE_DIV_CD");
		
		//주제분야 목록 조회
		List<HashMap<String,String>> clsf = codeService.listCtClsfs();
		
		//문화원 목록 조회
		/*vo = risService.selectOrgList();*/
		
		// 반환 정보 
	  	model.addAttribute("pageIndex"    , pageIndex);
	  	model.addAttribute("pageSize"     , pageSize);
	  	model.addAttribute("searchKeyword", searchKeyword);
	  	model.addAttribute("pageSizeCodes", pageSizeCodes);
	  	model.addAttribute("masterType", masterType);
	  	model.addAttribute("dtlsType", dtlsType);
	  	model.addAttribute("masterClsf", clsf);
	  	model.addAttribute("dtlsClsf", clsf);
	  	/*model.addAttribute("orgList",vo);*/
	  	
	  	
	  	//검색엔진 
  	try{ 	
	  	searchVO.setRealQuery("한복");
		searchVO.setQuery("한복");
		searchVO.setCollection("reference_Coll");
		// 검색관련 서버 설정
		String searchIp = nlibProperty.getString("search.searchIp");
		int searchPort = nlibProperty.getInt("search.searchPort");
		int searchTimeOut = nlibProperty.getInt("search.searchTimeOut");
		
		Sf1VO sf1Vo = new Sf1VO();
		sf1Vo.setSearchIp(searchIp);
		sf1Vo.setSearchPort(searchPort);
		sf1Vo.setSearchTimeOut(searchTimeOut);
		
		SearchCollectionResult collResult = searchService.getSearch(searchVO, sf1Vo);

		all_totalCount = Integer.toString(searchService.getSearch_All_cnt(searchVO, sf1Vo));
		
		// 결과
		SearchCollectionVO collReferecne = new SearchCollectionVO();
		SearchCollectionVO collCulturePost = new SearchCollectionVO();
		SearchCollectionVO collCulturePostHot = new SearchCollectionVO();
		SearchCollectionVO collTotal = new SearchCollectionVO();
		SearchCollectionVO collInfo = new SearchCollectionVO();
		SearchCollectionVO collMap = new SearchCollectionVO();
		SearchCollectionVO collNumber = new SearchCollectionVO();
		SearchCollectionVO collPick = new SearchCollectionVO();
		SearchCollectionVO collStory = new SearchCollectionVO();

		int totalCount = 0;
		int page_totalCount =0; 
		 
		//각 탭의 totalcount등의 데이터를 가져온다.
		ArrayList<SearchCollectionVO>  collList = collResult.getCollectionList();
		
		int collListSize = collList.size();
		for(int i = 0 ; i < collListSize ; i++){
			SearchCollectionVO coll = collList.get(i);
			String collEn = coll.getCollectionName();
			
			
			
			if(collEn.indexOf("culturePostHot") < 0 && collEn.indexOf("total") < 0 && collEn.indexOf("_cate") < 0){
					totalCount = totalCount + coll.getTotalCount();
			}
			
			if( !searchVO.getCollection().equals("ALL") && searchVO.getCollection().indexOf("_Coll") >= 0){
				if(searchVO.getCollection().replace("_Coll", "").equals(collEn)){
					page_totalCount = coll.getTotalCount();
				}
			}
			if(collEn.equals("info")){
				collInfo = coll;
			}
			else if(collEn.equals("map")){
				collMap = coll;
			}
			else if(collEn.equals("number")){
				collNumber = coll;
			}
			else if(collEn.equals("pick")){
				collPick = coll;
				
			}
			else if(collEn.equals("reference")){
				collReferecne = coll;
				for(int j = 0 ; j < collReferecne.getSearchResultList().size() ; j++){
					Map<Object ,Object> mapResult = collReferecne.getSearchResultList().get(j);
					DataMap paramMap1 = new DataMap();
					paramMap1.put("mId", mapResult.get("MEDIA_ID"));
					if(StringUtils.isNotEmpty(mapResult.get("MEDIA_ID").toString())){
				    	//DataMap media = cmmService.selectCmmAmsAssetsMediaDetail(paramMap1);
				    	String url="";
				    	/*String mediaId = media.getString("mid");
				    	String mediaInterfaceId = media.getString("interfaceId");
				    	String url = "";
				    	if (StringUtils.isNotEmpty(mediaInterfaceId)) { // mediaInterfaceId가 존재할 경우만 URL 정보 생성
					    	if(media.get("assetType") != null){
					    		if(media.get("assetType").toString().equals("문서") ){		        		
					        		url = CmmUtil.getPropertyStr(Constant.KCCF_HOME_KEY)+"/npdfView.do?";
					        		url += "npdf="+Constant.UA_TYPE_R+mediaInterfaceId; // MEDIA 의 INTERFACE_ID 사용
					        		
					    		}else if(media.get("assetType").toString().equals("링크")){
					    			url = media.get("linkData").toString();
					    		}else{
					    			url = CmmUtil.getPropertyStr(Constant.KCCF_HOME_KEY)+"/lib/libraryDetail.do?contentId="+mediaId;
					        		url += "&rfType="+Constant.UA_TYPE_R; // 히스토리 등록 시 사용
					    		}
					    	}
				    	}*/
				    	mapResult.put("LINK_URL", url);
					}
				}
			}
			else if(collEn.equals("culturePost")){
				collCulturePost = coll;
			}
			else if(collEn.equals("total")){
				collTotal = coll;
			}
			else if(collEn.equals("total_tags")){
				model.addAttribute("total_tags", coll);
			}
			else if(collEn.indexOf("_cate") >= 0){ //cate
				 if(collEn.equals("first_class_cate")){
						model.addAttribute("first_class_cate", coll);
					}
					else if(collEn.equals("second_class_cate")){
						model.addAttribute("second_class_cate", coll);
					}
					else if(collEn.equals("first_council_cate")){
						model.addAttribute("first_council_cate", coll);
					}
					else if(collEn.equals("second_council_cate")){
						model.addAttribute("second_council_cate", coll);
					}
					else if(collEn.equals("first_category_cate")){
						model.addAttribute("first_category_cate", coll);
					}
					else if(collEn.equals("second_category_cate")){
						model.addAttribute("second_category_cate", coll);
					}
					else if(collEn.equals("first_theme_cate")){
						model.addAttribute("first_theme_cate", coll);
					}
					else if(collEn.equals("second_theme_cate")){
						model.addAttribute("second_theme_cate", coll);
					}
			}
			else if(collEn.indexOf("culturePostHot") >= 0){ //cate
					if(collEn.equals("culturePostHot")){
						collCulturePostHot = coll;
					}
					else if(collEn.equals("culturePostHot_keywords")){
						model.addAttribute("culturePostHot_keywords", coll);
					}
					else if(collEn.equals("culturePostHot_tags")){
						model.addAttribute("culturePostHot_tags", coll);
					}
			}
		}

		
		// - 값 (검색엔진 오류 일때  0값 으로 )
		if(totalCount < 0){
			totalCount = 0;
		}
		model.addAttribute("totalCount",totalCount);
		model.addAttribute("reference", collReferecne);
		model.addAttribute("culturePost", collCulturePost);
		model.addAttribute("culturePostHot", collCulturePostHot);
		model.addAttribute("total", collTotal);
		model.addAttribute("all_totalCount",all_totalCount); 

		CollectionVO colVO = new CollectionVO();
		// 검색엔진에서 받아온 데이터로 api통해 열람,대출신청상태등 받아온다 
		for(int i = 0; collReferecne.getSearchResultList().size() > i;i++)
		{
			/*collReferecne.getSearchResultList().get(i).get("MASTER_ID");*/
			colVO.setMasterId("UR-91F3EB466E2743C48CC264BAC8CC573B");
			list.add(colVO);
		}
		System.out.println(list.size());
		System.out.println(list.get(0).getMasterId());
		System.out.println(list.get(1).getMasterId());
		System.out.println(list.get(2).getMasterId());
		System.out.println(list.get(3).getMasterId());
		list = collectionService.setDetailInfoForList(list);
		
		
		// 경로
		CmmUtil.setNfsPathModelMap(request,model);

		// 페이징 관련
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(searchVO.getStartCount());
		if(searchVO.getCollection().indexOf("toon") >= 0){
			if(searchVO.getViewCount() == 10){
				paginationInfo.setRecordCountPerPage(12);
			}else{
				paginationInfo.setRecordCountPerPage(searchVO.getViewCount());
			}
		}else{
			paginationInfo.setRecordCountPerPage(searchVO.getViewCount());
		}
		paginationInfo.setPageSize((CmmUtil.isMobile(request)) ? 5 :10); 
		//paginationInfo.setTotalRecordCount(totalCount);
		
		paginationInfo.setTotalRecordCount(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals("") ?   totalCount :page_totalCount );
		model.addAttribute("paginationInfo", paginationInfo);
		
		
		//serviceVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		//serviceVO.setLastIndex(paginationInfo.getLastRecordIndex());
		//serviceVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
		model.addAttribute("searchVO", searchVO);
		//System.out.println("\n\n\n\n\n\n\n/*****************totalSearchList-searchVO.toString()********************/"+searchVO.toString());
		
	}catch(Exception e){
		e.printStackTrace();
	}

	String resultUrl ="";
	
	//자료유형
	model.addAttribute("firstClassList", codeService.listCodes(Constant.CODE_ID_MASTER_TYPE_DIV_CD));
    model.addAttribute("secondClassList", codeService.listCodes(Constant.CODE_ID_DTLS_TYPE_DIV_CD));

    List<DataMap> councilList = resourcesService.selectCouncilList();    	
	model.addAttribute("councilList", councilList);
    
	// ams 서버 패스 정보
	CmmUtil.setAmsPathModelMap(request,model);
	searchVO.setQuery(searchVO.getQuery().replaceAll("\\\"", "&quot;"));
	searchVO.setExactQuery(searchVO.getExactQuery().replaceAll("\\\"", "&quot;"));
		return "nlib/collection/searchList";
	}
		
	/**
	 * 소장자료를 조회한다.
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/collection/listItemsAjax.do")
	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);
	}
	/**
	 * 소장자료 상세 내용 조회한다.
	 * 
	 * @param req
	 * @return
	 *//*
	@RequestMapping("/collection/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";
	}*/
}
