package com.eactive.eai.rms.bat.monitoring.eimsrcvlog;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.bat.common.base.BatBaseService;
import com.eactive.eai.rms.common.util.CommonUtil;

@Service("eimsRcvLogMonitorService")
public class EimsRcvLogMonitorService extends BatBaseService {

	@Autowired
	@Qualifier("eimsRcvLogMonitorDao")
	private EimsRcvLogMonitorDao dao;
	
	public HashMap<String, Object> selectList(int startNum,int endNum, HashMap<String,Object> paramap) throws Exception {
 
		List<List<Object>> totalCountArrList = new ArrayList<List<Object>>();
		HashMap<String,List<Integer>> searchCountMap = new HashMap<String,List<Integer>>();
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		
		paramap.put("startNum" , startNum);
		paramap.put("endNum"   , endNum);
		paramap.put("tableNum" , "");
		
		// 조회 DateTime(YYYY/MM/DD hh:mn:ss)에 miliSecond 추가 : 누락데이터 방지
		String startDateTime = paramap.get("searchStartTime").toString();
		String endDateTime = paramap.get("searchEndTime").toString();
		String searchEaiBzwkDstcd = paramap.get("searchEaiBzwkDstcd").toString().trim();
		// Local->UTC TimeZone 변경 후 MiliSec 추가
		paramap.replace("searchStartTime",startDateTime, CommonUtil.convertLocal2UTC(startDateTime)+"000");  
		paramap.replace("searchEndTime",endDateTime, CommonUtil.convertLocal2UTC(endDateTime)+"999");

		//** 업무구분 스패이스 없애기
		paramap.replace("searchEaiBzwkDstcd",searchEaiBzwkDstcd);
		
		// dayList 구하기
		String startDate = paramap.get("searchStartTime").toString().substring(0,8);
		String endDate = paramap.get("searchEndTime").toString().substring(0,8);
		String searchDate = endDate;  // 최신거래 우선순으로 정의

		int diff_end_start = endNum - startNum + 1;
		long countDays = CommonUtil.getCountDate(startDate,endDate);
		
		List<String> ddList = new ArrayList<String>();
		ddList.add(searchDate.substring(6,8));
		for (long d=0; d < countDays; d++) {
			searchDate = CommonUtil.getAddDate(searchDate);
			ddList.add(searchDate.substring(6,8));
		}
		
		// 단일 조회 시 다음날까지 조회기간에 포함
		if (startDate.equals(endDate)) ddList.add(CommonUtil.getAddDate(startDate).substring(6,8));
		
		// totalCountMap 구하기 (e.g ["dd", startNum, endNum])
		int totalCountStartNum = 0, totalCountEndNum = 0;
		for (String dd : ddList) {
			paramap.replace("tableNum", dd);
			List<Object> totalCountList = new ArrayList<Object>();
			totalCountStartNum = totalCountEndNum + 1;
			totalCountEndNum = totalCountEndNum + dao.selectListCount(paramap);
			totalCountList.add(dd);
			totalCountList.add(totalCountStartNum);
			totalCountList.add(totalCountEndNum);
			totalCountArrList.add(totalCountList);
		}
		
		// searchCountMap 구하기 (e.g {"dd"=[startNum,endNum]})
		for (int i=0; i<totalCountArrList.size(); i++) {

			List<Object> totalCountList = totalCountArrList.get(i);
			String day = (String)totalCountList.get(0);
			int dayStartNum = (int)totalCountList.get(1);
			int dayEndNum = (int)totalCountList.get(2);

			// i번째 totalCountList Count가 음수이면 SKIP
			if (dayEndNum-dayStartNum < 0) continue;

			String nextDay = "";
			int nextDayStartNum = 0, nextDayEndNum = 0;
			if (i < totalCountArrList.size()-1) {
				List<Object> totalCountNextList = totalCountArrList.get(i+1);
				nextDay = (String)totalCountNextList.get(0);
				nextDayStartNum = (int)totalCountNextList.get(1);
				nextDayEndNum = (int)totalCountNextList.get(2);
				
				// 위의 i+1번째 totalCountNextList Count가 0이면 i++번째 totalCountNextList 조회
				if (nextDayEndNum-nextDayStartNum <= 0) {
					for (int j=i+2; j<totalCountArrList.size(); j++) {
						totalCountNextList = totalCountArrList.get(j);
						nextDay = (String)totalCountNextList.get(0);
						nextDayStartNum = (int)totalCountNextList.get(1);
						nextDayEndNum = (int)totalCountNextList.get(2);
						if (nextDayEndNum-nextDayStartNum > 0) break;
					}
				}
			}

			int diff_total_start = dayEndNum - startNum + 1;

			List<Integer> numList = new ArrayList<Integer>();
			if (diff_total_start >= 0) {
				if (diff_total_start >= diff_end_start) {  // 첫번째 day 테이블에서 모두 조회
					numList.add(startNum);
					numList.add(endNum);
					searchCountMap.put(day, numList);
					break;
				} else if (diff_total_start < diff_end_start && startDate.equals(endDate)) {  // 첫번째 day 테이블에서만 일부 조회
					numList.add(startNum);
					numList.add(dayEndNum);
					searchCountMap.put(day, numList);
					break;					
				} else if (diff_total_start < diff_end_start) {  // 첫번째 day 테이블에서 일부, 두번째 day 테이블에서 일부 조회
					// 첫번째 day에서 일부 조회
					numList.add(startNum);
					numList.add(dayEndNum);
					searchCountMap.put(day, numList);
					// 두번째 day에서 나머지 조회
					numList = new ArrayList<Integer>();
					numList.add(1);
					numList.add(diff_end_start-diff_total_start);
					searchCountMap.put(nextDay, numList);
					break;
				}
			} else {
				if (startNum > dayEndNum && startNum <= nextDayEndNum) {
					if (endNum <= nextDayEndNum) {			// 두번째 day 테이블에서 모두 조회
						numList.add(1-diff_total_start);
						numList.add(diff_end_start-diff_total_start);
						searchCountMap.put(nextDay, numList);
						break;
					} else if (endNum > totalCountEndNum) {   // 조회 endCount가 totalCount를 넘으면 totalCount가지만 조회
						numList.add(1-diff_total_start);
						numList.add((totalCountEndNum-startNum+1)-diff_total_start);
						searchCountMap.put(nextDay, numList);
						break;
					}
				}
			}
		}

		// selectList 구하기
		for (String dd : searchCountMap.keySet()) {
			if (!dd.equals("")) {
				List<Integer> searchCount = searchCountMap.get(dd);
				paramap.replace("tableNum" , dd);
				paramap.replace("startNum" , searchCount.get(0));
				paramap.replace("endNum"   , searchCount.get(1));
				dataList.addAll(dao.selectList(paramap));
			}
		}
		
		// TimeZone UTC->Local 변경
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> listMap : dataList) {
			for (String key : listMap.keySet()) {
				if (key.equals("DATETIME")) {
					listMap.replace(key,CommonUtil.convertUTC2Local(listMap.get(key).toString()));
				}
			}
			resultList.add(listMap);
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("totalCount", totalCountEndNum);
		map.put("list", resultList);

		return map;
	}	

	public HashMap<String, Object> selectLogDetail(String sn, String dateTime) throws Exception {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("sn", sn);
		paramMap.put("regdate", dateTime);		
		HashMap<String, Object> detail = dao.selectLogDetail(paramMap);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("detail" , detail);
		
		return map;

	}
}
