package com.eactive.eai.rms.onl.dashboard.service;

import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.data.entity.onl.property.Prop;
import com.eactive.eai.data.entity.onl.property.PropGroup;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.data.entity.onl.property.PropertyGroupService;
import com.eactive.eai.rms.onl.dashboard.dao.DashboardErrorDAO;
import com.eactive.eai.rms.onl.manage.comm.unifbwk.UnifbwkManService;
import com.eactive.eai.rms.onl.manage.comm.unifbwk.UnifbwkUI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * The Interface DashboardService.
 * <ul>
 * <li>1. Function :</li>
 * <li>2. Summary :</li>
 * <li>3. Notification :</li>
 * </ul>
 * 
 */
@Service("mobileMonitorService")
public class MobileMonitorService extends OnlBaseService {

	@Autowired
	@Qualifier("dashboardError")
	private DashboardErrorDAO dashboardErrorDao;

	@Autowired
	private PropertyGroupService propertyGroupService;

	@Autowired
	private UnifbwkManService unifbwkManService;

	public int getLogListCount(String service, String logTime, String nowTime) throws Exception {

		DataSourceType dt = DataSourceTypeManager.getDataSourceType(service);
		DataSourceContextHolder.setDataSourceType(dt);

		// 취약점코드 수정 2019.08.22 SW
		String owner = "";
		if (dt != null) {
			owner = dt.getSchema();
		}

		int resultCount = dashboardErrorDao.getMobileMonitorLogListCount(owner, logTime, nowTime);

		return resultCount;
	}

	public Vector getLogList(String service, String logTime, String errorType, String commDiv) throws Exception {

		String logDate = getCurrentDate() + logTime.replaceAll(":", "");

		Vector vt = null;

		DataSourceType dt = DataSourceTypeManager.getDataSourceType(service);

		if (dt != null) {
			DataSourceContextHolder.setDataSourceType(dt);

			String owner = "";
			if (dt != null) {
				owner = dt.getSchema();
			}

			vt = dashboardErrorDao.getMobileMonitorLogList(owner, logDate, errorType, commDiv);
		}

		return vt;
	}

	public Vector getBatchLogList(String service, String logTime, String errType) throws Exception {

		String logDate = getCurrentDate() + logTime.replaceAll(":", "");

		Vector vt = null;

		DataSourceType dt = DataSourceTypeManager.getDataSourceType(service);

		if (dt != null) {
			DataSourceContextHolder.setDataSourceType(dt);

			String owner = "";
			if (dt != null) {
				owner = dt.getSchema();
			}

			vt = dashboardErrorDao.getMobileMonitorBatchLogList(owner, logDate, errType);
		}

		return vt;
	}

	public Vector getDetailInfomation(String eaiGuid, String service, String apCd) throws Exception {

		Vector vt = null;

		int yy = Integer.valueOf(eaiGuid.substring(13, 17));
		int mm = Integer.valueOf(eaiGuid.substring(17, 19));
		int dd = Integer.valueOf(eaiGuid.substring(19, 21));
		int hh = Integer.valueOf(eaiGuid.substring(21, 23));
		int MM = Integer.valueOf(eaiGuid.substring(23, 25));

		String startConvCal = "";
		String endConvCal = "";

		Calendar orgCal = new GregorianCalendar();

		orgCal.set(yy, mm - 1, dd, hh, MM, 00);
		orgCal.add(Calendar.MINUTE, -5);
		startConvCal = convertSdfTime(orgCal);
		orgCal.add(Calendar.MINUTE, 10);
		endConvCal = convertSdfTime(orgCal);

		if ("".equals(service))
			service = "DSG";

		DataSourceType dt = DataSourceTypeManager.getDataSourceType(service);
		DataSourceContextHolder.setDataSourceType(dt);

		// 취약점코드 수정 2019.08.22 SW
		String owner = "";
		if (dt != null) {
			owner = dt.getSchema();
		}

		// 대외디비에서 해당 GUID 검색
		vt = dashboardErrorDao.getDetailInfomation(owner, eaiGuid, startConvCal, endConvCal, apCd);

		// 대외 거래인 경우는 대외거래로 처리, 대외 거래가 아닌 경우 공동망 거래 처리
		if ("GSG".equals(service)) {
			dt = DataSourceTypeManager.getDataSourceType(service);
			DataSourceContextHolder.setDataSourceType(dt);

			if (dt != null) {
				owner = dt.getSchema();
			}

			if (!vt.isEmpty() && !"null".equalsIgnoreCase(vt.get(5).toString())) {
				// 은행코드가 있는 경우 은행코드를 검색해준다.//운영은 INSIDE -> COMMON
				String bankCode = getBankCode(service, (String) vt.get(5));
				vt.add(bankCode); // 인덱스 6
			}

		} else {
			// GUID가 대외에 있는 경우는 어뎁터의 이름과 전화번호를 넘겨준다.
			if (!vt.isEmpty() && !"null".equalsIgnoreCase(vt.get(5).toString())) {
				// 은행코드가 있는 경우 은행코드를 검색해준다.//개발은 INSIDE -> 운영은 COMMON
				String system = "";
				if (SystemUtil.isProdServer()) {
					system = "GSG";
				} else {
					system = "DSG";
				}
				String bankCode = getBankCode(system, (String) vt.get(5));
				vt.set(5, bankCode);
			}

			String ServCd = (String) vt.get(7);

			// 기동업무 정보 조회 //운영적용시 INSIDE -> OUTSIDE
			String apInfoIn[] = getWorkerInfo("DSG", ServCd.substring(ServCd.length() - 6, ServCd.length() - 3))
					.split(":");
			// 기동 담당자
			vt.add(apInfoIn[0]);
			// 기동업무 한글명
			vt.add(ServCd.substring(ServCd.length() - 6, ServCd.length() - 3) + " (" + apInfoIn[1] + ")");

			// 수동업무 정보 조회//운영적용시 INSIDE -> OUTSIDE
			String apInfoOut[] = getWorkerInfo("DSG", ServCd.substring(0, 3)).split(":");
			// 수동 담당자
			vt.add(apInfoOut[0]);
			// 수동업무 한글명
			vt.add(ServCd.substring(0, 3) + " (" + apInfoOut[1] + ")");

		}

		return vt;
	}

	// 업무코드 한글명 및 담당자 조회
	private String getWorkerInfo(String service, String apCode) throws Exception {

		String result = "";
		DataSourceType dt = DataSourceTypeManager.getDataSourceType(service);
		DataSourceContextHolder.setDataSourceType(dt);
		// 취약점코드 수정 2019.08.22 SW
		String owner = "";
		if (dt != null) {
			owner = dt.getSchema();
		}
		HashMap paramMap = new HashMap();
		paramMap.put("schemaId", owner);
		paramMap.put("eaiBzwkDstcd", apCode);

		UnifbwkUI userUI = unifbwkManService.selectDetail((String) paramMap.get("eaiBzwkDstcd"));

		if (userUI != null) {
			result = userUI.getEaiBzwkDstcd() + ":" + userUI.getBzwkDsticName();
		}
		return result;
	}

	private String getBankCode(String service, String bankCode) throws Exception {
		DataSourceType dt = DataSourceTypeManager.getDataSourceType(service);
		DataSourceContextHolder.setDataSourceType(dt);
		Optional<PropGroup> propGroup = propertyGroupService.findById("BANKCODE");
		if (!propGroup.isPresent()) {
			return "";
		}
		for (Prop prop : propGroup.get().getProps()) {
			if (prop.getId().getPrptyname().equals(bankCode)) {
				return prop.getPrpty2val();
			}
		}
		return "";
	}

	private String convertSdfTime(Calendar cal) {
		Date d = cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return sdf.format(d).toString();
	}

	private String getCurrentDate() {
		SimpleDateFormat SDF_YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
		return (SDF_YYYYMMDD).format(new Date());
	}

}
