package com.eactive.eai.rms.common.acl.bizKeyTran;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.man.bizKeyTran.BizKeyTran;
import com.eactive.eai.rms.data.entity.man.bizKeyTran.BizKeyTranService;
import com.eactive.eai.rms.onl.common.exception.BizException;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class BizKeyTranManService extends BaseService {

	@Autowired
	private BizKeyTranService bizKeyTranService;

	@Autowired
	private BizKeyTranUIMapper bizKeyTranUIMapper;

	public Page<BizKeyTranUI> selectList(Pageable pageable, BizKeyTranUI bizKeyTranUI) {
		Page<BizKeyTran> page = bizKeyTranService.findAll(pageable, bizKeyTranUI);
		return page.map(bizKeyTranUIMapper::toVo);
	}

	public BizKeyTranUI selectDetail(String eaiBzwkDstcd) {
		BizKeyTran bizKeyTran = bizKeyTranService.getById(eaiBzwkDstcd);
		return bizKeyTranUIMapper.toVo(bizKeyTran);
	}

	public void insert(BizKeyTranUI bizKeyTranUI) {
		if (bizKeyTranService.existsById(bizKeyTranUI.getEaiBzwkDstcd())) {
			throw new BizException("중복된 업무구분코드가 존재합니다.");
		}
		BizKeyTran bizKeyTran = bizKeyTranUIMapper.toEntity(bizKeyTranUI);
		bizKeyTranService.save(bizKeyTran);
	}

	public void update(BizKeyTranUI bizKeyTranUI) {
		BizKeyTran bizKeyTran = bizKeyTranService.getById(bizKeyTranUI.getEaiBzwkDstcd());
		bizKeyTranUIMapper.updateToEntity(bizKeyTranUI, bizKeyTran);
		bizKeyTranService.save(bizKeyTran);
	}

	public void delete(String eaiBzwkDstcd) {
		bizKeyTranService.deleteById(eaiBzwkDstcd);
	}

	public String selectBizKeyForApCode(String eaiBzwkDstcd) {
		Optional<BizKeyTran> bizKeyTran = bizKeyTranService.findById(eaiBzwkDstcd);
		return bizKeyTran.map(BizKeyTran::getApcode).orElse(eaiBzwkDstcd);
	}

	public Map<String, Object>[] selectListToExcel() {
		@SuppressWarnings("unchecked")
		Map<String, Object>[] mapArray = bizKeyTranService.findAll(Sort.by("eaibzwkdstcd")).stream().map(e -> {
			Map<String, Object> map = new HashMap<>();
			map.put("EAIBZWKDSTCD", e.getEaibzwkdstcd());
			map.put("APCODE", e.getApcode());
			return map;
		}).toArray(HashMap[]::new);
		return mapArray;
	}

}
