package com.njcn.serviceimpl.advanced;

import com.njcn.mapper.user.TfLgPloyAssMapper;
import com.njcn.pojo.advanced.EntityLogic;
import com.njcn.pojo.user.TfLgPloyAss;
import com.njcn.service.advanced.TransformerOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TransformerOperationServiceImpl implements TransformerOperationService {

	@Autowired
	private TfLgPloyAssMapper tfLgPloyAssMapper;

	@Override
	public List<TfLgPloyAss> getTflgPloyAss() {
		return tfLgPloyAssMapper.getTfLgPloyAss();
	}

	@Override
	public List<EntityLogic> getLogic() {
		return tfLgPloyAssMapper.getLogic();
	}

	/**
	 * 抽取物理隔绝信息并放入map集合中，表示该物理分割上有多少变压器
	 * 例如{{1,{1,2,3...}},{2,{7,8,9...}}}
	 * 地区编码为1,2
	 * 变压器编码为1,2,3,4....
	 */
	public Map<String,List<String>> getTflgPloyInfo(){
		List<TfLgPloyAss> list = getTflgPloyAss();

		if(list.size() > 0){
			Iterator<String> iterator = getAreaInfo(list).iterator();
			Map<String, List<String>> map = new HashMap<String, List<String>>();

			while(iterator.hasNext()){
				List<String> listTransformer = new ArrayList<String>();
				String areaString = iterator.next();

				for(TfLgPloyAss tfLgPloyAss : list){
					if(tfLgPloyAss.gettPIndex().equals(areaString)){
						listTransformer.add(tfLgPloyAss.getTfIndex());
					}
				}

				map.put(areaString, listTransformer); //第一个参数变压器策略guid，对应的变压器列表
			}

			return map;
		}

		return null;
	}

	/**
	 * 抽取物理隔绝信息与母线的关系并放入map集合中
	 * 与getTflgPloyInfo()方法功能类似
	 */
	public Map<String, List<Integer>> getLogicInfo(List<EntityLogic> list){
		if(list.size() > 0){
			Iterator<String> iterator = getAreaInfo(list).iterator();
			Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

			while(iterator.hasNext()){
				List<Integer> listLogic = new ArrayList<Integer>();
				String areaString = iterator.next();

				for(EntityLogic entityLogic : list){
					if(entityLogic.gettPIndex().equals(areaString)){
						listLogic.add(entityLogic.getNodeBefore());
						listLogic.add(entityLogic.getNodeNext());
					}
				}

				//去除list中重复数据
				Set<Integer> set = new TreeSet<Integer>(listLogic);
				map.put(areaString, new ArrayList<Integer>(set));
			}

			return map;
		}

		return null;
	}

	/**
	 * 获取物理隔绝编码信息
	 * 供getInfo()、getLogicInfo()方法使用
	 * 先从list数组中去重，然后获取物理隔绝编码
	 */
	public <T> Set<String>  getAreaInfo(List<T> list){
		Set<T> set = new HashSet<T>(list);
		Iterator<T> iterator = set.iterator();
		Set<String> setReturn = new HashSet<String>();

		while(iterator.hasNext()){
			Object object = iterator.next();

			if(object instanceof TfLgPloyAss){
				setReturn.add(((TfLgPloyAss)object).gettPIndex());
				continue;
			}

			setReturn.add(((EntityLogic)object).gettPIndex());
		}

		return setReturn;
	}
}
