package com.huatek.busi.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.huatek.busi.dao.BusiStabilityDao;
import com.huatek.busi.entity.BusiStability;
import com.huatek.busi.entity.BusiStabilityItremVo;
import com.huatek.busi.mapper.BusiStabilityMapper;
import com.huatek.busi.service.BusiStabilityService;
import com.huatek.busi.service.arrester.LightningrodImService;
import com.huatek.busi.service.capacitance.CapacitanceEquipmentImService;
import com.huatek.busi.service.gis.GisSf6PressureService;
import com.huatek.busi.service.transformer.TransformerEpaDataOriginService;
import com.huatek.busi.service.transformer.TransformerIcgeService;
import com.huatek.busi.util.AlgorithmSingleton;
import com.huatek.busi.vo.BusiStabilityIndexVo;
import com.huatek.busi.vo.BusiStabilityVo;
import com.huatek.busi.vo.stability.BusiCapacitanceEquipmentImStabilityVo;
import com.huatek.busi.vo.stability.BusiLightningrodimStabilityVo;
import com.huatek.busi.vo.stability.BusiOilStabilityVo;
import com.huatek.busi.vo.stability.BusiSF6StabilityVo;
import com.huatek.busi.vo.stability.CapacitanceEquipmentImStabilityVo;
import com.huatek.busi.vo.stability.IcgeStabilityVo;
import com.huatek.busi.vo.stability.LightningrodImStabilityVo;
import com.huatek.busi.vo.stability.OilStabilityVo;
import com.huatek.busi.vo.stability.SF6StabilityVo;

/**
 * 稳定性指标 ServiceImpl
 *
 * @author anker_cheng
 * @date Jul 29, 2019 2:13:59 PM
 */
@Component
@Service(interfaceClass = BusiStabilityService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiStabilityServiceImpl implements BusiStabilityService {

	protected final Logger logger = LoggerFactory.getLogger(BusiStabilityServiceImpl.class);

	@Autowired
	private BusiStabilityMapper busiStabilityMapper;

	@Autowired
	private BusiStabilityDao busiStabilityDao;

	@Autowired
	private TransformerIcgeService transformerIcgeService;

	/** @Fields lightningrodImService : 避雷器服务 */
	@Autowired
	private LightningrodImService lightningrodImService;

	/** @Fields capacitanceEquipmentImService : 容性服务 */
	@Autowired
	private CapacitanceEquipmentImService capacitanceEquipmentImService;
	
	@Autowired
	private GisSf6PressureService gisSf6PressureService;
	
	/** @Fields transformerEpaDataOriginService :原始数据服务 */
    @Autowired
    private TransformerEpaDataOriginService transformerEpaDataOriginService;

	@Override
	public Boolean insertIegcBusiStability(BusiStabilityVo vo) {
		List<BusiStabilityItremVo> item = vo.getList();
		if (item.size() < 6) {
			return false;
		}
		String sensorCode = vo.getSensorCode();
		String indexType = vo.getIndexType();
		BusiStability entity = this.buildData(sensorCode, indexType);
		String setIegcStability = setIegcStability(item);
		entity.setStabilityIndex(setIegcStability);
		busiStabilityDao.saveOrUpdate(entity);
		return true;
	}

	@Override
	public Boolean insertLightningrodImStability(BusiLightningrodimStabilityVo vo) {
		List<LightningrodImStabilityVo> item = vo.getList();
		if (item.size() < 6) {
			return false;
		}
		String sensorCode = vo.getSensorCode();
		String indexType = vo.getIndexType();
		BusiStability entity = this.buildData(sensorCode, indexType);
		entity.setStabilityIndex(setLightningrodImStability(item));
		busiStabilityDao.saveOrUpdate(entity);
		return true;
	}

	
	
	@Override
	public Boolean insertCapacitanceImStability(BusiCapacitanceEquipmentImStabilityVo vo) {
		List<CapacitanceEquipmentImStabilityVo> item = vo.getList();
		if (item.size() < 6) {
			return false;
		}
		String sensorCode = vo.getSensorCode();
		String indexType = vo.getIndexType();
		BusiStability entity = this.buildData(sensorCode, indexType);
		entity.setStabilityIndex(setCapacitanceImStability(item));
		busiStabilityDao.saveOrUpdate(entity);
		return true;
	}
	

	@Override
	public Boolean insertSF6Stability(BusiSF6StabilityVo vo) {
		List<SF6StabilityVo> item = vo.getList();
		if (item.size() < 6) {
			return false;
		}
		String sensorCode = vo.getSensorCode();
		String indexType = vo.getIndexType();
		BusiStability entity = this.buildData(sensorCode, indexType);
		entity.setStabilityIndex(setsSF6Stability(item));
		busiStabilityDao.saveOrUpdate(entity);
		return true;
	}

	private String setsSF6Stability(List<SF6StabilityVo> item) {
		List<Double> list = new ArrayList<>();
			// 压力
		item.forEach(it ->{
			list.add(Double.valueOf(it.getPressure()));
		});
		String result = AlgorithmSingleton.getInstance().calcStability(list);		
		Map<String, String> map = new HashMap<>();
		map.put("pressure", result);
		return JSONObject.toJSONString(map);
				
	}

	private String setCapacitanceImStability(List<CapacitanceEquipmentImStabilityVo> list) {
		String capacitance = this.calcCapacitanceImStability("1", list);
//		String totalCurrent = this.calcCapacitanceImStability("2", list);
		String lossFactor = this.calcCapacitanceImStability("3", list);
		Map<String, String> map = new HashMap<>();
		map.put("capacitance", capacitance);
		map.put("lossFactor", lossFactor);
		//map.put("totalCurrent", totalCurrent);
		return JSONObject.toJSONString(map);
	}

	private String calcCapacitanceImStability(String type, List<CapacitanceEquipmentImStabilityVo> item) {
		List<Double> list = new ArrayList<>();
		if (type.equals("1")) {
			// 电容量(pF)
			item.forEach(it -> {
				list.add(Double.valueOf(it.getCapacitance()));
			});
		} else if (type.equals("2")) {
			// 泄漏电流(mA)
			item.forEach(it -> {
				list.add(Double.valueOf(it.getTotalCurrent()));
			});
		}else if(type.equals("3")){
			// 介质损耗因数
			item.forEach(it -> {
				list.add(Double.valueOf(it.getLossFactor()));
			});
		}
		String result = AlgorithmSingleton.getInstance().calcStability(list);
		return result;
		
	}

	private BusiStability buildData(String sensorCode, String indexType) {
		BusiStability entity = busiStabilityMapper.selectBySensorCodeAndType(sensorCode, indexType);
		if (null == entity) {
			entity = new BusiStability();
			entity.setIndexType(indexType);
			entity.setSensorCode(sensorCode);
			entity.setCreateTime(LocalDateTime.now());
		}
		return entity;
	}

	private String setLightningrodImStability(List<LightningrodImStabilityVo> list) {
		String resistiveCurrent = this.calcLightningrodImStability("1", list);
		String totalCurrent = this.calcLightningrodImStability("2", list);
		Map<String, String> map = new HashMap<>();
		map.put("resistiveCurrent", resistiveCurrent);
		map.put("totalCurrent", totalCurrent);
		return JSONObject.toJSONString(map);
	}

//	private String calcIegcStability(List<IcgeStabilityVo> item) {
//		List<Double> list = new ArrayList<>();
//		item.forEach(it -> {
//			list.add(Double.valueOf(it.getTotalCoreCurrent()));
//		});
//		String result = AlgorithmSingleton.getInstance().calcStability(list);
//		return result;
//	}

	private String setIegcStability(List<BusiStabilityItremVo> item) {
		List<Double> list = new ArrayList<>();
		item.forEach(it -> {
			list.add(Double.valueOf(it.getValue()));
		});
		String result = AlgorithmSingleton.getInstance().calcStability(list);
		Map<String, String> map = new HashMap<>();
		map.put("totalCurrent", result);
		return JSONObject.toJSONString(map);
	}

	private String calcLightningrodImStability(String type, List<LightningrodImStabilityVo> item) {
		List<Double> list = new ArrayList<>();
		if (type.equals("1")) {
			// 阻性电流 (mA)
			item.forEach(it -> {
				list.add(Double.valueOf(it.getResistiveCurrent()));
			});
		} else if (type.equals("2")) {
			// 全电流 (mA)
			item.forEach(it -> {
				list.add(Double.valueOf(it.getTotalCurrent()));
			});
		}
		String result = AlgorithmSingleton.getInstance().calcStability(list);
		return result;
	}

	@Override
	public List<BusiStabilityIndexVo> findBySensorCode(String sensorCode) {
		List<BusiStabilityIndexVo> indexlist = new ArrayList<>();
		List<BusiStability> list = busiStabilityMapper.selectBySensorCode(sensorCode);
		list.forEach(item -> {
			BusiStabilityIndexVo vo = new BusiStabilityIndexVo();
			vo.setIndexType(item.getIndexType());
			vo.setStabilityIndex(item.getStabilityIndex());
			indexlist.add(vo);
		});
		return indexlist;
	}

    @Override
    public Map<String, Object> findStabilityMapBySensorCode(String sensorCode) {
        Map<String, Object> stabilityMap = Maps.newLinkedHashMapWithExpectedSize(4);
        stabilityMap.put("0", "");
        stabilityMap.put("1", "");
        stabilityMap.put("2", "");
        stabilityMap.put("3", "");
        List<BusiStabilityIndexVo> stabilityList = findBySensorCode(sensorCode);
        if(CollectionUtils.isEmpty(stabilityList)) {
            return stabilityMap;
        }
        for (BusiStabilityIndexVo vo : stabilityList) {
            String stabilityIndex = vo.getStabilityIndex();
            stabilityMap.put(vo.getIndexType(), JSONObject.parseObject(stabilityIndex, Map.class));
        }
        return stabilityMap;
    }

	@Override
	public List<?> getEquipmentData(String sensorCode, String status, String type, LocalDateTime begin,
			LocalDateTime end) {
		// 类别: 1-铁芯 2-夹件 3-避雷器 4-容性 5-SF6 6-套管
		if (type.equals("1")) {
			List<IcgeStabilityVo> list = transformerIcgeService.getByStatus(sensorCode, status, "1", begin, end);
			return list;
		} else if (type.equals("2")) {
			List<IcgeStabilityVo> list = transformerIcgeService.getByStatus(sensorCode, status, "2", begin, end);
			return list;
		} else if (type.equals("3")) {
			List<LightningrodImStabilityVo> list = lightningrodImService.getByStatus(sensorCode, status, begin, end);
			return list;
		} else if (type.equals("4")) {
			List<CapacitanceEquipmentImStabilityVo> list = capacitanceEquipmentImService.getByStatus(sensorCode, status, begin, end);
			return list ;
		} else if (type.equals("5")) {
			List<SF6StabilityVo> list = gisSf6PressureService.getByStatus(sensorCode, status, begin, end);
			return list ;
		} else if (type.equals("6")) {

		}else if(type.equals("7")){
			List<OilStabilityVo> list =transformerEpaDataOriginService.getByStatus(sensorCode, begin, end);
//			DecimalFormat dft = new DecimalFormat("0.0000");
			list.stream().forEach(oilInfo ->{
				if(oilInfo.getC2h2().contains("0E")){
					oilInfo.setC2h2("0");
				}
				else
				{
					oilInfo.setC2h2(new BigDecimal(oilInfo.getC2h2()).toString());
				}
				
				if(oilInfo.getH2().contains("0E")){
					oilInfo.setH2("0");
				}
				else
				{
					oilInfo.setH2(new BigDecimal(oilInfo.getH2()).toString());
				}
				
				if(oilInfo.getCh4().contains("0E")){
					oilInfo.setCh4("0");
				}
				else
				{
					oilInfo.setCh4(new BigDecimal(oilInfo.getCh4()).toString());
				}
				
				
				if(oilInfo.getC2h4().contains("0E")){
					oilInfo.setC2h4("0");
				}
				else
				{
					oilInfo.setC2h4(new BigDecimal(oilInfo.getC2h4()).toString());
				}
				
				if(oilInfo.getC2h6().contains("0E")){
					oilInfo.setC2h6("0");
				}
				else
				{
					oilInfo.setC2h6(new BigDecimal(oilInfo.getC2h6()).toString());
				}
				
				
				if(oilInfo.getCo().contains("0E")){
					oilInfo.setCo("0");
				}
				else
				{
					oilInfo.setCo(new BigDecimal(oilInfo.getCo()).toString());
				}
				
				if(oilInfo.getCo2().contains("0E")){
					oilInfo.setCo2("0");
				}
				else
				{
					oilInfo.setCo2(new BigDecimal(oilInfo.getCo2()).toString());
				}
				if(oilInfo.getO2().contains("0E")){
					oilInfo.setO2("0");
				}
				else
				{
					oilInfo.setO2(new BigDecimal(oilInfo.getO2()).toString());
				}
				
				if(oilInfo.getN2().contains("0E")){
					oilInfo.setN2("0");
				}
				else
				{
					oilInfo.setN2(new BigDecimal(oilInfo.getN2()).toString());
				}
				if(oilInfo.getZj().contains("0E")){
					oilInfo.setZj("0");
				}
				else
				{
					oilInfo.setZj(new BigDecimal(oilInfo.getZj()).toString());
				}
				
			});
			return list;
		}
		return null;
	}

	@Override
	public Map<String, Object> getStabilityBySensorCodeAndStatus(String type, String sensorCode, String runState) {
		Map<String, Object> map = new HashMap<String, Object>();
		BusiStability find = this.busiStabilityMapper.selectBySensorCodeAndType(sensorCode, runState);
		// 类别: 1-铁芯 2-夹件 3-避雷器 4-容性 5-SF6 6-套管
		if(null != find){
			String stabilityIndex = find.getStabilityIndex();
			@SuppressWarnings("unchecked")
			Map<String, Object> tmpMap = JSONObject.parseObject(stabilityIndex, Map.class);
			if (type.equals("1")) {
				map.put("totalCurrent",  tmpMap.get("totalCurrent") == null ? "--" : tmpMap.get("totalCurrent"));
			} else if (type.equals("2")) {
				map.put("totalCurrent",  tmpMap.get("totalCurrent")== null ? "--" : tmpMap.get("totalCurrent"));
			} else if (type.equals("3")) {
				map.put("resistiveCurrent",  tmpMap.get("resistiveCurrent")== null ? "--" : tmpMap.get("resistiveCurrent"));
				map.put("totalCurrent",  tmpMap.get("totalCurrent")== null ? "--" : tmpMap.get("totalCurrent"));
			} else if (type.equals("4")) {
				map.put("capacitance",  tmpMap.get("capacitance")== null ? "--" : tmpMap.get("capacitance"));
				map.put("lossFactor",  tmpMap.get("lossFactor")== null ? "--" : tmpMap.get("lossFactor"));
			} else if (type.equals("5")) {
				map.put("pressure", tmpMap.get("pressure")== null ? "--" : tmpMap.get("pressure"));
			} else if (type.equals("6")) {
				
			}
		}else{
			if (type.equals("1")) {
				map.put("totalCurrent", "--");
			} else if (type.equals("2")) {
				map.put("totalCurrent", "--");
			} else if (type.equals("3")) {
				map.put("resistiveCurrent", "--");
				map.put("totalCurrent", "--");
			} else if (type.equals("4")) {
				map.put("capacitance", "--");
				map.put("lossFactor", "--");
			} else if (type.equals("5")) {
				map.put("pressure", "--");
			} else if (type.equals("6")) {
				
			}
		}
		return map ;
	}

    @Override
    public Map<String, Object> getStabilityBySensorCodeAndStatus(String sensorCode, String runState) {
        BusiStability find = this.busiStabilityMapper.selectBySensorCodeAndType(sensorCode, runState);
        if (find == null) {
            return null;
        }
        @SuppressWarnings("unchecked")
        Map<String, Object> tmpMap = JSONObject.parseObject(find.getStabilityIndex(), Map.class);
        return tmpMap;
    }

    @Override
    public BusiStabilityIndexVo findStabilityMapByCondition(String sensorCode, String indexType) {         
         BusiStabilityIndexVo vo = new BusiStabilityIndexVo();
         BusiStability busiStability = busiStabilityMapper.findStabilityMapByCondition(sensorCode,indexType);
         if(busiStability != null)
         {
             vo.setIndexType(busiStability.getIndexType());
             vo.setStabilityIndex(busiStability.getStabilityIndex());
         }
         return vo; 
    }
    
    @Override
	public Boolean insertOilStability(BusiOilStabilityVo vo) {
		List<OilStabilityVo> item = vo.getList();
		if (item.size() < 4) {
			return false;
		}
		String sensorCode = vo.getSensorCode();
		BusiStability entity = this.buildData(sensorCode, "0");
		entity.setStabilityIndex(setsOilStability(item));
		busiStabilityDao.saveOrUpdate(entity);
		return true;
	}

	private String setsOilStability(List<OilStabilityVo> items) {
		 Map<String, String> map = new HashMap<>();
		List<Double> h2list = new ArrayList<>();
		List<Double> colist = new ArrayList<>();
		List<Double> co2list = new ArrayList<>();
		List<Double> ch4list = new ArrayList<>();
		List<Double> c2h2list = new ArrayList<>();
		List<Double> c2h4list = new ArrayList<>();
		List<Double> c2h6list = new ArrayList<>();
		List<Double> n2list = new ArrayList<>();
		List<Double> o2list = new ArrayList<>();
		List<Double> h2olist = new ArrayList<>();
		List<Double> zjlist = new ArrayList<>();
		items.forEach(item ->{
			h2list.add(Double.valueOf(item.getH2()));
			colist.add(Double.valueOf(item.getCo()));
			co2list.add(Double.valueOf(item.getCo2()));
			ch4list.add(Double.valueOf(item.getCh4()));
			
			c2h2list.add(Double.valueOf(item.getC2h2()));
			c2h4list.add(Double.valueOf(item.getC2h4()));
			c2h6list.add(Double.valueOf(item.getC2h6()));
			
			n2list.add(Double.valueOf(item.getN2()));
			o2list.add(Double.valueOf(item.getO2()));
			h2olist.add(Double.valueOf(item.getH2o()));
			zjlist.add(Double.valueOf(item.getZj()));
		});
		
		String h2 = calc(h2list);
		String co = calc(colist);
		String co2 = calc(co2list);
		String ch4 = calc(ch4list);
		String c2h2 = calc(c2h2list);
		String c2h4 = calc(c2h4list);
		String c2h6 = calc(c2h6list);
		String n2 = calc(n2list);
		String o2 = calc(o2list);
		String h2o = calc(h2olist);
		String zj = calc(zjlist);
		
		map.put("h2", h2);
		map.put("co", co);
		map.put("co2", co2);
		map.put("ch4", ch4);
		
		map.put("c2h2", c2h2);
		map.put("c2h4", c2h4);
		map.put("c2h6", c2h6);
		
		map.put("n2", n2);
		map.put("o2", o2);
		map.put("h2o", h2o);
		map.put("zj", zj);
		return JSONObject.toJSONString(map);
	}
	
	private String calc (List<Double> list){
		return AlgorithmSingleton.getInstance().calcStability(list);
	}
}