package nlib.col.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import nlib.col.service.CollectionService;
import nlib.col.service.CollectionVO;
import nlib.restful.DataApi;
import nlib.restful.service.DataApiReqVO;
import nlib.restful.service.DataApiResVO;
import nlib.restful.service.XmlConverter;
import nlib.util.StringUtil;

/**
 * <pre>
 * @Class Name : CollectionServiceImpl.java
 * 
 * @Description : 소장자료 정보를 조회하는 서비스
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 10. 6.    KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 10. 6.
 * @version 1.0
 *
 */
@Service("collectionService")
public class CollectionServiceImpl implements CollectionService {

	private static final Logger log = LoggerFactory.getLogger(CollectionServiceImpl.class);
    
	/** RESTFul API 송수신 모듈 */
	@Resource(name = "dataApi")
	private DataApi dataApi;
	
	@Resource(name="collectionDAO")
	private CollectionDAO collectionDAO;
	
	
	/**
	 * 자료 상세정보를 조회한다.
	 * 
	 * @param searchVO
	 * @return
	 * @throws Exception
	 */
	public CollectionVO getItemInfo(CollectionVO searchVO) throws Exception {

    	String message = null;

    	// 입력값 확인 
    	String masterId = searchVO.getMasterId();
    	String mbInfoId = searchVO.getMbInfoId();
    	
    	if(StringUtil.isEmpty(masterId)) {
    		message = "[필수값 미입력] 자료 ID 정보가 입력되지 않았습니다.";
    		return new CollectionVO("E102", message);
    	}
    	
    	// 변수 설정 
    	DataApiReqVO reqVO = new DataApiReqVO("/uac/service/nlib/col/getItemInfo", HttpMethod.GET);
    	reqVO.putInfoItem("masterId", masterId);
    	reqVO.setMbInfoId(mbInfoId); // 통신 시, 암호화되어 송수신됨 
    	
    	// API 호출 
    	DataApiResVO resVO = dataApi.request(reqVO);

    	// 결과값 전달 
    	CollectionVO retVO = (CollectionVO)XmlConverter.convertMapToObject(resVO.getInfo(), CollectionVO.class);
    	if(retVO == null) {
    		log.error("getItemInfo > 조회된 자료 정보가 없습니다.");
    		return null;
    	}
    	
    	retVO.setResultCode(resVO.getResultCode());
    	retVO.setResultMessage(resVO.getResultMessage());
    	
    	return retVO;
	}

	/**
	 * 목록의 자료정보에 상세정보를 조회하여 설정한 후 리턴한다. 
	 * 
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public List<CollectionVO> setDetailInfoForList(List<CollectionVO> list) throws Exception {
		return setDetailInfoForList(list, null);
	}
	
	/**
	 * 목록의 자료정보에 상세정보를 조회하여 설정한 후 리턴한다. 
	 * 
	 * @param list
	 * @param mbInfoId
	 * @param defaultThumbnailUrl
	 * @return
	 * @throws Exception
	 */
	public List<CollectionVO> setDetailInfoForList(List<CollectionVO> list, String mbInfoId) throws Exception {

		if(list == null || list.size() < 1) return list;

    	int cnt = list.size();
    	HashMap<String, CollectionVO> collectionMap = new HashMap<String, CollectionVO>();
    	
		// 문화원별 API 요청 처리 
    	String jsonMasterId = "";
    	for(int i=0; i<cnt; i++) {
			
    		CollectionVO vo = list.get(i);
    		
    		if(StringUtil.isEmpty(vo.getMasterId())) continue;
			if(mbInfoId == null) mbInfoId = vo.getMbInfoId();
    		
    		// [{"masterId":"xxxx"}, {"masterId":"xxxb"},…]
    		if(jsonMasterId.length() > 0) jsonMasterId += ",";
    		jsonMasterId += "{\"masterId\":\"" + vo.getMasterId() + "\"}";
    	}
    	if(StringUtil.isEmpty(jsonMasterId)) return list;
    	jsonMasterId = "[" + jsonMasterId + "]";
		
    	// API 호출 
    	DataApiReqVO reqVO = new DataApiReqVO("/uac/service/nlib/col/listItemInfo", HttpMethod.GET);
    	reqVO.setMbInfoId(mbInfoId); // 통신 시, 암호화되어 송수신됨 
    	reqVO.putInfoItem("jsonMasterId", jsonMasterId);
    	
    	DataApiResVO resVO = dataApi.request(reqVO);
    	
    	// 결과 처리 
    	if(resVO.getResultCode().charAt(0) == 'S') {
    		List<HashMap<String, String>> recordList = resVO.getList("record");
    		if(recordList == null || recordList.size() < 1) return list;
    		
    		for(HashMap<String, String> record : recordList) {
    			CollectionVO cVO = (CollectionVO)XmlConverter.convertMapToObject(record, CollectionVO.class);
    			if(cVO != null && StringUtil.isNotEmpty(cVO.getMasterId())) {
    				collectionMap.put(cVO.getMasterId(), cVO);
    			}
    		}
    	} else {
    		log.error("setDetailInfoForCartItems > 소장자료 다건 메타정보 조회 오류(API) : " + resVO.getResultCode() + " : " + resVO.getResultMessage());
    	}
		

		// 목록에 업데이트 설정 
    	for(int i=0; i<cnt; i++) {
    		CollectionVO vo = list.get(i);
    		String masterId = vo.getMasterId();
    		CollectionVO cVO = collectionMap.get(masterId);
    		
    		if(cVO == null) continue;
    		
    		vo.setTitle          (cVO.getTitle());
    		
    		vo.setTypeDivCd      (StringUtil.getString(cVO.getTypeDivCd()      , vo.getTypeDivCd()));
    		vo.setTypeCodeNm     (StringUtil.getString(cVO.getTypeCodeNm()     , vo.getTypeCodeNm()));
    		vo.setDtlsTypeDivCd  (StringUtil.getString(cVO.getDtlsTypeDivCd()  , vo.getDtlsTypeDivCd()));
    		vo.setDtlsTypeDivNm  (StringUtil.getString(cVO.getDtlsTypeDivNm()  , vo.getDtlsTypeDivNm()));
    		
    		vo.setSubjectCdUp    (StringUtil.getString(cVO.getSubjectCdUp()    , vo.getSubjectCdUp()));
    		vo.setSubjectNmUp    (StringUtil.getString(cVO.getSubjectNmUp()    , vo.getSubjectNmUp()));
    		vo.setSubjectCd      (StringUtil.getString(cVO.getSubjectCd()      , vo.getSubjectCd()));
    		vo.setSubjectNm      (StringUtil.getString(cVO.getSubjectNm()      , vo.getSubjectNm()));
    		
    		vo.setOrgNm          (StringUtil.getString(cVO.getOrgNm()          , vo.getOrgNm()));
    		vo.setCreatYyyy      (StringUtil.getString(cVO.getCreatYyyy()      , vo.getCreatYyyy()));
    		vo.setRprsThumbUrl   (StringUtil.getString(cVO.getRprsThumbUrl()   , vo.getRprsThumbUrl()));
    		vo.setInterfaceId    (StringUtil.getString(cVO.getInterfaceId()    , vo.getInterfaceId()));
    		vo.setOpenDivCd      (StringUtil.getString(cVO.getOpenDivCd()      , vo.getOpenDivCd()));
    		vo.setOperReadRangeCd(StringUtil.getString(cVO.getOperReadRangeCd(), vo.getOperReadRangeCd()));
    		vo.setOperOutRangeCd (StringUtil.getString(cVO.getOperOutRangeCd() , vo.getOperOutRangeCd()));
    		vo.setUseStatus      (StringUtil.getString(cVO.getUseStatus()      , vo.getUseStatus()));
    		vo.setRtnExpctDd     (StringUtil.formatDateStr(cVO.getRtnExpctDd() , "-"));
    		vo.setAwaiterCnt     (StringUtil.getInt   (cVO.getAwaiterCnt()     , vo.getAwaiterCnt()));
    		vo.setBookLentPsblYn (StringUtil.getString(cVO.getBookLentPsblYn() , vo.getBookLentPsblYn()));
    		vo.setRsrvPsblYn     (StringUtil.getString(cVO.getRsrvPsblYn()     , vo.getRsrvPsblYn()));
    		vo.setReqPsblYn      (StringUtil.getString(cVO.getReqPsblYn()      , vo.getReqPsblYn()));
    		vo.setInterestYn     (StringUtil.getString(cVO.getInterestYn()     , vo.getInterestYn()));
    		vo.setMUseYn         (StringUtil.getString(cVO.getMUseYn()         , vo.getMUseYn()));
    		vo.setDigitalReadYn  (StringUtil.getString(cVO.getDigitalReadYn()  , vo.getDigitalReadYn()));
    		
    		vo.setMngOrgCd       (StringUtil.getString(cVO.getMngOrgCd()       , vo.getMngOrgCd()));
    		vo.setMngOrgNm       (StringUtil.getString(cVO.getMngOrgNm()       , vo.getMngOrgNm()));
    	}
		
    	return list;
	}
	

	/**
	 * 목록의 자료정보에 상세정보를 조회하여 설정한 후 리턴한다. 
	 * 
	 * @param list
	 * @param mbInfoId
	 * @param defaultThumbnailUrl
	 * @return
	 * @throws Exception
	 */
	public List<CollectionVO> setDetailInfoForHashList(List<HashMap<String, String>> list, String mbInfoId) throws Exception {
		
		List<CollectionVO> listObj = new ArrayList<CollectionVO>();
		
		if(list == null || list.size() < 1) return null;
		
		for(HashMap<String, String> record : list) {
			CollectionVO cVO = (CollectionVO)XmlConverter.convertMapToObject(record, CollectionVO.class);
			if(cVO != null && StringUtil.isNotEmpty(cVO.getMasterId())) {
				listObj.add(cVO);
			}
		}
		
		return setDetailInfoForList(listObj, mbInfoId);
	}
	

	/**
	 * 자료 마스터ID 목록 문자열을 받아 CollectionVO 리스트 생성하여 리턴한다. 
	 * 
	 * @param masterIds
	 * @return
	 */
	public List<CollectionVO> makeListOfCollectionVO(String masterIds) {

		if(masterIds == null || StringUtil.isEmpty(masterIds)) return null;
	
		String[] items = masterIds.split(",");
		
		if(items == null || items.length < 1) return null;
		
		List<CollectionVO> retList = new ArrayList<CollectionVO>();
		for(String item : items) {
			
			if(StringUtil.isEmpty(item)) continue;
			
			CollectionVO itemVO = new CollectionVO();
			itemVO.setMasterId(item);
			retList.add(itemVO);
		}
		if(retList.size() < 1) return null;
		
		return retList;
	}
	

	/**
	 * 자료 마스터ID 목록 문자열을 받아 상세내용을 조회하고, CollectionVO 리스트 생성하여 리턴한다. 
	 * 
	 * @param masterIds
	 * @return
	 */
	public List<CollectionVO> makeInfoListOfCollectionVO(String masterIds, String mbInfoId) throws Exception {
		
		List<CollectionVO> retList = makeListOfCollectionVO(masterIds);
		
		if(retList == null || retList.size() < 1) return null;
		
		return setDetailInfoForList(retList, mbInfoId);
	}

	/**
	 * 자료상세조회 및 원문보기시에 로그 
	 * 
	 * @param colVO
	 * @return
	 */
	public void insertDataInquiryLog(CollectionVO colVO) throws Exception {
		collectionDAO.insertDataInquiryLog(colVO);
	}

	/**
	 * 함께 볼만한 자료 리스트 
	 * 
	 * @param vo
	 * @return
	 */
	public List<CollectionVO> selectSeeTogetherList(CollectionVO vo) throws Exception {
		return collectionDAO.selectSeeTogetherList(vo);
	}

	/**
	 * 유사한 자료 리스트 
	 * 
	 * @param vo
	 * @return
	 */
	public List<CollectionVO> selectSimilarList(CollectionVO vo) throws Exception {
		return collectionDAO.selectSimilarList(vo);
	}

}
