package com.eactive.eai.rms.onl.manage.comm.routing;

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

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.routing.Routing;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.spring.LocaleMessage;
import com.eactive.eai.rms.data.entity.onl.routing.RoutingSearch;
import com.eactive.eai.rms.data.entity.onl.routing.RoutingService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.transformer.function.generic.ToString;

@Service
@Transactional
public class RoutingManService extends BaseService {

	private RoutingUIMapper routingUIMapper;

	private RoutingService routingService;
	
	private LocaleMessage localeMessage;
	
	@Autowired
	public RoutingManService(RoutingUIMapper routingUIMapper, RoutingService routingService, LocaleMessage localeMessage) {
		this.routingUIMapper = routingUIMapper;
		this.routingService = routingService;
		this.localeMessage = localeMessage;
	}

	public Page<RoutingUI> selectList(Pageable pageable, RoutingSearch routingSearch) {
		Page<Routing> page = routingService.findAll(pageable, routingSearch);
		return page.map(routingUIMapper::toVo);
	}

	public RoutingUI selectDetail(String routName) {
		Routing routing = routingService.getById(routName);
		return routingUIMapper.toVo(routing);
	}

	public void insert(RoutingUI routingUI) {
		if (routingService.existsById(routingUI.getRoutName())) {
			throw new BizException(localeMessage.getString("routingDetail.nameExists"));
		}
		Routing routing = routingUIMapper.toEntity(routingUI);
		routingService.save(routing);
	}

	public void update(RoutingUI routingUI) {
		Routing routing = routingService.getById(routingUI.getRoutName());
		routingUIMapper.updateToEntity(routingUI, routing);
		routingService.save(routing);
	}

	public void delete(String routName) {
		routingService.deleteById(routName);
	}
	
	public Map<String, Object>[] selectListToExcel() {
		
		@SuppressWarnings("unchecked")
		Map<String, Object>[] mapArray = routingService.findAll()
			.stream()
			.map(e -> {
				Map<String, Object> map = new HashMap<>();
				map.put("ROUTNAME", e.getRoutname());
				map.put("MOTIVROUTURINAME", e.getMotivrouturiname());
				map.put("NONMOTIVROUTURINAME", e.getNonmotivrouturiname());
				map.put("LAYERDSTCD", e.getLayerdstcd());
				return map;
			}).toArray(HashMap[]::new);
		
		return mapArray;
	}

}
