package com.eactive.eai.rms.onl.manage.serviceinfo.submessage;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.entity.onl.submessage.SubMessageInfo;
import com.eactive.eai.data.entity.onl.submessage.SubMessageItem;
import com.eactive.eai.data.entity.onl.submessage.SubMessageItemId;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.data.entity.onl.stdmessage.SubExtendedColumnDefinitionService;
import com.eactive.eai.rms.data.entity.onl.submessage.SubMessageInfoService;
import com.eactive.eai.rms.onl.common.exception.EMSRuntimeException;
import com.eactive.eai.rms.onl.manage.serviceinfo.subdefault.SubExtendedColumnDefinitionUI;
import com.eactive.eai.rms.onl.manage.serviceinfo.subdefault.SubExtendedColumnDefinitionUIMapper;

@Service
@Transactional
public class SubMessageService {

	private SubExtendedColumnDefinitionService subExtendedColumnDefinitionService;

	private SubMessageInfoService subMessageInfoService;

	private SubMessageUIMapper subMessageUIMapper;

	private SubExtendedColumnDefinitionUIMapper subExtendedColumnDefinitionUIMapper;

	private ComboService comboService;

	@Autowired
	public SubMessageService(SubMessageInfoService subMessageInfoService, SubMessageUIMapper subMessageUIMapper,
			SubExtendedColumnDefinitionService subExtendedColumnDefinitionService,
			SubExtendedColumnDefinitionUIMapper subExtendedColumnDefinitionUIMapper, ComboService comboService) {
		this.subMessageInfoService = subMessageInfoService;
		this.subMessageUIMapper = subMessageUIMapper;
		this.subExtendedColumnDefinitionService = subExtendedColumnDefinitionService;
		this.subExtendedColumnDefinitionUIMapper = subExtendedColumnDefinitionUIMapper;
		this.comboService = comboService;
	}

	public Page<SubMessageUI> selectList(Pageable pageable, String searchBzwkSvcKeyName) {
		return subMessageInfoService.findAll(pageable, searchBzwkSvcKeyName).map(subMessageUIMapper::toVo);
	}

	public List<Map<String, Object>> selectListToExcel(String searchBzwkSvcKeyName) {
		return selectList(Pageable.unpaged(), searchBzwkSvcKeyName).stream().map(subMessageInfo -> {
			Map<String, Object> map = new HashMap<>();
			map.put("BZWKSVCKEYNAME", subMessageInfo.getBzwkSvcKeyName());
			return map;
		}).collect(Collectors.toList());
	}

	public SubMessageUI selectDetail(String bzwkSvcKeyName) {
		SubMessageInfo subMessageInfo = subMessageInfoService.getById(bzwkSvcKeyName);
		return subMessageUIMapper.toVo(subMessageInfo);
	}

	public List<SubExtendedColumnDefinitionUI> selectDetailForKey() {
		return subExtendedColumnDefinitionService
				.findAllKeys()
				.stream()
				.map(subExtendedColumnDefinitionUIMapper::toVo)
				.collect(Collectors.toList());
	}

	public void update(Map<String, Object> paramMap, SubMessageUI subMessageUI) {

		SubMessageInfo subMessageInfo = subMessageInfoService.getById(subMessageUI.getBzwkSvcKeyName());
		subMessageInfo.setModfimgtstusdstcd("1");
		subMessageInfo.getSubMessageItems().clear();

		List<SubMessageItem> subMessageItems = mergeHS05(paramMap, subMessageUI);
		subMessageInfo.getSubMessageItems().addAll(subMessageItems);

		subMessageInfoService.save(subMessageInfo);
	}

	public void insert(Map<String, Object> paramMap, SubMessageUI subMessageUI) {
		// 1.중복체크
		if (subMessageInfoService.existsById(subMessageUI.getBzwkSvcKeyName())) {
			throw new EMSRuntimeException("이미 존재하는 내부 표준전문입니다.");
		}

		SubMessageInfo subMessageInfo = new SubMessageInfo();
		subMessageInfo.setBzwksvckeyname(subMessageUI.getBzwkSvcKeyName());
		subMessageInfo.setModfimgtstusdstcd("1");

		List<SubMessageItem> subMessageItems = mergeHS05(paramMap, subMessageUI);

		subMessageInfo.setSubMessageItems(subMessageItems);
		subMessageInfoService.save(subMessageInfo);
	}

	public List<SubMessageItem> mergeHS05(Map<String, Object> paramMap, SubMessageUI subMessageUI) {

		List<SubMessageItem> subMessageItems = new LinkedList<>();

		for (Entry<String, Object> entry : paramMap.entrySet()) {
			if (subExtendedColumnDefinitionService.existsById(entry.getKey())) {
				String columnName = entry.getKey();
				String columnValue = (String) entry.getValue();

				SubMessageItemId subMessageItemId = new SubMessageItemId();
				subMessageItemId.setBzwksvckeyname(subMessageUI.getBzwkSvcKeyName());
				subMessageItemId.setColumnname(columnName);
				SubMessageItem subMessageItem = new SubMessageItem();
				subMessageItem.setColumnvalue(columnValue);
				subMessageItem.setId(subMessageItemId);

				subMessageItems.add(subMessageItem);
			}
		}

		return subMessageItems;
	}

	public void delete(String bzwkSvcKeyName) {
		subMessageInfoService.deleteById(bzwkSvcKeyName);
	}

	public Map<String, List<ComboVo>> selectCombo() {

		// 전문요청구분
		List<ComboVo> listReqRes = comboService.getFromCode("REQRES_TYPE");

		// 내외부구분코드
		List<ComboVo> listStndTelgmWtinExtnlDstcd = comboService.getFromCode("STD_INOUT_TYPE");

		// EAI내외부구분코드
		List<ComboVo> listEAIStndtelgmwtinextnldstCd = comboService.getFromCode("EAI_INOUT_TYPE");

		// 취소구분코드
		List<ComboVo> listTrstdidfrCd = comboService.getFromCode("TRSTDIDFR_CD");

		Map<String, List<ComboVo>> map = new HashMap<>();

		map.put("reqResList", listReqRes);
		map.put("stndTelgmWtinExtnlDstcdList", listStndTelgmWtinExtnlDstcd);
		map.put("eaiStndtelgmwtinextnldstCdList", listEAIStndtelgmwtinextnldstCd);
		map.put("trstdidfr_CdList", listTrstdidfrCd);

		return map;
	}

	public Map<String, List<ComboVo>> selectDetailCombo() {

		// 전문요청구분
		List<ComboVo> listReqRes = comboService.getFromCode("REQRES_TYPE");

		// 내외부구분코드
		List<ComboVo> listStndTelgmWtinExtnlDstcd = comboService.getFromCode("STD_INOUT_TYPE");

		// EAI내외부구분코드
		List<ComboVo> listEAIStndtelgmwtinextnldstCd = comboService.getFromCode("EAI_INOUT_TYPE");

		// 시스템 운영환경 구분코드
		List<ComboVo> listSysOperEvirnDstcd = comboService.getFromCode("SYSTEM_TYPE");

		// 원거래 복원 여부
		List<ComboVo> listOgtranRstrYn = comboService.getFromCode("RECOVER_TYPE");

		// 채널유형코드
		List<ComboVo> listChnlDstcd = comboService.getFromCode("CHNL_DST_CD");

		// 채널상세유형코드
		List<ComboVo> listChnlDvDstcd = comboService.getFromCode("CHNL_DV_DST_CD");

		// 그룹회사코드
		List<ComboVo> listGroupCoCd = comboService.getFromCode("GROUPCOCD");

		// 복합거래요청구분코드
		List<ComboVo> listCmpstrCd = comboService.getFromCode("CMPSTR_CD");

		// 취소구분코드
		List<ComboVo> listTrstdidfrCd = comboService.getFromCode("TRSTDIDFR_CD");

		// 매체구분코드
		List<ComboVo> listMdiadstCd = comboService.getFromCode("MDIADSTCD");

		// 은행코드
		List<ComboVo> listBnkCd = comboService.getFromCode("BNKCD");

		// 입출력구분
		List<ComboVo> listIoCd = comboService.getFromCode("IO_CD");

		// 당타발구분
		List<ComboVo> listDtCd = comboService.getFromCode("DT_CD");

		// 여부(당발응답정상여부)
		List<ComboVo> listYnCd = comboService.getFromCode("YN");

		Map<String, List<ComboVo>> map = new HashMap<>();

		map.put("reqResList", listReqRes);
		map.put("stndTelgmWtinExtnlDstcdList", listStndTelgmWtinExtnlDstcd);
		map.put("eaiStndtelgmwtinextnldstCdList", listEAIStndtelgmwtinextnldstCd);
		map.put("sysOperEvirnDstcdList", listSysOperEvirnDstcd);
		map.put("ogtranRstrYnList", listOgtranRstrYn);
		map.put("chnlDstcdList", listChnlDstcd);
		map.put("chnlDvDstcdList", listChnlDvDstcd);

		map.put("groupCoCdList", listGroupCoCd);
		map.put("cmpstrCdList", listCmpstrCd);
		map.put("trstdidfr_CdList", listTrstdidfrCd);
		map.put("mdiadst_CdList", listMdiadstCd);
		map.put("bnk_CdList", listBnkCd);

		map.put("io_CdList", listIoCd);
		map.put("dt_CdList", listDtCd);
		map.put("yn_CdList", listYnCd);

		return map;
	}

	public void clone(Map<String, Object> paramMap, String bzwkSvcKeyNameClone) {
		// 1.중복체크
		paramMap.put("bzwkSvcKeyName", paramMap.get("bzwkSvcKeyNameClone"));

		SubMessageUI subMessageUi = new SubMessageUI();
		subMessageUi.setBzwkSvcKeyName(bzwkSvcKeyNameClone);

		// 2.등록
		insert(paramMap, subMessageUi);
	}

	public List<SubExtendedColumnDefinitionUI> selectColumnList() {

		List<SubExtendedColumnDefinitionUI> columnDefinitionUIs = subExtendedColumnDefinitionService
				.findAll()
				.stream()
				.map(subExtendedColumnDefinitionUIMapper::toVo)
				.collect(Collectors.toList());

		for (SubExtendedColumnDefinitionUI columnDefinition : columnDefinitionUIs) {
			String comboName = columnDefinition.getComboName();
			if (StringUtils.isNotBlank(comboName)) {
				List<ComboVo> comboList = comboService.getFromCode(comboName);
				columnDefinition.setComboList(comboList);
			}
		}

		return columnDefinitionUIs;
	}
}
