package com.eactive.eai.rms.onl.manage.rule.layout;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutItemEntity;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutItemEntityId;
import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
import com.eactive.eai.rms.data.entity.onl.bzwkdstcd.UserBusinessService;
import com.eactive.eai.rms.data.entity.onl.layout.LayoutItemEMSRepository;
import com.eactive.eai.rms.data.entity.onl.layout.LayoutService;
import com.eactive.eai.rms.onl.manage.rule.layoutsync.LayoutSyncVo;

@Repository("layoutDao")
@SuppressWarnings("unchecked")
public class LayoutDao extends SqlMapClientTemplateDao {

	private static final Logger logger = Logger.getLogger(LayoutDao.class);
	private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

	@Autowired
	private LayoutService layoutService;

	@Autowired
	private LayoutItemEMSRepository layoutItemRepository;

	@Autowired
	private UserBusinessService userBusinessService;

	public int selectListCount(HashMap param) throws Exception {
		List<String> currentUserBusiness = userBusinessService.getCurrentUserBusinessCodes();
		long count = layoutService.getJPAQueryFactory()
			.selectFrom(com.eactive.eai.data.entity.onl.transformer.layout.QLayoutEntity.layoutEntity)
			.where(com.eactive.eai.data.entity.onl.transformer.layout.QLayoutEntity.layoutEntity.eaibzwkdstcd.in(currentUserBusiness))
			.fetchCount();
		return (int) count;
	}

	public HashMap selectDetail(HashMap param) throws Exception {
		String loutName = (String) param.get("loutName");
		Optional<LayoutEntity> optionalEntity = layoutService.findById(loutName);

		if (!optionalEntity.isPresent()) {
			return null;
		}

		LayoutEntity entity = optionalEntity.get();
		HashMap<String, Object> result = new HashMap<>();
		result.put("LOUTNAME", entity.getLoutname());
		result.put("LOUTPTRNNAME", entity.getLoutptrnname());
		result.put("LOUTDESC", entity.getLoutdesc());
		result.put("LASTAMNDHMS", entity.getLastamndhms() != null ? entity.getLastamndhms().format(DATETIME_FORMATTER) : null);
		result.put("EAIBZWKDSTCD", entity.getEaibzwkdstcd());
		result.put("UAPPLNAME", entity.getUapplname());
		result.put("SYSINTFACNAME", entity.getSysintfacname());

		return result;
	}

	public void insert(HashMap paramMap) throws Exception {
		LayoutEntity entity = new LayoutEntity();
		entity.setLoutname((String) paramMap.get("loutName"));
		entity.setLoutptrnname((String) paramMap.get("loutPtrnName"));
		entity.setLoutdesc((String) paramMap.get("loutDesc"));
		entity.setEaibzwkdstcd((String) paramMap.get("eaiBzwkDstcd"));
		entity.setUapplname((String) paramMap.get("uapplName"));
		entity.setSysintfacname((String) paramMap.get("sysIntfacName"));
		entity.setEaisevrdstcd((String) paramMap.get("eaiSevrDstcd"));
		entity.setUseyn((String) paramMap.get("useYn"));

		layoutService.save(entity);
	}

	public void update(HashMap paramMap) throws Exception {
		String loutName = (String) paramMap.get("loutName");
		Optional<LayoutEntity> optionalEntity = layoutService.findById(loutName);

		if (!optionalEntity.isPresent()) {
			throw new Exception("Layout not found: " + loutName);
		}

		LayoutEntity entity = optionalEntity.get();
		entity.setLoutptrnname((String) paramMap.get("loutPtrnName"));
		entity.setLoutdesc((String) paramMap.get("loutDesc"));
		entity.setEaibzwkdstcd((String) paramMap.get("eaiBzwkDstcd"));
		entity.setUapplname((String) paramMap.get("uapplName"));
		entity.setSysintfacname((String) paramMap.get("sysIntfacName"));

		layoutService.save(entity);
	}

	public void delete(HashMap paramMap) throws Exception {
		String loutName = (String) paramMap.get("loutName");
		layoutService.deleteById(loutName);
	}

	public int insertItem(HashMap<String, Object> param) {
		LayoutItemEntity entity = new LayoutItemEntity();

		// Composite Key 설정
		LayoutItemEntityId id = new LayoutItemEntityId();
		id.setLoutname((String) param.get("loutName"));
		id.setLoutitemname((String) param.get("loutItemName"));
		id.setLoutitemserno((Integer) param.get("loutItemSerno"));
		entity.setId(id);

		// 필드 설정
		entity.setLoutitemidname((Integer) param.get("loutItemIDName"));
		entity.setParntloutitemidname((Integer) param.get("parntLoutItemIDName"));
		entity.setLoutitemdesc((String) param.get("loutItemDesc"));
		entity.setLoutitemnodeptrnidname((Integer) param.get("loutItemNodePtrnIDName"));
		entity.setLoutitemptrnidname((Integer) param.get("loutItemPtrnIDName"));
		entity.setLoutitempathname((String) param.get("loutItemPathName"));
		entity.setLoutitemlencnt((Integer) param.get("loutItemLenCnt"));
		entity.setLoutitemrefinfo((String) param.get("loutItemRefInfo"));
		entity.setLoutitemrefinfo2((String) param.get("loutItemRefInfo2"));
		entity.setLoutitemoccurptrndstcd((String) param.get("loutItemOccurPtrnDstcd"));
		entity.setLoutitemmaxoccurnoitm((Integer) param.get("loutItemMaxOccurNoitm"));
		entity.setLoutitemminoccurnoitm((Integer) param.get("loutItemMinOccurNoitm"));
		entity.setLoutitembascval((String) param.get("loutItemBascVal"));
		entity.setLoutitemmskyn((String) param.get("loutItemMskYn"));
		entity.setLoutitemmaskoffset((Integer) param.get("loutItemMaskOffset"));
		entity.setLoutitemmasklength((Integer) param.get("loutItemMaskLength"));
		entity.setLoutdptcnt((Integer) param.get("lyoutDptCnt"));
		entity.setDecptlencnt((Integer) param.get("decptLenCnt"));
		entity.setLoutitemrefptrnidname((String) param.get("lyoutItemRefPtrnIDName"));

		layoutItemRepository.save(entity);
		return 1;
	}

	public int deleteItemAll(HashMap<String, Object> param) {
		String loutName = (String) param.get("loutName");
		return layoutItemRepository.deleteByLoutname(loutName);
	}

	public List<HashMap<String, Object>> selectListAll(HashMap<String, Object> param) {
		List<String> currentUserBusiness = userBusinessService.getCurrentUserBusinessCodes();

		List<LayoutEntity> entities = layoutService.getJPAQueryFactory()
			.selectFrom(com.eactive.eai.data.entity.onl.transformer.layout.QLayoutEntity.layoutEntity)
			.where(com.eactive.eai.data.entity.onl.transformer.layout.QLayoutEntity.layoutEntity.eaibzwkdstcd.in(currentUserBusiness))
			.orderBy(com.eactive.eai.data.entity.onl.transformer.layout.QLayoutEntity.layoutEntity.loutname.asc())
			.fetch();

		return entities.stream().map(entity -> {
			HashMap<String, Object> map = new HashMap<>();
			map.put("LOUTNAME", entity.getLoutname());
			map.put("LOUTDESC", entity.getLoutdesc());
			map.put("LOUTPTRNNAME", entity.getLoutptrnname());
			return map;
		}).collect(Collectors.toList());
	}

	public List<LayoutSyncVo> getLayoutXMLList(HashMap<String, String> param) {
		return template.queryForList("Layout.selectLayoutXMLList", param);
	}

	public List<LayoutSyncVo> getMigrationLayout(HashMap<String, String> param) {
		return template.queryForList("Layout.selectMigrationLayout", param);
	}

	public List<HashMap<String, String>> getLayoutMappingXMLList(HashMap<String, String> param) {
		return template.queryForList("Layout.selectLayoutMappingXMLList", param);
	}

	public void addLayoutMappingSyncLog(HashMap<String, String> param) {
		template.insert("Layout.insertMappingSyncLog", param);
	}

	public void recvLayoutMappingSyncLog(HashMap<String, String> param) {
		template.insert("Layout.updateMappingSyncLog", param);
	}

	public void addLayoutSyncLog(HashMap<String, String> param) {
		template.insert("Layout.insertLayoutSyncLog", param);
	}

	// Layout Popup
	public int selectListCountPop(HashMap param) throws Exception {
		return (Integer) template.queryForObject("Layout.selectListCountPop", param);
	}

	// Layout Popup
	public List selectListPop(HashMap param) throws Exception {
		return template.queryForList("Layout.selectListPop", param);
	}

	public List<HashMap> selectLayout(HashMap params) {
		// params에서 검색 조건 추출
		List<LayoutEntity> entities = layoutService.findAll();

		return entities.stream().map(entity -> {
			HashMap<String, Object> map = new HashMap<>();
			map.put("LOUTNAME", entity.getLoutname());
			map.put("LOUTPTRNNAME", entity.getLoutptrnname());
			map.put("LOUTDESC", entity.getLoutdesc());
			map.put("LASTAMNDHMS", entity.getLastamndhms() != null ? entity.getLastamndhms().format(DATETIME_FORMATTER) : null);
			map.put("EAIBZWKDSTCD", entity.getEaibzwkdstcd());
			map.put("UAPPLNAME", entity.getUapplname());
			map.put("SYSINTFACNAME", entity.getSysintfacname());
			return map;
		}).collect(Collectors.toList());
	}
}
