package cmm.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

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

import kccf.res.service.ResourcesService;
import kccf.sch.service.vo.SearchVO;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cmm.Constant;
import cmm.service.CmmAmsDocTableOfContentsVO;
import cmm.service.CmmApiService;
import cmm.service.CmmFileService;
import cmm.service.CmmService;
import cmm.service.ExtService;
import cmm.service.FileDetailVO;
import cmm.util.CmmUtil;
import cmm.util.CmmVO;
import cmm.util.DataMap;
import cmm.util.MessageAlertUtil;
import egovframework.com.cmm.ComDefaultCodeVO;
//import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.service.EgovCmmUseService;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

/**  
 * @Class Name : CmmController.java
 * @author ecplaza
 * @since 2018-04-17
 * @version 1.0
 */
@Controller
public class CmmController {
	/** LOGGER */
	private static final Logger LOGGER = LoggerFactory.getLogger(CmmController.class);
	
    /** EgovPropertyService */
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;
    
//    @Resource(name="egovMessageSource")
//    EgovMessageSource egovMessageSource;
//    
	@Resource(name = "cmmFileService")
	private CmmFileService cmmFileService;
	
	/** extService */
	@Resource(name = "extService")
	private ExtService extService;
	
	/** cmmApiService */
	@Resource(name = "cmmApiService")
	private CmmApiService cmmApiService;
	
	/** cmmService */
	@Resource(name = "cmmService")
	private CmmService cmmService;
    
    /** EgovCmmUseService */
    @Resource(name = "EgovCmmUseService")
    private EgovCmmUseService cmmUseService;
	
	/** resourcesService */
	@Resource(name = "resourcesService")
	private ResourcesService resourcesService;
	
    @RequestMapping(value="/cmm/downloadFile.do")
	public void cvplFileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException, EgovBizException {

		String atchFileId = request.getParameter("atchFileId");
		String fileSn = request.getParameter("fileSn");

		FileDetailVO paramVO = new FileDetailVO();
		paramVO.setAtchFileId(atchFileId);
		paramVO.setFileSn(fileSn);
		FileDetailVO fileDetailVO = cmmFileService.selectFileDetail(paramVO);

		File uFile = new File(fileDetailVO.getFileStreCours(), fileDetailVO.getStreFileNm());
		long fSize = uFile.length();

		if (fSize > 0) {
			String mimetype = "application/x-msdownload";

			response.setContentType(mimetype);
			setDisposition(fileDetailVO.getOrignlFileNm(), request, response);
			//response.setContentLength(fSize);

			BufferedInputStream in = null;
			FileInputStream fis = null;
			BufferedOutputStream out = null;

			try {
				
				fis = new FileInputStream(uFile);
				in = new BufferedInputStream(fis);
				out = new BufferedOutputStream(response.getOutputStream());

				FileCopyUtils.copy(in, out);
				out.flush();
			} catch (IOException ioe) {
				LOGGER.error("Error in cvplFileDownload()", ioe);
			} catch (NullPointerException npe) {
				LOGGER.error("Error in cvplFileDownload()", npe);
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException ioe) {
						LOGGER.error("Error in cvplFileDownload()", ioe);
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (IOException ioe) {
						LOGGER.error("Error in cvplFileDownload()", ioe);
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (IOException ioe) {
						LOGGER.error("Error in cvplFileDownload()", ioe);
					}
				}
			}

		} else {
			MessageAlertUtil.alertBack("파일이 존재하지 않습니다." , response);
		}
	}
    
    @RequestMapping("/cmm/selectIconFileDownLoad.do")
    public String selectIconFileDownLoad(@ModelAttribute("searchVO") FileDetailVO fileVO, @RequestParam Map<String, Object> commandMap, ModelMap model) throws IOException, EgovBizException {
		String atchFileId = (String)commandMap.get("param_atchFileId");
		List<FileDetailVO> result = cmmFileService.selectIconFileDownLoad(atchFileId);
		model.addAttribute("fileList", result);
		model.addAttribute("fileListCnt", result.size());
		model.addAttribute("atchFileId", atchFileId);
		return "kdm/cmm/cmmIconFileList";
    }
    
    @RequestMapping(value="/cmm/cmmSigunguList.do")
    public ModelAndView selectCmmSigunguList(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws EgovBizException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	model.addAttribute("resultList", extService.selectExtSigunguList(paramMap));
    	
    	return modelAndView;
    }
    
    @RequestMapping(value="/cmm/cmmSigunguList2.do")
    public ModelAndView selectCmmSigunguList2(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws EgovBizException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	model.addAttribute("resultList", extService.selectExtSigunguList2(paramMap));
    	
    	return modelAndView;
    }
    
    @RequestMapping(value="/cmm/cmmGisSigunguList.do")
    public ModelAndView selectCmmGisSigunguList(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws EgovBizException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	model.addAttribute("resultList", extService.selectExtGisSigunguList(paramMap));
    	
    	return modelAndView;
    }
    
    @RequestMapping(value="/cmm/cmmGisSigunguList2.do")
    public ModelAndView selectCmmGisSigunguList2(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws EgovBizException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	model.addAttribute("resultList", extService.selectExtGisSigunguList(paramMap));
    	
    	return modelAndView;
    }
    
    @RequestMapping(value="/cmm/cmmGisDongList.do")
    public ModelAndView selectCmmGisDongList(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws EgovBizException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	model.addAttribute("resultList", extService.selectExtGisDongList(paramMap));
    	
    	return modelAndView;
    }
    
    @RequestMapping(value="/cmm/cmmJusoCheck.do")
    public ModelAndView jusoCheck(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws EgovBizException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	String addr = paramMap.getString("localSido") + " " +  paramMap.getString("localSigungu") + " " + paramMap.getString("localDong");
    	paramMap.clear();
    	paramMap.setString("juso", addr);
    	DataMap rtnMap = cmmApiService.getNaverApiJuso(paramMap);
    	model.addAttribute("resultData", rtnMap);
    	
    	return modelAndView;
    }
    @RequestMapping(value="/cmm/cmmPscHstTotCnt.do")
    public void selectCmmPscHstTotCnt(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	String successYn = "N";
    	
    	int cnt = 0;
    	try {
    		cnt = cmmService.selectCmmPscHstTotCnt(paramMap);
    		successYn = "Y";
		} catch (EgovBizException e) {
			LOGGER.error("Error in selectCmmPscHstTotCnt()", e);
		}
    	
    	JSONObject jsonObj = new JSONObject();
    	jsonObj.put("successYn", successYn);
    	jsonObj.put("cnt", cnt);
    	
    	
    	response.setContentType("text/html; charset=utf-8");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "no-cahce");
		response.setHeader("Cache-Control", "no-store"); // HTTP 1.0
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    		 
    	response.getWriter().write(jsonObj.toString());
    }
    
    @RequestMapping(value="/cmm/regCmmPscHst.do")
    public void insertCmmPscHst(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	DataMap paramMap1 = DataMap.getParamMap(request);
    	DataMap paramMap2 = DataMap.getParamMap(request);
    	DataMap paramMap3 = DataMap.getParamMap(request);
    	
    	paramMap1.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap1.setString("sidoName", paramMap1.getString("localSido1")); 
    	paramMap1.setString("sigunguName", paramMap1.getString("localSigungu1"));
    	
    	paramMap2.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap2.setString("sidoName", paramMap2.getString("localSido2"));     	
    	paramMap2.setString("sigunguName", paramMap2.getString("localSigungu2"));
    	
    	paramMap3.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap3.setString("sidoName", paramMap3.getString("localSido3")); 
    	paramMap3.setString("sigunguName", paramMap3.getString("localSigungu3"));
    	
    	String successYn = "N";
    	String addr = "";
    	
    	try {
    		
    		addr = paramMap1.getString("localSido1") + "|" + paramMap1.getString("localSigungu1") + "^";
    		addr = addr + paramMap2.getString("localSido2") + "|" + paramMap2.getString("localSigungu2") + "^";
    		addr = addr + paramMap3.getString("localSido3") + "|" + paramMap3.getString("localSigungu3");
    				
    		paramMap1.setInt("sortOrdr", 1);
    		if(cmmService.selectCmmPscHstTotCnt(paramMap1)>0){
    			cmmService.updateCmmPscHst(paramMap1); 
    		}else{ 
    			cmmService.insertCmmPscHst(paramMap1);
    		}
    		
    		paramMap2.setInt("sortOrdr", 2);
    		if(cmmService.selectCmmPscHstTotCnt(paramMap2)>0){
    			cmmService.updateCmmPscHst(paramMap2); 
    		}else{ 
    			cmmService.insertCmmPscHst(paramMap2);
    		}
    		
    		paramMap3.setInt("sortOrdr", 3);
    		if(cmmService.selectCmmPscHstTotCnt(paramMap3)>0){
    			cmmService.updateCmmPscHst(paramMap3); 
    		}else{ 
    			cmmService.insertCmmPscHst(paramMap3);
    		}
    		
    		CmmUtil.removeCookie(request, response, CmmUtil.getCookie(request, propertiesService.getString("kccf.cookie.addr.key")));
    		//CmmUtil.removeCookie(request, response, CmmUtil.getCookie(request, propertiesService.getString("kccf.cookie.pscType.key")));
    		CmmUtil.setEncoderCookie(response,  propertiesService.getString("kccf.cookie.addr.key"), addr);
    		//CmmUtil.setEncoderCookie(response,  propertiesService.getString("kccf.cookie.pscType.key"), paramMap.getString("pscType")); 
    		
    		successYn = "Y";
    	} catch (PatternSyntaxException ex1) {
    		LOGGER.error("Error in insertCmmPscHst()", ex1);
		} catch (EgovBizException ex2) {
			LOGGER.error("Error in insertCmmPscHst()", ex2);
		}
	    	
    	JSONObject jsonObj = new JSONObject();
    	jsonObj.put("successYn", successYn);
    	
    	
    	response.setContentType("text/html; charset=utf-8");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "no-cahce");
		response.setHeader("Cache-Control", "no-store"); // HTTP 1.0
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    		 
    	response.getWriter().write(jsonObj.toString());
    }
    
    @RequestMapping(value="/cmm/regCmmPscHst-data.do")
    public String insertCmmPscHstAjax(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap.setString("sidoName", paramMap.getString("localSido")); 
    	paramMap.setString("sigunguName", paramMap.getString("localSigungu"));
    	
    	String addr = "";
    	try {
    		
    		addr = paramMap.getString("localSido") + "|" + paramMap.getString("localSigungu");
    		if(cmmService.selectCmmPscHstTotCnt(paramMap)>0){
    			cmmService.updateCmmPscHst(paramMap); 
    		}else{ 
    			cmmService.insertCmmPscHst(paramMap);
    		}
    		
    		CmmUtil.removeCookie(request, response, CmmUtil.getCookie(request, propertiesService.getString("kccf.cookie.addr.key")));
    		CmmUtil.removeCookie(request, response, CmmUtil.getCookie(request, propertiesService.getString("kccf.cookie.pscType.key")));
    		CmmUtil.setEncoderCookie(response,  propertiesService.getString("kccf.cookie.addr.key"), addr);
    		CmmUtil.setEncoderCookie(response,  propertiesService.getString("kccf.cookie.pscType.key"), paramMap.getString("pscType")); 
    		
    		
    		int pscHstCnt = 0;
    		DataMap pscHstMap = cmmService.selectCmmPscHstDetail(paramMap);
    		List<DataMap> sigunguList = null;
    		if(pscHstMap != null){
    			pscHstCnt = 1;
    			paramMap.clear();
    			paramMap.setString("sido", pscHstMap.getString("sidoName"));
    			sigunguList = extService.selectExtSigunguList(paramMap);
    		}
    		model.addAttribute("pscHstCnt", pscHstCnt);
    		model.addAttribute("pscHst", pscHstMap); 
    		model.addAttribute("pscHstSigunguList", sigunguList); 
    		
    	} catch (PatternSyntaxException ex1) {
    		LOGGER.error("Error in insertCmmPscHst()", ex1);
		} catch (EgovBizException ex2) {
			LOGGER.error("Error in insertCmmPscHst()", ex2);
		}
    	
    	return "kccf/cmm/userSetPopupAjax.jsp";
    }
    
    @RequestMapping(value="/cmm/cmmActivityHstAllListTotCnt.do")
    public ModelAndView selectCmmActivityHstAllListTotCnt(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	String successYn = "N";
    	
    	List<DataMap> resultList =  null;
    	try {
    		resultList = cmmService.selectCmmActivityHstAllListTotCnt(paramMap);
    		successYn = "Y";
		} catch (EgovBizException e) {
			LOGGER.error("Error in selectCmmActivityHstAllListTotCnt()", e);
		}
    	model.addAttribute("successYn", successYn);
    	model.addAttribute("resultList", resultList);
    	return modelAndView;
    }
    @RequestMapping(value="/cmm/regCmmScrap.do")
    public void insertCmmScrap(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap.setString("contentId", paramMap.getString("cId")); 
    	paramMap.setString("contentType", paramMap.getString("cType")); 
    	
    	String keyName = "contentId";
    	if(Constant.CONTENT_TYPE_G.equals(paramMap.getString("contentType"))
    			|| Constant.CONTENT_TYPE_I.equals(paramMap.getString("contentType"))
    			|| Constant.CONTENT_TYPE_P.equals(paramMap.getString("contentType")) ){
    		keyName = "targetId";
    	}
    	paramMap.setString("linkUrl", paramMap.getString("lUrl") + "?"+keyName+"="+paramMap.getString("contentId")); 
    	
    	String successYn = "Y";
    	String resultCode = "01";
    	try {
    		if("on".equals(paramMap.getString("already"))){
    			if(cmmService.selectCmmScrapCnt(paramMap)<1){
    				successYn = "N";
    				resultCode = "98";
    			}else{
    				cmmService.deleteCmmScrapInfo(paramMap);
    			}
    		}else{
    			// 다른곳에서 등록시에는 불이 안들어온 상태로 DB에만 등록되어있어서 체크 해야함.
    			if(cmmService.selectCmmScrapCnt(paramMap)>0){
    				successYn = "N";
    				resultCode = "99";
    			}else{
    				resultCode = "00";
    				cmmService.insertCmmScrap(paramMap);
    			}
    		}
		} catch (EgovBizException e) {
			LOGGER.error("Error in insertCmmScrap()", e);
		}
    	JSONObject jsonObj = new JSONObject();
    	jsonObj.put("successYn", successYn);
    	jsonObj.put("resultCode", resultCode);
    	
    	response.setContentType("text/html; charset=utf-8");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "no-cahce");
		response.setHeader("Cache-Control", "no-store"); // HTTP 1.0
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    		 
    	response.getWriter().write(jsonObj.toString());
    }
    @RequestMapping(value="/cmm/regCmmRecentlyView.do")
    public void insertCmmRecentlyView(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap.setString("contentId", paramMap.getString("cId")); 
    	paramMap.setString("contentType", paramMap.getString("cType")); 
    	paramMap.setString("linkUrl", paramMap.getString("lUrl")); 
    	
    	String successYn = "N";
    	try {
			cmmService.insertCmmActivityHst(paramMap);
    		successYn = "Y";
		} catch (EgovBizException e) {
			LOGGER.error("Error in insertCmmRecentlyView()", e);
		}
    	JSONObject jsonObj = new JSONObject();
    	jsonObj.put("successYn", successYn);
    	
    	response.setContentType("text/html; charset=utf-8");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "no-cahce");
		response.setHeader("Cache-Control", "no-store"); // HTTP 1.0
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    		 
    	response.getWriter().write(jsonObj.toString());
    }
    @RequestMapping(value="/cmm/regSatisfaction.do")
    public ModelAndView insertSatisfaction(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
		String satisfaction;
		switch (paramMap.get("satisfaction").toString()){
		    case "매우만족" : satisfaction="5";
		            break;   
		    case "만족" : satisfaction="4";
		            break;
		    case "보통" : satisfaction="3";
		            break;
		    case "불만족" : satisfaction="2";
            		break;        
		    default: satisfaction="1";
		            break;
		}
		paramMap.setString("contentId", paramMap.get("contentId").toString()); 
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(request)); 
    	paramMap.setString("stsfdg", satisfaction);  //만족도
    	paramMap.setString("stsfdgCnt", paramMap.get("satisfactionText").toString());  
    	paramMap.setString("contentType", paramMap.get("type").toString());  
    	String successYn = "N";
    	try {
    		if(cmmService.selectSatisfactionTotCnt(paramMap) > 0){
    			successYn = "Y";
    		}else{
    			cmmService.insertSatisfaction(paramMap);
    			successYn = "N";
    		}
    	} catch (EgovBizException e) {
			LOGGER.error("Error in insertSatisfaction()", e);
		}
    	
    	model.addAttribute("successYn", successYn);
    	return modelAndView;
    }
    
    
    @RequestMapping(value="/cmm/cmmAmsAssetMediaList.do")
    public String selectCmmAmsAssetMediaList(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(req);
    	
    	//paramMap.setString("aId", paramMap.getString("aId")); 
    	//cmmVO.setaId(paramMap.getString("aId"));
    	
    	// 스크랩 여부 키 
    	paramMap.setString("sessionId", CmmUtil.getCookieId(req)); 
    	
    	model.addAttribute("paramVO", cmmVO); // 파라미터
    	
    	// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
    	// ams nfs 파일 경로
    	CmmUtil.setNfsPathModelMap(req,model);
    	
    	
    	return "/kccf/cmm/layerMediaListAjax";
	}
    
    
    /**
     * AMS ASSETS 상세 정보
     * pick 레이어 에셋의 상세정보 : 모든 데이터
     * @param cmmVO
     * @param model
     * @param commandMap
     * @param req
     * @param res
     * @return
     * @throws EgovBizException
     */
    @RequestMapping(value="/cmm/cmmAmsAssetsPick.do")
    public String selectCmmAmsAssetsPick(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(req);
    	LOGGER.info("selectCmmAmsAssetsPick() paramMap={}", paramMap);
    	
    	//paramMap.setString("aId", paramMap.getString("aId")); 
    	//cmmVO.setaId(paramMap.getString("aId"));
    	
    	// 스크랩 여부 키 
    	paramMap.setString("sessionId", CmmUtil.getCookieId(req)); 
    	
    	// Asset 상세정보 : 죄측 상단 및 상세
    	DataMap cmmAmsAssetsDetail = cmmService.selectCmmAmsAssetsDetail(paramMap);
    	model.addAttribute("cmmAmsAssetsDetail", cmmAmsAssetsDetail);
    	
    	// 다른문화원 소장자료 목록 정보를 가져오기 위한  맵핑
    	paramMap.setString("sojangCouncil", cmmAmsAssetsDetail.getString("sojangCouncil")); // 소장문화원
    	
    	// AssetMedia 그룹 목록 : 좌측 목록 Cnt
    	List<DataMap> cmmAmsAssetsMediaGroupListCnt = cmmService.selectCmmAmsAssetsMediaGroupListCnt(paramMap);
    	model.addAttribute("cmmAmsAssetsMediaGroupListCnt", cmmAmsAssetsMediaGroupListCnt);
    	
    	// AssetMedia 그룹 목록 : 좌측 목록
    	List<DataMap> cmmAmsAssetsMediaGroupList = cmmService.selectCmmAmsAssetsMediaGroupList(paramMap);
    	model.addAttribute("cmmAmsAssetsMediaGroupList", cmmAmsAssetsMediaGroupList);
    	
		/**** 연속자료 paging ****/
       	PaginationInfo paginationInfo = new PaginationInfo();
   		paginationInfo.setCurrentPageNo(cmmVO.getPageIndex());
   		paginationInfo.setRecordCountPerPage(cmmVO.getPageUnit());
   		paginationInfo.setPageSize((CmmUtil.isMobile(req)) ? cmmVO.getMobilePageSize() : cmmVO.getPageSize());
   		
   		cmmVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
   		cmmVO.setLastIndex(paginationInfo.getLastRecordIndex());
   		cmmVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
   		/**** 연속자료 paging ****/
    	
   		int totCnt = 0;
   		DataMap cmmAmsAssetsMediaDetail = null;
   		List<DataMap> cmmAmsAssetsContinueList = null;
   		List<DataMap> tagsListResult = null;
   		
   		// 화면에서 mId 값 넘어오면(지역문화Pick 유형별 목록) 넘어온 값 사용하도록 수정 (2019.10.16)
   		String mediaId = paramMap.getString("mId");
   		if (StringUtils.isEmpty(mediaId)) {
   			// 화면에서 mId 값 넘어오지 않는 경우 (지역문화Pick 지역별 목록)
   			if(cmmAmsAssetsMediaGroupList != null && cmmAmsAssetsMediaGroupList.size()>0) {
   				mediaId = cmmAmsAssetsMediaGroupList.get(0).getString("id"); // 0번째의 미디어 아이디
   			}
   		}
   		LOGGER.info("selectCmmAmsAssetsPick() mediaId={}", mediaId);
   		
    	if(StringUtils.isNotEmpty(mediaId)){
    		// 미디어 ID 맵핑
    		if (StringUtils.isEmpty(paramMap.getString("mId"))) paramMap.setString("mId", mediaId);
    		cmmVO.setmId(paramMap.getString("mId"));
    		
    		// 에셋 미디어 상세정보(원문보기 쪽 상세정보)
        	cmmAmsAssetsMediaDetail = cmmService.selectCmmAmsAssetsMediaDetail(paramMap);
        	
        	/* 목차 정보가 많을 경우 select box에 표시하기 어려움 - 뷰어 띄울 때 목차 표시하도록 변경할 예정
        	// 문서 목차정보 파싱
        	List<CmmAmsDocTableOfContentsVO> tableOfContentsList = CmmUtil.parseTableOfContents(cmmAmsAssetsMediaDetail.getString("tableOfContents"));
        	cmmAmsAssetsMediaDetail.put("tableOfContentsList", tableOfContentsList);
        	*/
        	
        	// 연관태그목록
        	tagsListResult = cmmService.selectCmmAmsAssetsTagsList(paramMap);
    		model.addAttribute("cmmAmsAssetsTagsList", tagsListResult);
        	
    		// 연속자료 총 수
    		totCnt = cmmService.selectCmmAmsAssetsContinueListTotCnt(cmmVO); 
    		// 연속자료 목록
    		cmmAmsAssetsContinueList = cmmService.selectCmmAmsAssetsContinueList(cmmVO);
    	}
    	// 상세정보
    	model.addAttribute("cmmAmsAssetsMediaDetail", cmmAmsAssetsMediaDetail); 
    	
    	/* 목차 정보가 많을 경우 select box에 표시하기 어려움 - 뷰어 띄울 때 목차 표시하도록 변경할 예정
    	// 문서 원문보기 OCR 목록 (2019.10.04)
    	if (cmmAmsAssetsMediaDetail != null && cmmAmsAssetsMediaDetail.getInt("ocrSplitNum") > 1) {
    		model.addAttribute("cmmAmsAssetsMediaOcrList", cmmService.selectCmmAmsAssetsMediaOcrList(paramMap)); 
    	}
    	*/
    	
    	// 연속자료  페이징 오브젝트
    	paginationInfo.setTotalRecordCount(totCnt);
    	model.addAttribute("paginationInfo", paginationInfo);
    	model.addAttribute("cmmAmsAssetsContinueList", cmmAmsAssetsContinueList); // 연속자료 목록
    	
    	
    	// 연관 지역문화 이야기
    	List cmsTag = new ArrayList();
		for(int i = 0; i < tagsListResult.size() ; i++){
			cmsTag.add(tagsListResult.get(i).get("tagsName") );
		}
		List<DataMap> themesResult = cmmService.selectCmmAmsAssetsThemesContentsList(cmsTag);	
		model.addAttribute("cmmAmsAssetsThemesContentsList",themesResult);
    	
    	
    	// 문화원의 다른 소장자료 목록
		List<DataMap> diffSojangListResult = cmmService.selectCmmAmsAssetsDiffSojangList(paramMap);
		/* 목차 정보가 많을 경우 select box에 표시하기 어려움 - 뷰어 띄울 때 목차 표시하도록 변경할 예정
		for (int i=0; diffSojangListResult!=null && i<diffSojangListResult.size(); i++) {
			DataMap diffSojang = diffSojangListResult.get(i);
        	// 문서 목차정보 파싱
        	List<CmmAmsDocTableOfContentsVO> diffSojangTableOfContentsList = CmmUtil.parseTableOfContents(diffSojang.getString("tableOfContents"));
        	diffSojang.put("tableOfContentsList", diffSojangTableOfContentsList);
			
        	// 문서 원문보기 OCR 목록
        	if (diffSojang.getInt("ocrSplitNum") > 1) {
        		diffSojang.put("mediaOcrList", cmmService.selectCmmAmsAssetsMediaOcrList(paramMap)); 
        	}
//        	LOGGER.info("selectCmmAmsAssetsPick() diffSojangListResult... i={}, diffSojang.get(\"tableOfContentsLis\")=", i, diffSojang.get("tableOfContentsList"));
		}
		*/
    	model.addAttribute("cmmAmsAssetsDiffSojangList", diffSojangListResult);
    	
    	/* 목차 정보가 많을 경우 select box에 표시하기 어려움 - 뷰어 띄울 때 목차 표시하도록 변경할 예정
    	// 문서 목차정보 파싱
    	List<CmmAmsDocTableOfContentsVO> tableOfContentsList = CmmUtil.parseTableOfContents(cmmAmsAssetsMediaDetail.getString("tableOfContents"));
    	cmmAmsAssetsMediaDetail.put("tableOfContentsList", tableOfContentsList);
    	*/
    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(req)); 
    	paramMap.setString("contentId", paramMap.getString("mId")); 
    	paramMap.setString("contentType", Constant.CONTENT_TYPE_A); 
    	cmmService.insertCmmActivityHst(paramMap);
    	
    	model.addAttribute("paramVO", cmmVO); // 파라미터
    	
    	// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
    	// ams nfs 파일 경로
    	CmmUtil.setNfsPathModelMap(req,model);
    	// jsi 값 세팅
    	model.addAttribute("jsi", CmmUtil.getCookieId(req));
    	
    	return "/kccf/cmm/layerAmsAssetsPickAjax";
	}
    //AMS 미디어 목록 상세 레이어(PICK) : Ajax
    @RequestMapping(value="/cmm/cmmAmsAssetsPickDetail.do")
    public String selectCmmAmsAssetsPickDetail(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(req);
    	
    	//paramMap.setString("aId", paramMap.getString("aId")); 
    	//cmmVO.setaId(paramMap.getString("aId"));
    	//paramMap.setString(mId", paramMap.getString("mId")); 
    	//cmmVO.setaId(paramMap.getString("mId"));
    	
    	// 스크랩 여부 키 
    	paramMap.setString("sessionId", CmmUtil.getCookieId(req)); 
    	
    	// Asset 상세정보(죄측 상단 및 상세)
    	DataMap cmmAmsAssetsDetail = cmmService.selectCmmAmsAssetsDetail(paramMap);
    	model.addAttribute("cmmAmsAssetsDetail", cmmAmsAssetsDetail);
    	
    	// 다른문화원 소장자료 목록 정보를 가져오기 위한  맵핑
    	paramMap.setString("sojangCouncil", cmmAmsAssetsDetail.getString("sojangCouncil")); // 소장문화원
    	
    	// 에셋 미디어 상세정보(원문보기 쪽 상세정보)
    	DataMap cmmAmsAssetsMediaDetail = cmmService.selectCmmAmsAssetsMediaDetail(paramMap);
    	model.addAttribute("cmmAmsAssetsMediaDetail", cmmAmsAssetsMediaDetail);
    	
    	/* 목차 정보가 많을 경우 select box에 표시하기 어려움 - 뷰어 띄울 때 목차 표시하도록 변경할 예정
    	// 문서 목차정보 파싱
    	List<CmmAmsDocTableOfContentsVO> tableOfContentsList = CmmUtil.parseTableOfContents(cmmAmsAssetsMediaDetail.getString("tableOfContents"));
    	cmmAmsAssetsMediaDetail.put("tableOfContentsList", tableOfContentsList);

    	// 문서 원문보기 OCR 목록 (2019.10.04)
    	if (cmmAmsAssetsMediaDetail != null && cmmAmsAssetsMediaDetail.getInt("ocrSplitNum") > 1) {
    		model.addAttribute("cmmAmsAssetsMediaOcrList", cmmService.selectCmmAmsAssetsMediaOcrList(paramMap)); 
    	}
    	*/
    	
    	// 연관태그목록
    	List<DataMap> tagsListResult = cmmService.selectCmmAmsAssetsTagsList(paramMap);
		model.addAttribute("cmmAmsAssetsTagsList", tagsListResult);
    	
		/**** 연속자료 paging ****/
       	PaginationInfo paginationInfo = new PaginationInfo();
   		paginationInfo.setCurrentPageNo(cmmVO.getPageIndex());
   		paginationInfo.setRecordCountPerPage(cmmVO.getPageUnit());
   		paginationInfo.setPageSize((CmmUtil.isMobile(req)) ? cmmVO.getMobilePageSize() : cmmVO.getPageSize());
   		
   		cmmVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
   		cmmVO.setLastIndex(paginationInfo.getLastRecordIndex());
   		cmmVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
   		/**** 연속자료 paging ****/
   		
   		// 미디어 ID 맵핑
   		cmmVO.setmId(paramMap.getString("mId"));
		// 연속자료 총 수
   		int totCnt = cmmService.selectCmmAmsAssetsContinueListTotCnt(cmmVO); 
		// 연속자료 목록
   		model.addAttribute("cmmAmsAssetsContinueList", cmmService.selectCmmAmsAssetsContinueList(cmmVO));
    	// 연속자료  페이징 오브젝트
    	paginationInfo.setTotalRecordCount(totCnt);
    	model.addAttribute("paginationInfo", paginationInfo);
    	
    	// 연관 지역문화 이야기
    	List cmsTag = new ArrayList();
		for(int i = 0; i < tagsListResult.size() ; i++){
			cmsTag.add(tagsListResult.get(i).get("tagsName") );
		}
		List<DataMap> themesResult = cmmService.selectCmmAmsAssetsThemesContentsList(cmsTag);	
		model.addAttribute("cmmAmsAssetsThemesContentsList",themesResult);
    	
    	// 문화원의 다른 소장자료 목록
		List<DataMap> diffSojangListResult = cmmService.selectCmmAmsAssetsDiffSojangList(paramMap);
		/* 목차 정보가 많을 경우 select box에 표시하기 어려움 - 뷰어 띄울 때 목차 표시하도록 변경할 예정
		for (int i=0; diffSojangListResult!=null && i<diffSojangListResult.size(); i++) {
			DataMap diffSojang = diffSojangListResult.get(i);
        	// 문서 목차정보 파싱
        	List<CmmAmsDocTableOfContentsVO> diffSojangTableOfContentsList = CmmUtil.parseTableOfContents(diffSojang.getString("tableOfContents"));
        	diffSojang.put("tableOfContentsList", diffSojangTableOfContentsList);
			
        	// 문서 원문보기 OCR 목록
        	if (diffSojang.getInt("ocrSplitNum") > 1) {
        		diffSojang.put("mediaOcrList", cmmService.selectCmmAmsAssetsMediaOcrList(paramMap)); 
        	}
//        	LOGGER.info("selectCmmAmsAssetsPickDetail() diffSojangListResult... i={}, diffSojang.get(\"tableOfContentsLis\")=", i, diffSojang.get("tableOfContentsList"));
		}
		*/
    	model.addAttribute("cmmAmsAssetsDiffSojangList", diffSojangListResult);

    	
    	paramMap.setString("jsessionId", CmmUtil.getCookieId(req)); 
    	paramMap.setString("contentId", paramMap.getString("mId")); 
    	paramMap.setString("contentType", Constant.CONTENT_TYPE_A); 
    	cmmService.insertCmmActivityHst(paramMap);
    	
    	// 관심지역 정보
		model.addAttribute("pscHst", cmmService.selectCmmPscHstDetail(paramMap)); 
		
    	model.addAttribute("paramVO", cmmVO); // 파라미터
    	
    	// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
    	// ams nfs 파일 경로
    	CmmUtil.setNfsPathModelMap(req,model);
    	
    	return "/kccf/cmm/layerAmsAssetsPickDetailAjax";
	}
    //AMS 미디어 목록 상세 레이어(PICK) : 연속자료  목록: Ajax
    @RequestMapping(value="/cmm/cmmAmsAssetsPickContinueList.do")
    public String selectCmmAmsAssetsPickContinueList(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(req);
    	
    	// 스크랩 여부 키 
    	paramMap.setString("sessionId", CmmUtil.getCookieId(req)); 
    	
    	// Asset 상세정보(죄측 상단 및 상세)
    	DataMap cmmAmsAssetsDetail = cmmService.selectCmmAmsAssetsDetail(paramMap);
    	model.addAttribute("cmmAmsAssetsDetail", cmmAmsAssetsDetail);
    	
    	// 에셋 미디어 상세정보(원문보기 쪽 상세정보)
    	DataMap cmmAmsAssetsMediaDetail = cmmService.selectCmmAmsAssetsMediaDetail(paramMap);
    	model.addAttribute("cmmAmsAssetsMediaDetail", cmmAmsAssetsMediaDetail);
    	
    	
		/**** 연속자료 paging ****/
       	PaginationInfo paginationInfo = new PaginationInfo();
   		paginationInfo.setCurrentPageNo(cmmVO.getPageIndex());
   		paginationInfo.setRecordCountPerPage(cmmVO.getPageUnit());
   		paginationInfo.setPageSize((CmmUtil.isMobile(req)) ? cmmVO.getMobilePageSize() : cmmVO.getPageSize());
   		
   		cmmVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
   		cmmVO.setLastIndex(paginationInfo.getLastRecordIndex());
   		cmmVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
   		/**** 연속자료 paging ****/
   		
		// 연속자료 총 수
   		int totCnt = cmmService.selectCmmAmsAssetsContinueListTotCnt(cmmVO); 
		// 연속자료 목록
   		model.addAttribute("cmmAmsAssetsContinueList", cmmService.selectCmmAmsAssetsContinueList(cmmVO));
    	// 연속자료  페이징 오브젝트
    	paginationInfo.setTotalRecordCount(totCnt);
    	model.addAttribute("paginationInfo", paginationInfo);
    	
    	// 관심지역 정보
		model.addAttribute("pscHst", cmmService.selectCmmPscHstDetail(paramMap)); 
    	model.addAttribute("paramVO", cmmVO); // 파라미터
    	
    	// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
    	// ams nfs 파일 경로
    	CmmUtil.setNfsPathModelMap(req,model);
    	
    	return "/kccf/cmm/layerAmsAssetsPickContinueListAjax";
	}
    // 미디어 기준의 목록(레이어 원문보기용)
    @RequestMapping(value="/cmm/cmmAmsAssetsOriginViewList.do")
    public String selectCmmAmsAssetsOriginViewList(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(req);
    	
    	paramMap.setString("aid", paramMap.getString("aId")); 
    	paramMap.setString("mid", paramMap.getString("mId")); 
    	
    	// AssetMedia 목록
    	String rsUrl = "";
    	String assetType = "";
    	if(Constant.M_TYPE_I.equals(paramMap.getString("mType"))){
    		// 이미지
    		rsUrl = "/kccf/cmm/layerImgAjax";
    		assetType = Constant.M_TYPE_ARRAY[0];
    	} else if(Constant.M_TYPE_V.equals(paramMap.getString("mType"))){
    		// 비디오
    		rsUrl = "/kccf/cmm/layerVideoAjax";
    		assetType = Constant.M_TYPE_ARRAY[1];
    	} else if(Constant.M_TYPE_A.equals(paramMap.getString("mType"))){
    		// 오디오
    		rsUrl = "/kccf/cmm/layerAudioAjax";
    		assetType = Constant.M_TYPE_ARRAY[2];
    	}
    	
    	paramMap.setString("assetType", assetType); 
    	model.addAttribute("mType", paramMap.getString("mType"));
    	model.addAttribute("pageIndex", 1);
    	model.addAttribute("lastPageNo", 1);
    	
    	model.addAttribute("cmmOriginViewList", cmmService.selectCmmAmsAssetsOriginViewList(paramMap));
    	// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
    	
    	return rsUrl;
	}
    
    
    @RequestMapping(value="/cmm/cmmAmsAssetsOriginViewList-data.do")
    public String selectCmmAmsAssetsOriginViewListData(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	
    	DataMap paramMap = DataMap.getParamMap(req);
		model.addAttribute("paramVO",cmmVO);
		paramMap.setString("uaType", Constant.UA_TYPE_A);
		paramMap.setString("activityType", Constant.ACTIVITY_TYPE_B);
		// 파라미터 맵핑
  
    	
   
    	paramMap.setString("aid", paramMap.getString("aId")); 
    	paramMap.setString("mid", paramMap.getString("mId")); 
    	
    	// AssetMedia 목록
    	String rsUrl = "";
    	String assetType = "";
    	if(Constant.M_TYPE_I.equals(paramMap.getString("mType"))){
    		// 이미지
    		rsUrl = "/kccf/cmm/layerImgAddAjax";
    		assetType = Constant.M_TYPE_ARRAY[0];
    	} else if(Constant.M_TYPE_V.equals(paramMap.getString("mType"))){
    		// 비디오
    		rsUrl = "/kccf/cmm/layerVideoAddAjax";
    		assetType = Constant.M_TYPE_ARRAY[1];
    	} else if(Constant.M_TYPE_A.equals(paramMap.getString("mType"))){
    		// 오디오
    		rsUrl = "/kccf/cmm/layerVideoAddAjax";
    		assetType = Constant.M_TYPE_ARRAY[2];
    	}
    	

   		
   		paramMap.setString("assetType", assetType); 
    	model.addAttribute("mType", paramMap.getString("mType"));
   		
    	
    	
    	/**** paging ****/
       	PaginationInfo paginationInfo = new PaginationInfo();
   		paginationInfo.setCurrentPageNo(cmmVO.getPageIndex());
   		paginationInfo.setRecordCountPerPage(cmmVO.getPageUnit());
   		paginationInfo.setPageSize(cmmVO.getPageSize());
   		
   		cmmVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
   		cmmVO.setLastIndex(paginationInfo.getLastRecordIndex());
   		cmmVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
   		/**** paging ****/
    	
   		paramMap.setInt("recordCountPerPage", paginationInfo.getRecordCountPerPage()); 
    	paramMap.setInt("firstIndex", paginationInfo.getFirstRecordIndex());
    	paramMap.setInt("lastIndex", paginationInfo.getLastRecordIndex());
   		
   		int totCnt = cmmService.selectCmmAmsAssetsOriginViewListAjaxCnt(paramMap);
   		model.addAttribute("totCnt", totCnt);
   		paginationInfo.setTotalRecordCount(totCnt);
   		model.addAttribute("paginationInfo", paginationInfo);
   		model.addAttribute("lastPageNo", paginationInfo.getLastPageNo());
		
   		
   		
		model.addAttribute("cmmOriginViewList", cmmService.selectCmmAmsAssetsOriginViewListAjax(paramMap));
		
		
		// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
		
   		
		return rsUrl;
	}
    
    
    
    
    
    
    
    
    
    
    
    
    
    // 미디어 기준의 상세(레이어 원문보기용)
    @RequestMapping(value="/cmm/cmmAmsAssetsOriginViewDetail.do")
    public ModelAndView selectCmmAmsAssetsOriginViewDetail(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	LOGGER.info("selectCmmAmsAssetsOriginViewDetail() start... req.getRequestURI()={}, req.getQueryString()={}", req.getRequestURI(), req.getQueryString());
    	
    	DataMap paramMap = DataMap.getParamMap(req);
    	paramMap.setString("mid", paramMap.getString("mId")); 
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	DataMap responseMap = new DataMap();
    	DataMap resultMap = cmmService.selectCmmAmsAssetsOriginViewDetail(paramMap);
    	responseMap.put("result", resultMap);
    	
    	
    	// 미디어 활동이력 (원문보기 이력) 등록 (2019.08.26)
		DataMap hstParamMap = new DataMap();
		hstParamMap.put("jsessionId", CmmUtil.getCookieId(req));
		hstParamMap.put("contentId", paramMap.getString("mId"));
		hstParamMap.put("assetType", resultMap.getString("assetType"));
		hstParamMap.put("linkUrl", req.getRequestURI()+"?"+req.getQueryString());
		hstParamMap.put("uaType", CmmUtil.isMobile(req) ? Constant.UA_TYPE_M : Constant.UA_TYPE_W);
		cmmService.insertCmmActivityMediaHst(hstParamMap);
    	
    	
    	model.addAttribute("responseData", responseMap);
    	return modelAndView;
	}
    
    @RequestMapping(value="/cmm/imageSrc.do")
    public String cmmSmartEditorImageView(HttpServletRequest request, HttpServletResponse response) {
		return "egovframework/cmm/cmmSmartEditorImageView";
    }
	private String getBrowser(HttpServletRequest request) {
		String header = request.getHeader("User-Agent");
		if (header.indexOf("MSIE") > -1) {
			return "MSIE";
		} else if (header.indexOf("Trident") > -1) { // IE11 문자열 깨짐 방지
			return "Trident";
		} else if (header.indexOf("Chrome") > -1) {
			return "Chrome";
		} else if (header.indexOf("Opera") > -1) {
			return "Opera";
		}
		return "Firefox";
	}
	private void setDisposition(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String browser = getBrowser(request);

		String dispositionPrefix = "attachment; filename=";
		String encodedFilename = null;

		if (browser.equals("MSIE")) {
			encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
		} else if (browser.equals("Trident")) { // IE11 문자열 깨짐 방지
			encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
		} else if (browser.equals("Firefox")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		} else if (browser.equals("Opera")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		} else if (browser.equals("Chrome")) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < filename.length(); i++) {
				char c = filename.charAt(i);
				if (c > '~') {
					sb.append(URLEncoder.encode("" + c, "UTF-8"));
				} else {
					sb.append(c);
				}
			}
			encodedFilename = sb.toString();
		} else {
			throw new IOException("Not supported browser");
		}

		response.setHeader("Content-Disposition", dispositionPrefix + encodedFilename);

		if ("Opera".equals(browser)) {
			response.setContentType("application/octet-stream;charset=UTF-8");
		}
	}
    /**
     * response Cache
     * @param response
     */
    @SuppressWarnings("unused")
	private void setResponseCacheControl(HttpServletResponse response){
    	response.setContentType("text/html; charset=utf-8");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "no-cahce");
		response.setHeader("Cache-Control", "no-store"); // HTTP 1.0
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    }
    
	/**
     * PDF 호출 - [RIS] 파일에 표시되는 URL (viewer에 관계없이 변하지 않는 URL 제공위해 생성)
     * ex) /npdfView.do?npdf=R10692
     * 
     * npdf="미디어ID"				(사용여부, 원문공개여부 모두 Y가 아니면 404 페이지)
     * npdf="R+미디어인터페이스ID" 	(사용여부, 원문공개여부 모두 Y가 아니면 404 페이지)
     * npdf="I+미디어인터페이스ID"	(사용여부, 원문공개여부 모두 Y가 아니면 404 페이지)
     * npdf="A+미디어인터페이스ID" 	(사용여부, 원문공개여부 관계없이 항상 뷰어 띄움)
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value="/npdfView.do")
    public String nPdfView(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
    	DataMap paramMap = DataMap.getParamMap(request);
    	String npdf = paramMap.getString("npdf"); // "R" + interfaceId
    	String pNumber  = paramMap.getString("pn"); 
    	if (StringUtils.isEmpty(npdf)) {
    		LOGGER.error("nPdfView() npdf is empty...");
    		return "/code404.jsp";
    	}
    	
    	String rfType = ""; // RIS일 경우 "R" (Constant.UA_TYPE_R)
    	String contentId = ""; // asset media id
    	if (npdf.startsWith(Constant.UA_TYPE_R) || npdf.startsWith("I") || npdf.startsWith("A")) { // npdf="R+인터페이스ID", npdf="I+인터페이스ID", npdf="A+인터페이스ID" 
    		if (npdf.startsWith(Constant.UA_TYPE_R)) rfType = Constant.UA_TYPE_R;
    		
    		if (npdf.length() > 1) {
    			// interface_id 로 media_id 구하기
				DataMap mediaParamMap = new DataMap();
				mediaParamMap.put("interfaceId", npdf.substring(1));
				DataMap mediaMap = cmmService.selectCmmAmsAssetsMediaDetailByInterfaceId(mediaParamMap);
				if (mediaMap != null) contentId = mediaMap.getString("id");
    		}	
    	} else { // mediaId만 넘긴 경우 (npdf="미디어ID")
    		contentId = npdf;
    	}
    	LOGGER.info("nPdfView() contentId={}, rfType={}", contentId, rfType);
    	
    	// searchData index (분할파일일 경우 default로 띄울 분할파일 index 값 (1부터 시작하는 값))
    	//int sdIdx = paramMap.getInt("sd"); xss 때문에 아래처럼 수정 
    	
    	String sd = CmmUtil.clearXSS(paramMap.getString("sd"));	// XSS 방지
    	if(sd == "") sd = "0";
    	int sdIdx = Integer.parseInt(sd);
    	
    	if (sdIdx == 0) sdIdx += 1;
    	LOGGER.info("nPdfView() sdIdx={}", sdIdx);

    	String assetType = "";
//    	String encData = "";	// 원본파일 사용할 경우 
    	String path = "";		// 분할파일 사용할 경우
    	String title = "";		// 분할파일 사용할 경우
    	String searchData = "";	// 분할파일 사용할 경우 (분할파알 중 default로 선택될 파일명)
    	String orginTitle = "";
    	String ogData = "";
    	
    	if (StringUtils.isNotEmpty(contentId)) {
    		String jsessionId = CmmUtil.getCookieId(request);
    		
    		// media 단건조회
			DataMap mediaParamMap = new DataMap();
			mediaParamMap.put("mId", contentId);
			mediaParamMap.put("sessionId", jsessionId);
			if (npdf.startsWith("A")){
				mediaParamMap.put("allView", "Y");
			}
			DataMap mediaMap = cmmService.selectCmmAmsAssetsMediaDetail(mediaParamMap);
			orginTitle = mediaMap.getString("title");
			ogData = mediaMap.getString("title")+"||";
			ogData = ogData + CmmUtil.getPropertyStr(Constant.KCCF_HOME_KEY)+request.getRequestURI()+"?"+request.getQueryString()+"||";
			
			if (StringUtils.isNotEmpty(mediaMap.getString("mainImg"))){
				ogData = ogData + CmmUtil.getAssetImageUrl(mediaMap.getString("mainImg"))+"||";
			}else{
				ogData = ogData + "||";
			}
			ogData = ogData + mediaMap.getString("sojangCouncilNm");
			
			if (mediaMap != null) {
				if ("N".equals(mediaMap.getString("useAt")) || "N".equals(mediaMap.getString("orgOpenAt"))) {
		    		LOGGER.error("nPdfView() USE_AT=N or ORG_OPEN_AT=N ... npdf={}, mediaParamMap={}", npdf, mediaParamMap);
		    		if (!npdf.startsWith("A")) return "/code404.jsp"; // npdf="A***" 형식일 때는 사용여부/원문공개여부 상관없이 항상 띄움
				}
				assetType = mediaMap.getString("assetType");

        		String pdfViewerDelimiter = "||"; // pdf뷰어에서 사용하는 delimiter
        		String amsNasPath = CmmUtil.getPropertyStr(Constant.NFS_NAS_KEY);
        		
            	// 분할파일 정보 조회
            	List<DataMap> ocrList = cmmService.selectCmmAmsAssetsMediaOcrList(mediaParamMap);
            	if (ocrList == null || ocrList.size() == 0) {
            		String streFileName = mediaMap.getString("streFileName");
            		String filePath = CmmUtil.getPropertyStr(Constant.NFS_NAS_KEY)+CmmUtil.getPropertyStr(Constant.NFS_DOC_KEY);
            		if (streFileName.contains("/")) filePath = CmmUtil.getPropertyStr(Constant.NFS_NAS_KEY);
            		if (streFileName.startsWith(CmmUtil.getPropertyStr("ams.nas.root.path"))) filePath = ""; // ex) /nfs_nas/minio/amsweb-opt/pdf/***.pdf 

            		path += filePath + streFileName;
            		/*
            		// 암호화 문자열 생성 - 기존방식 (원본파일 하나 호출)
            		encData = FunctionTag.unidocsViewer(filePath, streFileName);
            		*/
            		
        	    	// 2019.12.27 수정작업 이후 - customLayout.jsp 사용하려면 반드시 searchData 값 존재해야 함
            		searchData = FilenameUtils.getName(path); // 경로 제외한 파일명만
            		
            	} else {
            		// sdIdx 값이 ocrList 크기를 벗어날 경우 첫번째 분할 파일 default로 보여주기
            		if (sdIdx > ocrList.size()) sdIdx = 1;
            		
	            	for (int i=0; i<ocrList.size(); i++) {
	            		DataMap ocr = ocrList.get(i);
	            		String fileName = ocr.getString("fileName");
	            		if (i > 0) path += pdfViewerDelimiter;
	            		if (fileName.startsWith(CmmUtil.getPropertyStr("ams.nas.root.path"))) path += fileName; // ex) /nfs_nas/minio/amsweb-opt/pdf/***.pdf
	            		else path += amsNasPath + fileName; // ex) 248/15/5064_divide1-1.pdf
	            		
	            		
	            		if (i == (sdIdx-1)) {
	            			searchData = fileName;
	            			searchData = FilenameUtils.getName(path); // 경로 제외한 파일명만
	            		}
	            	}
	            	pNumber = "1"; //분할파일은 1페이지 부터 무조건 시작
            	}
            	LOGGER.info("nPdfView() path={}", path);
            	LOGGER.info("nPdfView() searchData={}", searchData);

            	// 문서 목차정보 파싱
            	List<CmmAmsDocTableOfContentsVO> tableOfContentsList = CmmUtil.parseTableOfContents(mediaMap.getString("tableOfContents"));
            	title = CmmUtil.makeTableOfContentsMarkup(tableOfContentsList, pdfViewerDelimiter);
            	LOGGER.info("nPdfView() title={}", title);

            	/*
            	// 암호화 문자열 생성
        	    // PDFPath, downloadYn(true/false), printYn(true/false)
        		String download = "true";
        		String print = "true";
        		String annotation = "false";
        		String[] param = new String[]{ java.net.URLEncoder.encode( path, "UTF-8" ), java.net.URLEncoder.encode( title, "UTF-8" ), download, print, annotation};
        		encData = PDFInfoEncrypter.encrypt( param );
        		LOGGER.info("nPdfView() encData={}", encData);
        		*/
			}
    		
        	// 미디어 활동이력 (원문보기 이력) 등록
    		DataMap hstParamMap = new DataMap();
    		hstParamMap.put("jsessionId", jsessionId);
    		hstParamMap.put("contentId", contentId);
    		hstParamMap.put("assetType", assetType);
    		hstParamMap.put("linkUrl", request.getRequestURI()+"?"+request.getQueryString());
    		String uaType = rfType; // rfType 값이 넘어온 경우 그대로 사용
    		if (StringUtils.isEmpty(uaType)) {
    			if (CmmUtil.isMobile(request)) uaType = Constant.UA_TYPE_M;
    			else uaType = Constant.UA_TYPE_W;
    		}
    		hstParamMap.put("uaType",  uaType);
    		cmmService.insertCmmActivityMediaHst(hstParamMap);
    	}
    	
    	/*if (StringUtils.isNotEmpty(encData)) { // 원본파일 열 경우 - 기존방식 사용
	    	String pdfPath = CmmUtil.getPropertyStr(Constant.PDF_VIEW_KEY);
	    	return "redirect:"+pdfPath + "/customLayoutBasic.jsp?encdata="+encData;
	    	
    	} else */ if (StringUtils.isNotEmpty(path)) { // prepareCustomLayout.jsp 에서 암호화 후 POST 전송 (직접 redirect 하면 "Request-URI Too Long" 에러 발생
    		// 목차 + 분할파일 열 경우 및 원본파일 일 경우 모두 신규방식 사용 (2019.12.27) 
	    	request.setAttribute("path", path);
	    	request.setAttribute("title", title);
	    	request.setAttribute("searchData", searchData);
	    	request.setAttribute("orginTitle", orginTitle);
	    	request.setAttribute("ogData", ogData);
	    	request.setAttribute("pNumber", pNumber);
	    	
	    	return "kccf/cmm/prepareCustomLayout";
    	} else {
    		LOGGER.error("nPdfView() encData, path empty... npdf={}", npdf);
    		return "/code404.jsp";
    	}
    }
    
	/**
     * 테스트용 PDF 호출
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value="/cmm/pdfView.do")
    public String cmmPdfView(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	DataMap paramMap = DataMap.getParamMap(request);
    	String fileNm = paramMap.getString("fileNm");
    	model.addAttribute("fileNm", fileNm);
    	return "/kccf/cmm/pdfTestView";
    }
    /**
     * 테스트용 vod 호출 (ams에서 동영상 확인위해 사용한다고 함)
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value="/cmm/vodView.do")
    public String cmmVodView(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	// 동영상파일명
    	String fileNm = paramMap.getString("fileNm");
    	model.addAttribute("fileNm", fileNm);

    	// 자막파일명
    	String sFileNm = paramMap.getString("sFileNm");
    	model.addAttribute("sFileNm", sFileNm);
    	
    	return "/kccf/cmm/vodTestView";
    }
    

    
    /**
     * 테스트용 audio 호출
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value="/cmm/audioView.do")
    public String cmmAudioView(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    	DataMap paramMap = DataMap.getParamMap(request);
    	String fileNm = paramMap.getString("fileNm");
		String fileNmOri = paramMap.getString("fileNmOri");
    	model.addAttribute("fileNm", fileNm);
		model.addAttribute("fileNmOri", fileNmOri);
    	return "/kccf/cmm/audioTestView";
    }
    
    // 미디어 활동이력 (원문보기 이력) 등록 (2019.08.26)
    @RequestMapping(value="/cmm/regCmmMediaHst.do")
    public ModelAndView insertCmmActivityMediaHst(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	LOGGER.info("insertCmmActivityMediaHst() start... req.getRequestURI()={}, req.getQueryString()={}", req.getRequestURI(), req.getQueryString());
    	
    	DataMap paramMap = DataMap.getParamMap(req);
    	paramMap.setString("mid", paramMap.getString("mId")); 
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	DataMap responseMap = new DataMap();
    	DataMap resultMap = cmmService.selectCmmAmsAssetsOriginViewDetail(paramMap);
    	responseMap.put("result", resultMap);
    	
    	
    	// 미디어 활동이력 (원문보기 이력) 등록 (2019.08.26)
		DataMap hstParamMap = new DataMap();
		hstParamMap.put("jsessionId", CmmUtil.getCookieId(req));
		hstParamMap.put("contentId", paramMap.getString("mId"));
		hstParamMap.put("assetType", resultMap.getString("assetType"));
		hstParamMap.put("linkUrl", req.getRequestURI()+"?"+req.getQueryString());
		hstParamMap.put("uaType", CmmUtil.isMobile(req) ? Constant.UA_TYPE_M : Constant.UA_TYPE_W);
		cmmService.insertCmmActivityMediaHst(hstParamMap);
    	
    	
    	model.addAttribute("responseData", hstParamMap);
    	return modelAndView;
	}
    
    /**
     * [상세검색] 레이어 - 지역문화원 정보
     * @param cmmVO
     * @param model
     * @param commandMap
     * @param req
     * @param res
     * @return
     * @throws Exception 
     */
    @RequestMapping(value="/cmm/cmmSearchLayerCouncilInfo-data.do")
    public String selectCmmSearchLayerCouncilInfoAjax(
    		 @ModelAttribute("searchVO") SearchVO searchVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws Exception {
    	DataMap paramMap = DataMap.getParamMap(req);
    	LOGGER.info("selectCmmCouncilInfoListAjax() paramMap={}, searchVO={}", paramMap, searchVO);
    	
    	ComDefaultCodeVO CodeVO = new ComDefaultCodeVO();
        CodeVO.setCodeId(Constant.CODE_ID_FMS018);
        model.addAttribute("couSidoList", cmmUseService.selectCmmCodeDetail(CodeVO));
        
    	List<DataMap> councilList = resourcesService.selectCouncilList();    	
    	model.addAttribute("councilList", councilList);
    	
    	model.addAttribute("searchVO", searchVO);
    	
    	return "kccf/cmm/searchLayerCouncilAjax";
	}
    
    
    
    @RequestMapping(value="/cmm/risDownloadFile.do")
	public void risFileDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {

    	DataMap paramMap = DataMap.getParamMap(request);
    	LOGGER.info("risFileDownload() paramMap={}", paramMap);
    	DataMap media = cmmService.selectCmmAmsAssetsMediaDetail2(paramMap); // asset id로 조회
    	String mediaId = media.getString("mediaId");
    	String mediaInterfaceId = media.getString("mediaInterfaceId");
    	
    	List<DataMap> tagsList = null;
    	tagsList = cmmService.selectCmmAmsAssetsTagKeyList(paramMap);
    	
    	StringBuffer msb = new StringBuffer();
    	msb.append("TY - BOOK\n");
    	if(media.get("title") != null){ msb.append("TI - " + media.get("title").toString() + "\n");} //제목
    	
    	if(media.get("author") != null){ msb.append("AU - " + media.get("author").toString() + "\n");} //저자
    	
    	if(media.get("summary") != null){ //요약
    		msb.append("AB - " + media.get("summary").toString() + "\n");
    	}else{
    		msb.append("AB - 한국문화원연합회 지역문화 포털에서 제공하는 지방문화원 소장자료 입니다.\n");
    	}
    	
    	if(media.get("mgntNo") != null){ msb.append("CN - " + media.get("mgntNo").toString() + "\n");} //도서번호
    	
    	if(media.get("genyear") != null){ msb.append("DA - " + media.get("genyear").toString() + "\n");} //발행일자
    	
    	if(media.get("genyear") != null){ msb.append("PY - " + media.get("genyear").toString() + "\n");} //발행년도
    	
    	if(media.get("totalPage") != null){ msb.append("SP - " + media.get("totalPage").toString() + "\n");} //총페이지수
    	
    	msb.append("LA - Korean\n"); //언어
    	
    	if(media.get("copyright") != null){ msb.append("PB - " + media.get("copyright").toString() + "\n");} //출판사
    	
    	if (StringUtils.isNotEmpty(mediaInterfaceId)) { // mediaInterfaceId가 존재할 경우만 URL 정보 생성
	    	if(media.get("assetType") != null){
	    		if(media.get("assetType").toString().equals("문서") ){

	    			String url = CmmUtil.getPropertyStr(Constant.KCCF_HOME_KEY)+"/npdfView.do?";
	        		url += "npdf="+Constant.UA_TYPE_R+mediaInterfaceId; // MEDIA 의 INTERFACE_ID 사용
	        		
	        		if(media.get("orgOpenAt").toString().equals("Y")){ //원문공개여부
	        			msb.append("UR - "+url+"\n");
	        		}
	        		
	    		}else if(media.get("assetType").toString().equals("링크")){
	    			msb.append("UR - " + media.get("linkData").toString() + "\n");
	    		}else{
	    			String url = CmmUtil.getPropertyStr(Constant.KCCF_HOME_KEY)+"/lib/libraryDetail.do?contentId="+mediaId;
	        		url += "&rfType="+Constant.UA_TYPE_R; // 히스토리 등록 시 사용
	    			msb.append("UR - " + url + "\n");
	    		}
	    	}
    	}
    	
    	if(media.get("source") != null){ msb.append("DB - " + media.get("source").toString() + "\n");} //아카이브
    	
    	for(int i = 0; i < tagsList.size() ; i++){
			if(tagsList.get(i).get("tagName").toString() != "-"){ msb.append("KW - " + tagsList.get(i).get("tagName").toString() + "\n");} //키워드
		}
    	
    	if(media.get("subtitle") != null){ msb.append("T2 - " + media.get("subtitle").toString() + "\n");} //부제목
    	
    	msb.append("ER - ");
		
		byte[] content = msb.toString().getBytes();
        
        String fileName = media.get("title").toString() + ".ris";
        //FileOutputStream fos = null;
        BufferedOutputStream outs = null;
        try
        {
			String orglFileNm = new String(fileName.getBytes("euc-kr"), "iso-8859-1");
			response.setHeader("Content-Disposition", "attachment; filename=\""+ orglFileNm +"\"");
            outs = new BufferedOutputStream(response.getOutputStream());
            outs.write(content);
            outs.close();
        }
        catch (IOException e){
            LOGGER.error("fail in risFileDownload()", e);
        } catch (Exception e){
            LOGGER.error("fail in risFileDownload()", e);
        }
        
        response.getOutputStream().flush();
        response.getOutputStream().close();

	}
    
    @RequestMapping(value="/cmm/cmmWebzineSubScribe.do")
    public String selectCmmWebzineCnfirm(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");

    	String successYn = "N";
    	int cnt = 0;
    	try {
    		cnt = cmmService.selectCmmWebzineCnfirm(paramMap);
    		if(cnt < 1){
    			cmmService.insertCmmWebzineSubScribe(paramMap);
    			successYn = "Y";
    		}else{
    			successYn = "F";
    		}
    		
		} catch (EgovBizException e) {
			LOGGER.error("Error in selectCmmWebzineCnfirm()", e);
		}
    	model.addAttribute("successYn", successYn);
    	return "/kccf/cmm/webzineMessage";
    }
    
    @RequestMapping(value="/cmm/nvodView.do")
    public String cmmNvodView(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(request);
    	String nvod = paramMap.getString("nvod");
    	
    	String rfType = ""; // RIS일 경우 "R" (Constant.UA_TYPE_R)
    	String contentId = ""; // asset media id    	
    	String assetType = "";
    	String fileNm = "";
    	String sFileNm = "";
    	String mainImg = "";
    	if (nvod.startsWith("Z")) { // nvod="Z+인터페이스ID" (웹진)
    		if (nvod.length() > 1) {
    			// interface_id 로 media_id 구하기
				DataMap mediaParamMap = new DataMap();
				mediaParamMap.put("interfaceId", nvod.substring(1));
				mediaParamMap.put("useAt", "Y");
				DataMap mediaMap = cmmService.selectCmmAmsAssetsMediaDetailByInterfaceId(mediaParamMap);
				if (mediaMap != null){
					contentId = mediaMap.getString("id");
					assetType = mediaMap.getString("assetType");
				}
				
				// 동영상파일명
		    	fileNm = mediaMap.getString("streFileName");
		    	model.addAttribute("fileNm", fileNm);
		    	// 자막파일명
		    	sFileNm = mediaMap.getString("subtitleStreFileName");
		    	model.addAttribute("sFileNm", sFileNm);
		    	// 자막파일명
		    	mainImg = mediaMap.getString("mainImg");
		    	model.addAttribute("mainImg", mainImg);
		    	
		    	model.addAttribute("mediaMap", mediaMap);
    		}
    		
    	}
    	
    	if (StringUtils.isNotEmpty(contentId)) {
    		String jsessionId = CmmUtil.getCookieId(request);
    		// 미디어 활동이력 (원문보기 이력) 등록
    		DataMap hstParamMap = new DataMap();
    		hstParamMap.put("jsessionId", jsessionId);
    		hstParamMap.put("contentId", contentId);
    		hstParamMap.put("assetType", assetType);
    		hstParamMap.put("linkUrl", request.getRequestURI()+"?"+request.getQueryString());
    		String uaType = rfType; // rfType 값이 넘어온 경우 그대로 사용
    		if (StringUtils.isEmpty(uaType)) {
    			if (CmmUtil.isMobile(request)) uaType = Constant.UA_TYPE_M;
    			else uaType = Constant.UA_TYPE_W;
    		}
    		hstParamMap.put("uaType",  uaType);
    		cmmService.insertCmmActivityMediaHst(hstParamMap);
    	}

    	return "/kccf/cmm/vodView";
    }
    
    // 미디어 기준의 목록(레이어 원문보기용)
    @RequestMapping(value="/cmm/cmmNvodViewLayer.do")
    public String cmmNvodViewLayer(
    		@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
    		) throws EgovBizException {
    	DataMap paramMap = DataMap.getParamMap(req);
    	
    	paramMap.setString("aid", paramMap.getString("aId")); 
    	paramMap.setString("mid", paramMap.getString("mId")); 
    	
    	// AssetMedia 목록
    	String rsUrl = "";
    	String assetType = "";
    	
    	// 비디오
    	rsUrl = "/kccf/cmm/layerNvodViewAjax";
    	assetType = Constant.M_TYPE_ARRAY[1];
    	
    	paramMap.setString("assetType", assetType); 
    	model.addAttribute("mType", paramMap.getString("mType"));
    	model.addAttribute("pageIndex", 1);
    	model.addAttribute("lastPageNo", 1);
    	
    	model.addAttribute("cmmOriginViewList", cmmService.selectCmmAmsAssetsOriginViewList(paramMap));
    	// ams 서버 패스 정보
    	CmmUtil.setAmsPathModelMap(req,model);
    	
    	return rsUrl;
	}
    
    
    /**
     * YOURLS의 API를 통해서 단축URL 가져오기 
     * @param cmmVO
     * @param model
     * @param commandMap
     * @param req
     * @param res
     * @return
     * @throws EgovBizException
     */
    @RequestMapping(value="/cmm/shorturl-data.do")
   	public ModelAndView shorturl (
   			@ModelAttribute("cmmVO") CmmVO cmmVO
   			, ModelMap model
   			, HttpServletRequest req
			, HttpServletResponse res
   			) throws EgovBizException  {
    	String returnUrl = "";
    	DataMap paramMap = DataMap.getParamMap(req);
    	try {
    		String originUrl = URLEncoder.encode(paramMap.getString("url"), "UTF-8");
			URL url = new URL( propertiesService.getString("shorturl.api") + "&action=shorturl&format=xml&title=nculture&url=" + originUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
			con.setRequestMethod("GET");
			//con.setRequestProperty("Authorization", header);
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if(responseCode==200) { // 정상 호출
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {  // 에러 발생
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
						
			String str = response.toString();
			Pattern pattern = Pattern.compile("<shorturl>(.+?)</shorturl>");
			Matcher matcher = pattern.matcher(str);
			while (matcher.find()) {
			    //System.out.println(matcher.group(1));
				returnUrl = matcher.group(1);  		    
			    if(matcher.group(1) ==  null){
			    	break;
			    }
			}
		} catch (Exception e) {
			System.err.println(e.toString());
		}
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	model.addAttribute("responseData", returnUrl);
    	return modelAndView;
   	}
    
    @RequestMapping(value="/cmm/cmmAssetSecondCategory.do")
    public ModelAndView selectCmmAssetSecondCategoryList(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	DataMap paramMap = DataMap.getParamMap(request);
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	ComDefaultCodeVO CodeVO = new ComDefaultCodeVO();
    	CodeVO.setCodeId(Constant.CODE_ID_FMS015);
		CodeVO.setCode(paramMap.getString("code"));
		
		// DDDDDDDDDDDDDDDDDDDDD cmmUseService.selectCmmCodeDetail2 부재로 임시 막음 (2021.08.13) 
    	// model.addAttribute("resultList", cmmUseService.selectCmmCodeDetail2(CodeVO));
		
    	
    	return modelAndView;
    }
    
    @RequestMapping(value="/cmm/tableOfContentsView.do")
   	public String selectLocalCultureListAjax (
   		  @ModelAttribute("cmmVO") CmmVO cmmVO
 			, ModelMap model
			, @RequestParam Map<String, Object> commandMap
			, HttpServletRequest req
			, HttpServletResponse res
   			) throws Exception  {
    	
    	DataMap paramMap = DataMap.getParamMap(req);
    	
    	DataMap cmmAmsAssetsMediaDetail = null;
    	String mediaId = paramMap.getString("mId");
    	if(StringUtils.isNotEmpty(mediaId)){
    		// 미디어 ID 맵핑
    		if (StringUtils.isEmpty(paramMap.getString("mId"))) paramMap.setString("mId", mediaId);
    		
    		// 에셋 미디어 상세정보(원문보기 쪽 상세정보)
        	cmmAmsAssetsMediaDetail = cmmService.selectCmmAmsAssetsMediaDetail(paramMap);
        	List<CmmAmsDocTableOfContentsVO> tableOfContentsList = CmmUtil.parseTableOfContents(cmmAmsAssetsMediaDetail.getString("tableOfContents"));
        	cmmAmsAssetsMediaDetail.put("tableOfContentsList", tableOfContentsList);
        	
        	if (cmmAmsAssetsMediaDetail.getInt("ocrSplitNum") > 1) {
        		cmmAmsAssetsMediaDetail.put("mediaOcrList", cmmService.selectCmmAmsAssetsMediaOcrList(paramMap)); 
        	}
    	}
    	
    	// 상세정보
    	model.addAttribute("cmmAmsAssetsMediaDetail", cmmAmsAssetsMediaDetail); 
    	
		paramMap.setString("jsessionId", CmmUtil.getCookieId(req)); 
		CmmUtil.setAmsPathModelMap(req,model);
		
   		return "/kccf/cmm/layerTableOfContentsAjax";
   	}
    
}
