package kccf.sch.web;

import static kccf.sch.common.WNDefine.CONNECTION_CLOSE;

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 kccf.res.service.ResourcesService;
import kccf.sch.common.WNSearch;
import kccf.sch.common.WNUtils;
import kccf.sch.service.ArkService;
import kccf.sch.service.PopWordService;
import kccf.sch.service.SearchCollectionResult;
import kccf.sch.service.SearchService;
import kccf.sch.service.vo.ArkVO;
import kccf.sch.service.vo.PopWordVO;
import kccf.sch.service.vo.SearchCollectionVO;
import kccf.sch.service.vo.SearchVO;
import kccf.sch.service.vo.Sf1VO;
import kccf.ton.service.LocalToonService;
import nlib.cmm.service.NlibProperty;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 cmm.Constant;
import cmm.service.CmmActivityHstVO;
import cmm.service.CmmService;
import cmm.util.CmmUtil;
import cmm.util.DataMap;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import egovframework.com.cmm.ComDefaultCodeVO;
import egovframework.com.cmm.service.EgovCmmUseService;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
//추가

@Controller
public class SearchController {
	/** LOGGER */
	//@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(SearchController.class);

	@Resource(name = "searchService")
    private SearchService searchService;
	
    @Resource(name = "nlibProperty")
    protected NlibProperty nlibProperty;
    
	@Resource(name="ArkService")
	private ArkService arkService;
	
	@Resource(name="PopwordService")
	private PopWordService popWordService;

	@Resource(name = "localToonService")
    private LocalToonService localToonService;
	
    /** CmmService */
   	@Resource(name = "cmmService")
    private CmmService cmmService;

    /** EgovCmmUseService */
    @Resource(name = "EgovCmmUseService")
    private EgovCmmUseService cmmUseService;
   	
	/** resourcesService */
	@Resource(name = "resourcesService")
	private ResourcesService resourcesService;
	
	/**SEARCHLIST**/
	@RequestMapping(value="/sch/totalSearchList.do")
	public String totalSearchList (
	   			  @ModelAttribute("searchVO") SearchVO searchVO
	   			  , String all_totalCount
	   			 , String gubun
	   			, String gubun_ajax
	   			, ModelMap model
	   			, HttpServletRequest request
				, HttpServletResponse res
				
	   			) throws Exception 
	{
		try{
				LOGGER.debug("[PATH][/sch/totalSearchList.do][searchVO][{}]",searchVO.toString());
				//System.out.println("\n\n\n\n\n\n\n/*****************totalSearchList-searchVO.toString()********************/"+searchVO.toString());
				
				// 검색관련 서버 설정
				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);

				if(gubun.equals("1")){ //&&(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals(""))
					all_totalCount = Integer.toString(searchService.getSearch_All_cnt(searchVO, sf1Vo));
					// all_totalCount = Integer.toString(collResult_all_cnt);
//					 System.out.println("################################"+searchVO.getCollection()+"/"+all_totalCount+"/"+gubun);
				}else {
					all_totalCount = Integer.toString(searchService.getSearch_All_cnt(searchVO, sf1Vo)); //2019-11-27 gubun??
//					 System.out.println("else ################################:"+searchVO.getCollection()+"/"+all_totalCount+"/"+gubun);
				}
				//System.out.println("\n\n\n\n\n################################gubun_ajax:"+searchVO.getCollection()+"/"+gubun_ajax);
				
				// 결과
				SearchCollectionVO collInfo = new SearchCollectionVO();
				SearchCollectionVO collMap = new SearchCollectionVO();
				SearchCollectionVO collNumber = new SearchCollectionVO();
				SearchCollectionVO collPick = new SearchCollectionVO();
				SearchCollectionVO collReferecne = new SearchCollectionVO();
				SearchCollectionVO collStory = new SearchCollectionVO();
				SearchCollectionVO collCulturePost = new SearchCollectionVO();
				SearchCollectionVO collCulturePostHot = new SearchCollectionVO();
				SearchCollectionVO collTotal = new SearchCollectionVO();
				SearchCollectionVO collToon = new SearchCollectionVO();
				

				int totalCount = 0;
				int page_totalCount =0; 
				 
				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 paramMap = new DataMap();
							paramMap.put("mId", mapResult.get("MEDIA_ID"));
							if(StringUtils.isNotEmpty(mapResult.get("MEDIA_ID").toString())){
						    	DataMap media = cmmService.selectCmmAmsAssetsMediaDetail(paramMap);
						    	String mediaId = media.getString("id");
						    	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("story")){
						collStory = coll;
					}
					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);
							}
					}
					else if(collEn.indexOf("toon") >= 0){
						if(collEn.equals("toon")){
							collToon = coll;
						}
						else if(collEn.equals("toon_tags")){
							model.addAttribute("toon_tags", coll);
						}
						// 최근열람툰
				   		CmmActivityHstVO cmmActivityHstVO = new CmmActivityHstVO();
				   		cmmActivityHstVO.setTargetId(CmmUtil.getCookieId(request)); 
						cmmActivityHstVO.setUaType(Constant.UA_TYPE_W);
						cmmActivityHstVO.setActivityType(Constant.ACTIVITY_TYPE_O);
						cmmActivityHstVO.setContentType(Constant.CONTENT_TYPE_T);
						model.addAttribute("openPageList", localToonService.selectLocalToonOpenPageList(cmmActivityHstVO));
						model.addAttribute("openPageHotList", localToonService.selectLocalToonOpenPageHotList(cmmActivityHstVO));
					}
				}
	
				
				// - 값 (검색엔진 오류 일때  0값 으로 )
				if(totalCount < 0){
					totalCount = 0;
				}
				model.addAttribute("totalCount",totalCount);
				model.addAttribute("info", collInfo);
				model.addAttribute("map", collMap);
				model.addAttribute("number", collNumber);
				model.addAttribute("pick", collPick);
				model.addAttribute("reference", collReferecne);
				model.addAttribute("story", collStory);
				model.addAttribute("culturePost", collCulturePost);
				model.addAttribute("culturePostHot", collCulturePostHot);
				model.addAttribute("total", collTotal);
				model.addAttribute("all_totalCount",all_totalCount); 
				model.addAttribute("toon",collToon); 
	
				// 경로
				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 ="";
			

			/*if(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals("")){
				resultUrl = "kccf/sch/totalSearchList.kccf";
			}else if(searchVO.getCollection().equals("pick_Coll")){
				resultUrl = "kccf/sch/searchPickList.kccf";
			}else if(searchVO.getCollection().equals("culturePost_Coll")){
				resultUrl = "kccf/sch/searchCulturePostList.kccf";
			}else if(searchVO.getCollection().equals("number_Coll")){
				resultUrl = "kccf/sch/searchNumberList.kccf";
			}else if(searchVO.getCollection().equals("story_Coll")){
				resultUrl = "kccf/sch/searchStoryList.kccf";
			}else if(searchVO.getCollection().equals("reference_Coll")){
				resultUrl = "kccf/sch/searchReferenceList.kccf";
			}else if(searchVO.getCollection().equals("info_Coll")){
				resultUrl = "kccf/sch/searchInfoList.kccf";
			}*/

			ComDefaultCodeVO CodeVO = new ComDefaultCodeVO();
			CodeVO.setCodeId(Constant.CODE_ID_FMS014);
			model.addAttribute("firstCategoryList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
			CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS015);
	        model.addAttribute("secondCategoryList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
			CodeVO.setCodeId(Constant.CODE_ID_FMS004);
			model.addAttribute("themaList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
			CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS005);
	        model.addAttribute("seriesList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
			CodeVO.setCodeId(Constant.CODE_ID_FMS012);
			model.addAttribute("firstClassList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
			CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS013);
	        model.addAttribute("secondClassList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS016);
	        model.addAttribute("contentTypeList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS018);
	        model.addAttribute("couSidoList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        List<DataMap> councilList = resourcesService.selectCouncilList();    	
	    	model.addAttribute("councilList", councilList);
	        
			if(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals("")){
				if(gubun_ajax != null && gubun_ajax.equals("2")){
					resultUrl = "kccf/sch/totalSearchListAjax";
				}else{
					resultUrl = "kccf/sch/totalSearchList.kccf";
				}
				
			}else if(searchVO.getCollection().equals("pick_Coll")){
				resultUrl = "kccf/sch/searchPickListAjax";
			}else if(searchVO.getCollection().equals("culturePost_Coll")){
				resultUrl = "kccf/sch/searchCulturePostList";
			}else if(searchVO.getCollection().equals("number_Coll")){
				resultUrl = "kccf/sch/searchNumberListAjax";
			}else if(searchVO.getCollection().equals("story_Coll")){
				resultUrl = "kccf/sch/searchStoryListAjax";
			}else if(searchVO.getCollection().equals("reference_Coll")){
				resultUrl = "kccf/sch/searchReferenceListAjax";
			}else if(searchVO.getCollection().equals("info_Coll")){
				resultUrl = "kccf/sch/searchInfoListAjax";
			}else if(searchVO.getCollection().equals("toon_Coll")){
				resultUrl = "kccf/sch/searchToonListAjax";
			}
			
			//System.out.println("\n\n\n\n\n################################gubun_ajax:"+searchVO.getCollection()+"/"+gubun_ajax+"/"+resultUrl);
		
	    	// ams 서버 패스 정보
	    	CmmUtil.setAmsPathModelMap(request,model);
	    	searchVO.setQuery(searchVO.getQuery().replaceAll("\\\"", "&quot;"));
	    	searchVO.setExactQuery(searchVO.getExactQuery().replaceAll("\\\"", "&quot;"));
			
			return resultUrl;
	}	
	

	
	
	
	/** POPWORD */
	@RequestMapping(value="/sch/popword.do")
	public String popword(@ModelAttribute("PopWordVO") PopWordVO popWordVo, ModelMap model) throws Exception {
		
		String popWordStr = "";
		String managerIp =  nlibProperty.getString("search.managerIp");
		int managerPort = nlibProperty.getInt("search.managerPort"); 
		
		Sf1VO sf1Vo = new Sf1VO();
		sf1Vo.setManagerIp(managerIp);
		sf1Vo.setManagerPort(managerPort);
		
		popWordStr = popWordService.getPopWord(popWordVo, sf1Vo);
		model.addAttribute("popWordStr", popWordStr);
		
		return "kccf/sch/popword/popword.kccf-sch";
	}
	
	
	/** ARK */
	@RequestMapping(value="/sch/ark.do")
	public String ark(@ModelAttribute("ArkVO") ArkVO arkVO, ModelMap model) throws Exception {
		String arkStr = "";
		String managerIp =   nlibProperty.getString("search.managerIp");
		int managerPort =  nlibProperty.getInt("search.managerPort")	;
		
		
		Sf1VO sf1Vo = new Sf1VO();
		sf1Vo.setManagerIp(managerIp);
		sf1Vo.setManagerPort(managerPort);
		
		arkStr = arkService.getArk(arkVO, sf1Vo);
		
		model.addAttribute("arkStr", arkStr);

		return "kccf/sch/ark/ark.kccf-sch";
		
	}
	
	  
	@RequestMapping(value="/sch/totalSearchList_ajax.do")
   	public String totalSearchList_ajax (
   		  @ModelAttribute("searchVO") SearchVO searchVO
			  , String all_totalCount
			  , String gubun
			  , ModelMap model
			  , HttpServletRequest request
			  ,HttpServletResponse res
			) throws Exception 
	{
		try{
				LOGGER.debug("[PATH][/sch/totalSearchList.do][searchVO][{}]",searchVO.toString());
				//System.out.println("\n\n\n\n\n\n\n/*****************totalSearchList-searchVO.toString()********************/"+searchVO.toString());
				
				// 검색관련 서버 설정
				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);

				if(gubun.equals("1")){ //&&(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals(""))
					all_totalCount = Integer.toString(searchService.getSearch_All_cnt(searchVO, sf1Vo));
					// all_totalCount = Integer.toString(collResult_all_cnt);
//					 System.out.println("################################"+searchVO.getCollection()+"/"+all_totalCount+"/"+gubun);
				}else {
					all_totalCount = Integer.toString(searchService.getSearch_All_cnt(searchVO, sf1Vo)); //2019-11-27 gubun??
//					 System.out.println("else ################################:"+searchVO.getCollection()+"/"+all_totalCount+"/"+gubun);
				}
				//System.out.println("\n\n\n\n\n################################gubun_ajax:"+searchVO.getCollection()+"/"+gubun_ajax);
				
				// 결과
				SearchCollectionVO collInfo = new SearchCollectionVO();
				SearchCollectionVO collMap = new SearchCollectionVO();
				SearchCollectionVO collNumber = new SearchCollectionVO();
				SearchCollectionVO collPick = new SearchCollectionVO();
				SearchCollectionVO collReferecne = new SearchCollectionVO();
				SearchCollectionVO collStory = new SearchCollectionVO();
				SearchCollectionVO collCulturePost = new SearchCollectionVO();
				SearchCollectionVO collCulturePostHot = new SearchCollectionVO();
				SearchCollectionVO collTotal = new SearchCollectionVO();
				SearchCollectionVO collToon = new SearchCollectionVO();
				

				int totalCount = 0;
				int page_totalCount =0; 
				 
				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 paramMap = new DataMap();
							paramMap.put("mId", mapResult.get("MEDIA_ID"));
							if(StringUtils.isNotEmpty(mapResult.get("MEDIA_ID").toString())){
						    	DataMap media = cmmService.selectCmmAmsAssetsMediaDetail(paramMap);
						    	String mediaId = media.getString("id");
						    	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("story")){
						collStory = coll;
					}
					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);
							}
					}
					else if(collEn.indexOf("toon") >= 0){
						if(collEn.equals("toon")){
							collToon = coll;
						}
						else if(collEn.equals("toon_tags")){
							model.addAttribute("toon_tags", coll);
						}
						// 최근열람툰
				   		CmmActivityHstVO cmmActivityHstVO = new CmmActivityHstVO();
				   		cmmActivityHstVO.setTargetId(CmmUtil.getCookieId(request)); 
						cmmActivityHstVO.setUaType(Constant.UA_TYPE_W);
						cmmActivityHstVO.setActivityType(Constant.ACTIVITY_TYPE_O);
						cmmActivityHstVO.setContentType(Constant.CONTENT_TYPE_T);
						model.addAttribute("openPageList", localToonService.selectLocalToonOpenPageList(cmmActivityHstVO));
						model.addAttribute("openPageHotList", localToonService.selectLocalToonOpenPageHotList(cmmActivityHstVO));
					}
				}
	
				
				// - 값 (검색엔진 오류 일때  0값 으로 )
				if(totalCount < 0){
					totalCount = 0;
				}
				model.addAttribute("totalCount",totalCount);
				model.addAttribute("info", collInfo);
				model.addAttribute("map", collMap);
				model.addAttribute("number", collNumber);
				model.addAttribute("pick", collPick);
				model.addAttribute("reference", collReferecne);
				model.addAttribute("story", collStory);
				model.addAttribute("culturePost", collCulturePost);
				model.addAttribute("culturePostHot", collCulturePostHot);
				model.addAttribute("total", collTotal);
				model.addAttribute("all_totalCount",all_totalCount); 
				model.addAttribute("toon",collToon); 
	
				// 경로
				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 ="";
			

			/*if(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals("")){
				resultUrl = "kccf/sch/totalSearchList.kccf";
			}else if(searchVO.getCollection().equals("pick_Coll")){
				resultUrl = "kccf/sch/searchPickList.kccf";
			}else if(searchVO.getCollection().equals("culturePost_Coll")){
				resultUrl = "kccf/sch/searchCulturePostList.kccf";
			}else if(searchVO.getCollection().equals("number_Coll")){
				resultUrl = "kccf/sch/searchNumberList.kccf";
			}else if(searchVO.getCollection().equals("story_Coll")){
				resultUrl = "kccf/sch/searchStoryList.kccf";
			}else if(searchVO.getCollection().equals("reference_Coll")){
				resultUrl = "kccf/sch/searchReferenceList.kccf";
			}else if(searchVO.getCollection().equals("info_Coll")){
				resultUrl = "kccf/sch/searchInfoList.kccf";
			}*/

			ComDefaultCodeVO CodeVO = new ComDefaultCodeVO();
			CodeVO.setCodeId(Constant.CODE_ID_FMS014);
			model.addAttribute("firstCategoryList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
			CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS015);
	        model.addAttribute("secondCategoryList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
			CodeVO.setCodeId(Constant.CODE_ID_FMS004);
			model.addAttribute("themaList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
			CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS005);
	        model.addAttribute("seriesList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
			CodeVO.setCodeId(Constant.CODE_ID_FMS012);
			model.addAttribute("firstClassList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
			CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS013);
	        model.addAttribute("secondClassList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS016);
	        model.addAttribute("contentTypeList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        CodeVO = new ComDefaultCodeVO();
	        CodeVO.setCodeId(Constant.CODE_ID_FMS018);
	        model.addAttribute("couSidoList", cmmUseService.selectCmmCodeDetail(CodeVO));
	        
	        List<DataMap> councilList = resourcesService.selectCouncilList();    	
	    	model.addAttribute("councilList", councilList);
	        
			if(searchVO.getCollection().equals("ALL") || searchVO.getCollection().equals("")){
				resultUrl = "kccf/sch/totalSearchListAjax";
			}else if(searchVO.getCollection().equals("pick_Coll")){
				resultUrl = "kccf/sch/searchPickListAjax";
			}else if(searchVO.getCollection().equals("culturePost_Coll")){
				resultUrl = "kccf/sch/searchCulturePostList";
			}else if(searchVO.getCollection().equals("number_Coll")){
				resultUrl = "kccf/sch/searchNumberListAjax";
			}else if(searchVO.getCollection().equals("story_Coll")){
				resultUrl = "kccf/sch/searchStoryListAjax";
			}else if(searchVO.getCollection().equals("reference_Coll")){
				resultUrl = "kccf/sch/searchReferenceListAjax";
			}else if(searchVO.getCollection().equals("info_Coll")){
				resultUrl = "kccf/sch/searchInfoListAjax";
			}else if(searchVO.getCollection().equals("toon_Coll")){
				resultUrl = "kccf/sch/searchToonListAjax";
			}
			
			//System.out.println("\n\n\n\n\n################################gubun_ajax:"+searchVO.getCollection()+"/"+gubun_ajax+"/"+resultUrl);
		
	    	// ams 서버 패스 정보
	    	CmmUtil.setAmsPathModelMap(request,model);
	    	searchVO.setQuery(searchVO.getQuery().replaceAll("\\\"", "&quot;"));
	    	searchVO.setExactQuery(searchVO.getExactQuery().replaceAll("\\\"", "&quot;"));
			
			return resultUrl;
	}	
	
	/**
	 * OCR문서의 몇번째 문서인지 리턴하기 위한 api
	 * reference.js 에서 function reference_viewOcr(mediaId, query)로 호출
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/sch/getOcrId.do")
	public String getOcrId (HttpServletRequest request, ModelMap model ) throws Exception {
		//디버깅 보기 설정
		boolean isDebug = false;
		String exquery = ""; // exquery 조건 필드
		String jsonStr = "";
		
		int startCount = 0;	//보여줄 페이지 번호
		String strOperation ="";
		
		int viewResultCount = WNUtils.parseInt(WNUtils.getCheckReqXSS(request, "LISTCOUNT", "1"), 1); // 출력건수
		String sort = WNUtils.getCheckReqXSS(request, "SORT", "ID"); // 정렬방식
		String sortOrder = WNUtils.getCheckReqXSS(request, "SORTORDER", "ASC"); // 정렬방식
	    String collection = WNUtils.getCheckReqXSS(request, "COLLECTION", "ocr"); // 컬랙션
	    String media_id = WNUtils.getCheckReqXSS(request, "MEDIA_ID", ""); // 메뉴
	    String query = WNUtils.getCheckReqXSS(request, "query", "");
		
		String[] collections = null;
	    if(collection.equals("ALL")) { //통합검색인 경우
	    	collections = new String[]{"info","map","number","pick","reference","story","culturePost","total","toon"};	//COLLECTIONS;
	    } else {                        //개별검색인 경우
	        collections = new String[] { collection };
	    }
	    
	    exquery += "<MEDIA_ID:contains:" + media_id + ">";
		
		// 검색관련 서버 설정
		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);
		
		WNSearch wnsearch = new WNSearch(isDebug, false, collections, null);
//	    WNSearch wnsearch = new WNSearch(isDebug, false, collections, null, WNDefine.USE_RESULT_JSON);
	    wnsearch.setSf1Vo(sf1Vo);
	    wnsearch.set(query, "ALL", viewResultCount, startCount, sort, sortOrder, strOperation, exquery, "1970.01.01", WNUtils.getCurrentDate());
	    wnsearch.search(query, false, CONNECTION_CLOSE, true, sf1Vo.getSearchIp(), sf1Vo.getSearchPort());
	    String debugMsg = wnsearch.printDebug() != null ? wnsearch.printDebug().trim() : "";
	    
	    int min = viewResultCount;
	    if(wnsearch.getResultTotalCount("ocr") < viewResultCount){
	    	min = wnsearch.getResultTotalCount("ocr");	//가장 적은 수로 결과를 리턴
	    }
	    	
	    
	    Gson gson = new Gson();
	    JsonArray doc = new JsonArray();
	    String[] fields = {"ID","MEDIA_ID","FIRST_PAGE_NUM","LAST_PAGE_NUM","ORDER_NUM","FILE_NAME"};
	    for(int idx =0 ; idx < min; idx++){
	    	JsonObject obj = new JsonObject();
	    	for(String field : fields){
	    		obj.addProperty(field, wnsearch.getField("ocr", field, idx, false));
	    	}
	    	doc.add(obj);
	    }
	    
	    jsonStr = gson.toJson(doc);
//	    jsonStr = wnsearch.getResultJson();
			
	    model.addAttribute("jsonStr", jsonStr);
	    model.addAttribute("isDebug", isDebug);    //디버그메시지출력여부
	    model.addAttribute("debugMsg", debugMsg);  //디버그 메시지 출력
	    
	    
	    if ( wnsearch != null )
	        wnsearch.closeServer();
	    
	    return "kccf/sch/ocr/schOcrRetrunId.kccf-sch";
	}
    
}
