package cmm.service.impl;


import java.util.List;
import java.util.StringTokenizer;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;

import cmm.Constant;
import cmm.service.CmmService;
import cmm.util.CmmUtil;
import cmm.util.CmmVO;
import cmm.util.DataMap;
import cmm.util.DateUtil;
import egovframework.com.cmm.service.impl.CmmUseDAO;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.cmmn.exception.FdlException;
import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.fdl.property.EgovPropertyService;

/**  
 * 공통 서비스 클래스를 구현한다.
 * @Class Name : CmmServiceImpl.java
 * @author ecplaza 
 * @since 2018-04-18
 * @version 1.0
 */
@Service("cmmService")
public class CmmServiceImpl extends EgovAbstractServiceImpl implements CmmService {

	/** LOGGER */
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(CmmServiceImpl.class);
	
	  /** EgovPropertyService */
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;
    
    /** cmmDAO */
    @Resource(name="cmmDAO")
    private CmmDAO cmmDAO;
    
    /** cmmUseDAO */
    @Resource(name="cmmUseDAO")
    private CmmUseDAO cmmUseDAO;
    
//    /** egovSchedulerHstIdGnrService */
//    @Resource(name = "egovSchedulerHstIdGnrService")
//    private EgovIdGnrService schedulerHstIdGnrService;
    
    @Override
	public List<DataMap> selectCmmActivityHstAllListTotCnt(DataMap paramMap) throws EgovBizException{
		return (List<DataMap>)cmmDAO.selectCmmActivityHstAllListTotCnt(paramMap);
	}
    @Override
	public int selectSatisfactionTotCnt(DataMap paramMap) throws EgovBizException{
		return (Integer)cmmDAO.selectSatisfactionTotCnt(paramMap);
	}
    @Override
	public int selectCmmPscHstTotCnt(DataMap paramMap) throws EgovBizException{
		return (Integer)cmmDAO.selectCmmPscHstTotCnt(paramMap);
	}
    @Override
	public DataMap selectCmmPscHstDetail(DataMap paramMap) throws EgovBizException{
		return cmmDAO.selectCmmPscHstDetail(paramMap);
	}
    @Override
	public DataMap selectCmmPmsPostRandom(DataMap paramMap) throws EgovBizException{
		if(StringUtils.isBlank(paramMap.getString("today"))){
			paramMap.setString("today", DateUtil.getNowString(DateUtil.DATE_DB_FORMAT));
		}
		return cmmDAO.selectCmmPmsPostRandom(paramMap);
	}
    /**
	 * 에셋 상세정보
	 * pick 레이어 사용(좌측 상단)
     */
    @Override
	public DataMap selectCmmAmsAssetsDetail(DataMap paramMap) throws EgovBizException {
		return cmmDAO.selectCmmAmsAssetsDetail(paramMap);
	}
    
    /**
 	 * 에셋 미디어 그룹 목록
	 * pick 레이어 사용(좌측 목록) 
     */
    @Override
   	public List<DataMap> selectCmmAmsAssetsMediaGroupListCnt(DataMap paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsMediaGroupListCnt(paramMap);
   	}
    /**
 	 * 에셋 미디어 그룹 목록
	 * pick 레이어 사용(좌측 목록) 
     */
    @Override
   	public List<DataMap> selectCmmAmsAssetsMediaGroupList(DataMap paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsMediaGroupList(paramMap);
   	}
    @Override
	public List<DataMap> selectCmmAmsAssetsMediaList(DataMap paramMap) throws EgovBizException {
		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsMediaList(paramMap);
	}
    /**
     * 에셋 미디어 상세정보
	 * pick 레이어 사용(완문보기  상세정보)  
     */
    @Override
   	public DataMap selectCmmAmsAssetsMediaDetail(DataMap paramMap) throws EgovBizException{
   		return cmmDAO.selectCmmAmsAssetsMediaDetail(paramMap);
   	}
    /**
     * 에셋 미디어 상세정보 (미디어의 INTERFACE_ID 값으로 조회)
	 * pick 레이어 사용(완문보기  상세정보)  
     */
    @Override
   	public DataMap selectCmmAmsAssetsMediaDetailByInterfaceId(DataMap paramMap) throws EgovBizException{
   		return cmmDAO.selectCmmAmsAssetsMediaDetailByInterfaceId(paramMap);
   	}
    /**
     * 에셋 미디어 OCR 목록
     * pick 레이어 사용(문서 완문보기)
     */
    @Override
   	public List<DataMap> selectCmmAmsAssetsMediaOcrList(DataMap paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsMediaOcrList(paramMap);
   	}
    /**
     * 에셋 상세 연관태그 목록
	 * pick 레이어 사용(상세 정보의 연관태그)
     */
    @Override
   	public List<DataMap> selectCmmAmsAssetsTagsList(DataMap paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsTagsList(paramMap);
   	}
    /**
	 * 에셋 상세 연속자료 목록 총 수
	 * pick 레이어 사용(상세 정보의 연속자료 목록 총 수)
     */
    @Override
	public int selectCmmAmsAssetsContinueListTotCnt(CmmVO param) throws EgovBizException{
		return (Integer)cmmDAO.selectCmmAmsAssetsContinueListTotCnt(param);
	}
    /**
	 * 에셋 상세 연속자료 목록 
	 * pick 레이어 사용(상세 정보의 연속자료 목록)  
     */
    @Override
   	public List<DataMap> selectCmmAmsAssetsContinueList(CmmVO param) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsContinueList(param);
   	}
    /**
     * 에셋 상세 연관 지역문화이야기 목록
	 * pick 레이어 사용(지역문화이야기 목록) 
     */
    @Override
   	public List<DataMap> selectCmmAmsAssetsThemesContentsList(List paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsThemesContentsList(paramMap);
   	}
    /**
     * 에셋 상세  다른문화원 소장자료 목록
	 * pick 레이어 사용(다른문화원 소장자료 목록) 
     */
    public List<DataMap> selectCmmAmsAssetsDiffSojangList(DataMap paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsDiffSojangList(paramMap);
   	}
	@Override
	public List<DataMap> selectCmmAmsAssetsOriginViewList(DataMap paramMap) throws EgovBizException {
		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsOriginViewList(paramMap);
	}
	
	@Override
   	public int selectCmmAmsAssetsOriginViewListAjaxCnt(DataMap paramMap) throws EgovBizException{
   		return (Integer)cmmDAO.selectCmmAmsAssetsOriginViewListAjaxCnt(paramMap);
   	}
	@Override
	public List<DataMap> selectCmmAmsAssetsOriginViewListAjax(DataMap paramMap) throws EgovBizException {
		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsOriginViewListAjax(paramMap);
	}
	
	@Override
	public DataMap selectCmmAmsAssetsOriginViewDetail(DataMap paramMap) throws EgovBizException {
		return cmmDAO.selectCmmAmsAssetsOriginViewDetail(paramMap);
	} 
	@Override
	public int selectCmmScrapCnt(DataMap paramMap) throws EgovBizException {
		return (Integer)cmmDAO.selectCmmScrapCnt(paramMap);
	}
	@Override
    public void insertSatisfaction(DataMap paramMap) throws EgovBizException {
		cmmDAO.insertSatisfaction(paramMap);
	}
	@Override
    public void insertCmmSchedulerHst(DataMap paramMap) throws FdlException, EgovBizException {
    	//paramMap.setString("schedulerHstId", schedulerHstIdGnrService.getNextStringId());
		cmmDAO.insertCmmSchedulerHst(paramMap);
	}
	@Override
    public void insertCmmPscHst(DataMap paramMap) throws EgovBizException{
       	cmmDAO.insertCmmPscHst(paramMap);
   	}
	@Override
    public void updateCmmPscHst(DataMap paramMap) throws EgovBizException{
	   cmmDAO.updateCmmPscHst(paramMap);
	}
	@Override
    public void insertCmmScrap(DataMap paramMap) throws EgovBizException{
    	if(Constant.CONTENT_TYPE_A.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmScrapTypeA(paramMap);
    	}else if(Constant.CONTENT_TYPE_B.equals(paramMap.getString("contentType"))){
    			paramMap.setString("bbsId", Constant.BBS_ID_CUL);
   	   			cmmDAO.insertCmmScrapTypeB(paramMap);
   		}else if(Constant.CONTENT_TYPE_C.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmScrapTypeC(paramMap);
   		}else if(Constant.CONTENT_TYPE_G.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmScrapTypeG(paramMap);
   		}else if(Constant.CONTENT_TYPE_I.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmScrapTypeI(paramMap);
   		}else if(Constant.CONTENT_TYPE_P.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmScrapTypeP(paramMap);
   		}else if(Constant.CONTENT_TYPE_T.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmScrapTypeT(paramMap);
   		}
    }
	@Override
   	public void insertCmmActivityHst(DataMap paramMap) throws EgovBizException {
		
		// 사용구분(W:웹,M:모바일웹,A앱,I:API,R:RIS)
		String uaType = paramMap.getString("uaType");
		if (StringUtils.isEmpty(uaType)) {
			paramMap.setString("uaType", Constant.UA_TYPE_W);
		}
		
   		if(Constant.CONTENT_TYPE_A.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmActivityHstTypeA(paramMap);
   		}else if(Constant.CONTENT_TYPE_B.equals(paramMap.getString("contentType"))){
   			paramMap.setString("bbsId", Constant.BBS_ID_CUL);
   			cmmDAO.insertCmmActivityHstTypeB(paramMap);
   		}else if(Constant.CONTENT_TYPE_C.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmActivityHstTypeC(paramMap);
   		}else if(Constant.CONTENT_TYPE_G.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmActivityHstTypeG(paramMap);
   		}else if(Constant.CONTENT_TYPE_I.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmActivityHstTypeI(paramMap);
   		}else if(Constant.CONTENT_TYPE_P.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmActivityHstTypeP(paramMap);
   		}else if(Constant.CONTENT_TYPE_T.equals(paramMap.getString("contentType"))){
   			cmmDAO.insertCmmActivityHstTypeT(paramMap);
   		}
   	}
	@Override
   	public void updateCmmActivityHst(DataMap paramMap) throws EgovBizException {
   		if(paramMap.get("ids") != null){
   			String [] ids = null;
   			String [] contentTypes = null;
   			if(paramMap.get("ids") instanceof String[]){
   				ids = (String[]) paramMap.get("ids");
   				contentTypes  = paramMap.getString("contentTypes").split(",");
   			}else{
   				ids = new String[1];
   				ids[0] = paramMap.getString("ids");
   				contentTypes = new String[1];
   				contentTypes[0] = paramMap.getString("contentTypes");
   			}
   			for(String temp : ids){
   				paramMap.setString("contentId", temp);
   				cmmDAO.updateCmmActivityHst(paramMap);
   				paramMap.remove("contentId");
   			}
   		}
   	}
	@Override
	public void deleteCmmScrapInfo(DataMap paramMap) throws EgovBizException{
		if(paramMap.get("ids") != null){
   			String [] ids = null;
   			String [] contentTypes = null;
   			if(paramMap.get("ids") instanceof String[]){
   				ids = (String[]) paramMap.get("ids");
   				contentTypes  = paramMap.getString("contentTypes").split(",");
   			}else{
   				ids = new String[1];
   				ids[0] = paramMap.getString("ids");
   				contentTypes = new String[1];
   				contentTypes[0] = paramMap.getString("contentTypes");
   			}
   			for(String temp : ids){
   				paramMap.setString("id", temp);
   				cmmDAO.deleteCmmScrapInfo(paramMap);
   				paramMap.remove("id");
   			}
   		}else{
   			cmmDAO.deleteCmmScrapInfo(paramMap);	
   		}
	}
	
	/**
	 * 모바일 디바이스 정보 목록
	 */
	@Override
	public List<DataMap> selecCmmMobileDeviceInfoList(DataMap paramMap) throws EgovBizException {
		return (List<DataMap>)cmmDAO.selecCmmMobileDeviceInfoList(paramMap);
	}
	
	@Override
   	public void insertCmmActivityMediaHst(DataMap paramMap) throws EgovBizException {
   			cmmDAO.insertCmmActivityMediaHst(paramMap);
   	}
	
    @Override
   	public List<DataMap> selectCmmAmsAssetsTagKeyList(DataMap paramMap) throws EgovBizException {
   		return (List<DataMap>)cmmDAO.selectCmmAmsAssetsTagKeyList(paramMap);
   	}
    @Override
   	public DataMap selectCmmAmsAssetsMediaDetail2(DataMap paramMap) throws EgovBizException{
   		return cmmDAO.selectCmmAmsAssetsMediaDetail2(paramMap);
   	}
    
    @Override
   	public int selectCmmWebzineCnfirm(DataMap paramMap) throws EgovBizException{
   		return (Integer)cmmDAO.selectCmmWebzineCnfirm(paramMap);
   	}
    
    @Override
    public void insertCmmWebzineSubScribe(DataMap paramMap) throws EgovBizException{
       	cmmDAO.insertCmmWebzineSubScribe(paramMap);
   	}

    @Override
    public void insertCmmMainData(String gubun) throws EgovBizException, FdlException{
    	String toDay =  DateUtil.getNowString(DateUtil.DATE_DB_FORMAT);
		String tomorrow =  DateUtil.getAddDayFormat(1,DateUtil.DATE_DB_FORMAT);
		String startDt = DateUtil.getNowString(DateUtil.DATETIME_FORMAT);
		DataMap schedulerHstMap = new DataMap();
		boolean isSuccess = false;
		String msg = "";
		int dataCnt = 0;
		
		try {
	    	DataMap paramMap= new DataMap(); 
	    	
	    	if(gubun.equals("G")){     	// 이달의 지역문화정보
	    		paramMap.put("gubun", "G"); //구분 (C:이야기, A:지역문화PICK, G:지역문화정보, P:포스트)
	        	
	        	List<DataMap> extGiaList = cmmDAO.selectMainExtGiaList(paramMap);
	        	if(extGiaList.size()> 0){
	        		cmmDAO.deleteCmmMainExtGiaData(paramMap);
		        	for(DataMap extGia : extGiaList){
		        		extGia.put("gubun", "G");
		        		cmmDAO.insertCmmMainData(extGia);
		        		dataCnt++;
		        	}
		        	isSuccess = true;
	        	}else{
	        		msg = "[데이터 조회오류]조회된 데이터 size:0";
	        	}
	    	}
	    	
		} catch (TransactionException ex1) {
			LOGGER.error("fail in insertCmmMainData()", ex1);
			msg = dataLimit(ex1.toString());
		} catch (Exception ex2) {
			LOGGER.error("fail in insertCmmMainData()", ex2);
			msg = dataLimit(ex2.toString());
		} finally{
			schedulerHstMap.setString("schedulerMethodNm", "setMainInfo");
			
			String schedulerNm = "";
			if(gubun.equals("A")){
				schedulerNm = Constant.SCHEDULER_MAIN_A_INFO;
			}else if (gubun.equals("C")){
				schedulerNm = Constant.SCHEDULER_MAIN_C_INFO;
			}else if (gubun.equals("G")){
				schedulerNm = Constant.SCHEDULER_MAIN_G_INFO;
			}else{
				schedulerNm = Constant.SCHEDULER_MAIN_P_INFO;
			}
			schedulerHstMap.setString("schedulerNm", schedulerNm);
			schedulerHstMap.setString("strTm", startDt);
			schedulerHstMap.setString("endTm", DateUtil.getNowString(DateUtil.DATETIME_FORMAT));
			if(isSuccess){
				schedulerHstMap.setString("rstMsg", "등록성공");
			}else{
				schedulerHstMap.setString("rstMsg", "등록실패");
				schedulerHstMap.setString("etcCn", msg);
			}
			schedulerHstMap.setInt("dataCnt", dataCnt);
		}
		
		//schedulerHstMap.setString("schedulerHstId", schedulerHstIdGnrService.getNextStringId());
		cmmDAO.insertCmmSchedulerHst(schedulerHstMap);
   	}
    
    @Override
   	public DataMap insertCmmExtGiaMainInfo(String contentType) throws FdlException {

		String startDt = DateUtil.getNowString(DateUtil.DATETIME_FORMAT);
		DataMap schedulerHstMap = new DataMap();
		boolean isSuccess = false;
		String msg = "";
		int dataCnt = 0;
		
		try {
	    	DataMap paramMap= new DataMap(); 
	    	
	    	if(contentType.equals("G")){     	// 이달의 지역문화정보
	    		paramMap.put("gubun", "G"); //구분 (C:이야기, A:지역문화PICK, G:지역문화정보, P:포스트)
	        	
	        	List<DataMap> extGiaList = cmmDAO.selectMainExtGiaList(paramMap);
	        	if(extGiaList.size()> 0){
	        		cmmDAO.deleteCmmMainExtGiaData(paramMap);
		        	for(DataMap extGia : extGiaList){
		        		extGia.put("gubun", "G");
		        		cmmDAO.insertCmmMainData(extGia);
		        		dataCnt++;
		        	}
		        	isSuccess = true;
	        	}else{
	        		msg = "[데이터 조회오류]조회된 데이터 size:0";
	        	}
	    	}
	    	
		} catch (TransactionException ex1) {
			LOGGER.error("fail in insertCmmMainData()", ex1);
			msg = dataLimit(ex1.toString());
		} catch (Exception ex2) {
			LOGGER.error("fail in insertCmmMainData()", ex2);
			msg = dataLimit(ex2.toString());
		} finally{
			schedulerHstMap.setString("schedulerMethodNm", "setMainInfo");
			
			String schedulerNm = "";
			if(contentType.equals("A")){
				schedulerNm = Constant.SCHEDULER_MAIN_A_INFO;
			}else if (contentType.equals("C")){
				schedulerNm = Constant.SCHEDULER_MAIN_C_INFO;
			}else if (contentType.equals("G")){
				schedulerNm = Constant.SCHEDULER_MAIN_G_INFO;
			}else{
				schedulerNm = Constant.SCHEDULER_MAIN_P_INFO;
			}
			schedulerHstMap.setString("schedulerNm", schedulerNm);
			schedulerHstMap.setString("strTm", startDt);
			schedulerHstMap.setString("endTm", DateUtil.getNowString(DateUtil.DATETIME_FORMAT));
			if(isSuccess){
				schedulerHstMap.setString("rstMsg", "등록성공");
			}else{
				schedulerHstMap.setString("rstMsg", "등록실패");
				schedulerHstMap.setString("etcCn", msg);
			}
			schedulerHstMap.setInt("dataCnt", dataCnt);
		}
		
		//schedulerHstMap.setString("schedulerHstId", schedulerHstIdGnrService.getNextStringId());
		cmmDAO.insertCmmSchedulerHst(schedulerHstMap);
		return schedulerHstMap;
    }
    
    @Override
	public DataMap selectCmmPscHst(String jsessionId) throws EgovBizException {
    	DataMap paramMap = new DataMap();
		paramMap.setString("jsessionId", jsessionId); 
		paramMap.setInt("sortOrdr", 1);
		DataMap pscHstMap1 = cmmDAO.selectCmmPscHstDetail(paramMap);
		
		paramMap.setInt("sortOrdr", 2);
		DataMap pscHstMap2 = cmmDAO.selectCmmPscHstDetail(paramMap);
		
		paramMap.setInt("sortOrdr", 3);
		DataMap pscHstMap3 = cmmDAO.selectCmmPscHstDetail(paramMap);
		
		String pscHstAddr = propertiesService.getString("kccf.default.pscHst");
		String[] addrArr = pscHstAddr.split("\\^");
		String addr = "";
		String sidoName = "";
		String sigunguName = "";
		
		if(pscHstMap1 == null){
			if(!StringUtils.isBlank(addrArr[0])){
				addr = addrArr[0].replaceAll("\\|", " ");
	    		StringTokenizer st = new StringTokenizer(addr," ");
	    		if(st.hasMoreElements()){
	    			if(st.hasMoreTokens()){
	    				sidoName = st.nextToken();
	    			}
	    			if(st.hasMoreTokens()){
	    				sigunguName = st.nextToken();
	    			}
	    		}
			}
			pscHstMap1 = new DataMap();
			pscHstMap1.setString("sidoName", sidoName);
			pscHstMap1.setString("sigunguName", sigunguName);
		}
		
		if(pscHstMap2 == null){
			if(!StringUtils.isBlank(addrArr[1])){
				addr = addrArr[1].replaceAll("\\|", " ");
	    		StringTokenizer st = new StringTokenizer(addr," ");
	    		if(st.hasMoreElements()){
	    			if(st.hasMoreTokens()){
	    				sidoName = st.nextToken();
	    			}
	    			if(st.hasMoreTokens()){
	    				sigunguName = st.nextToken();
	    			}
	    		}
			}
			pscHstMap2 = new DataMap();
			pscHstMap2.setString("sidoName", sidoName);
			pscHstMap2.setString("sigunguName", sigunguName);
		}
		
		if(pscHstMap3 == null){
			if(!StringUtils.isBlank(addrArr[2])){
				addr = addrArr[2].replaceAll("\\|", " ");
	    		StringTokenizer st = new StringTokenizer(addr," ");
	    		if(st.hasMoreElements()){
	    			if(st.hasMoreTokens()){
	    				sidoName = st.nextToken();
	    			}
	    			if(st.hasMoreTokens()){
	    				sigunguName = st.nextToken();
	    			}
	    		}
			}
			pscHstMap3 = new DataMap();
			pscHstMap3.setString("sidoName", sidoName);
			pscHstMap3.setString("sigunguName", sigunguName);
		}
		
		DataMap pscHstMap = new DataMap(); //관심지역 표시에 사용
		pscHstMap.put("pscHst1", pscHstMap1);
		pscHstMap.put("pscHst2", pscHstMap2);
		pscHstMap.put("pscHst3", pscHstMap3);
		
		return pscHstMap;
	} 
    
    private String dataLimit(String data){
    	String rtnStr = "";
    	if(CmmUtil.checkMaxbyte(data , 1000)){
    		rtnStr = data.substring(0 , 1000);
    	}else{
    		rtnStr = data;
    	}
    	return rtnStr;
    }
    
	public DataMap getMainLogo() throws EgovBizException{
		return cmmDAO.getMainLogo();
	}
    
}