package com.huatek.busi.service.impl.gis;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
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.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huatek.busi.common.BusiConstant.EqType;
import com.huatek.busi.common.BusiConstant.GzType;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.SiteConstants.GisTreeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.common.util.TimeUtil;
import com.huatek.busi.common.util.Tools;
import com.huatek.busi.dto.EquipmentInfoDto;
import com.huatek.busi.dto.GisSf6PressureStatisticsDto;
import com.huatek.busi.dto.curve.BaseCurveQueryDto;
import com.huatek.busi.dto.curve.PointItemDto;
import com.huatek.busi.entity.BusiEqmWarning;
import com.huatek.busi.entity.BusiGisSensor;
import com.huatek.busi.entity.BusiOnlineMonitorData;
import com.huatek.busi.entity.BusiSiteTree;
import com.huatek.busi.entity.GisSf6IncreaseRateCache;
import com.huatek.busi.entity.GisSf6Pressure;
import com.huatek.busi.mapper.GisSf6IncreaseRateCacheMapper;
import com.huatek.busi.mapper.GisSf6PressureMapper;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.gis.BusiGisSensorService;
import com.huatek.busi.service.gis.GisSF6ThresholdService;
import com.huatek.busi.service.gis.GisSf6PressureService;
import com.huatek.busi.service.gis.RptGisMonitorSf6Service;
import com.huatek.busi.service.impl.cac.AbstractCacEtlService;
import com.huatek.busi.util.AlgorithmSingleton;
import com.huatek.busi.util.CalcUtil;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.GisSf6PressureStatisticsVo;
import com.huatek.busi.vo.GisSf6PressureVo;
import com.huatek.busi.vo.GisSf6ThresholdVo;
import com.huatek.busi.vo.curve.PointItemVo;
import com.huatek.busi.vo.monitor.BusiOnlineMonitorDataVo;
import com.huatek.busi.vo.stability.SF6StabilityVo;
import com.huatek.busi.vo.warning.BusiGisSf6ItemVo;
import com.huatek.busi.vo.warning.BusiGisSf6ItemVo.BusiGisSf6ItemVoBuilder;
import com.huatek.busi.vo.warning.BusiGisSf6Vo;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 断路器/GIS——SF6气体压力：024004、024005 ServiceImpl
 *
 * @author anker_cheng
 * @date Jun 26, 2019 1:11:48 PM
 */
@Slf4j
@Component
@Service(interfaceClass = GisSf6PressureService.class)
@Transactional(rollbackFor = Exception.class)
public class GisSf6PressureServiceImpl extends AbstractCacEtlService<GisSf6Pressure> implements GisSf6PressureService {
    @Autowired
    private GisSf6PressureMapper gisSf6PressureMapper;
    @Autowired
	private GisSf6IncreaseRateCacheMapper gisSf6IncreaseRateCacheMapper;
    @Reference(check = false)
    private RptGisMonitorSf6Service rptGisMonitorSf6Service;
    @Reference(check = false)
    private GisSF6ThresholdService gisSF6ThresholdService;
    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;
    @Reference(check = false)
    private BusiGisSensorService busiGisSensorService;
    
    
    /** @Fields PRESSURE_VALID : 压力最大有效值*/ 
    public BigDecimal PRESSURE_VALID = new BigDecimal("1200");
    
    /** @Fields MOISTURE_VALID : 微水最大有效值*/ 
    public BigDecimal MOISTURE_VALID = new BigDecimal("1000");
    
    
    /** @Fields VALID : 有效标识 */ 
    public final  String VALID  = "1" ;
    
    /** @Fields INVALID : 无效标识*/ 
    public final String INVALID  = "2" ;

    @Override
    protected void saveHistoryData(GisSf6Pressure cacEntity, EquipmentInfoDto equipmentInfo) {
        String equipmentSensitivity = "--";
        BusiGisSensor sensorInfo = this.getSensorInfo(cacEntity.getSensorId());
        if (null != sensorInfo) {
            String standardPressure = sensorInfo.getStandardPressure();
            try {
                Double standerdPressure = Double.valueOf(standardPressure);
                Double absolutePressure = Double.valueOf(cacEntity.getAbsolutePressure());
                Double temperature = Double.valueOf(cacEntity.getTemperature());
                equipmentSensitivity =
                    AlgorithmSingleton.getInstance().calcSensitivity(temperature, absolutePressure, standerdPressure);
            } catch (Exception e) {
                log.error("计算灵敏度异常:[{}]", e.getMessage());
            }
        }
        // 增加保存灵敏度信息
        cacEntity.setEquipmentSensitivity(equipmentSensitivity);
        // 设置rowkey，导入hbase使用
        cacEntity.setHbaseRowkey(Tools.strReverse(TimeUtil.getTimeStr(cacEntity.getTimeStamp())) + "_"
            + cacEntity.getSensorId() + "_" + TimeUtil.getTimeStr(cacEntity.getTimeStamp()) + "_"
            + cacEntity.getCacMonitorTypeCode() + "_" + cacEntity.getMainTreeId());

        // 设置缺失率
        String standardPressure = "";
        BusiSensorVo sensor = busiGisSensorService.getBusiSensorVo(cacEntity.getSensorId());
        if (sensor != null && sensor.getStandardPressure() != null) {
            standardPressure = sensor.getStandardPressure();
        }
        if (!"".equals(standardPressure) && standardPressure != null) {
            cacEntity.setDailyLeakLate(CalcUtil.calcLoseRate(new BigDecimal(standardPressure.trim()),
                new BigDecimal(cacEntity.getTemperature()), new BigDecimal(cacEntity.getPressure20c())).toString());
        }
        if(StringUtils.isNotEmpty(cacEntity.getPressure20c())){
            //折合20度的压力值
            String res = CalcUtil.pressionInfo(new BigDecimal(standardPressure.trim()),
                    new BigDecimal(cacEntity.getTemperature()), new BigDecimal(cacEntity.getPressure20c())).toString();
            cacEntity.setPressure(res);
            log.info("-----------------gis-sf6标准压力（页面输入值）：" + standardPressure.trim() + ",  报文温度：" + cacEntity.getTemperature() + ",  报文压力：" + cacEntity.getPressure20c() + ",  折合到20度的压力值" + res);
        }else{
  cacEntity.setPressure("");
}

      

        // 压力
        String pressure20c = cacEntity.getPressure20c();
        if(StringUtils.isNoneBlank(pressure20c) && new BigDecimal(pressure20c).compareTo(PRESSURE_VALID) > 0){
        	cacEntity.setValided(INVALID);
        }
        else
        {
        	cacEntity.setValided(VALID);
        }
        super.saveHistoryData(cacEntity, equipmentInfo);
    }

    @Override
    public void saveBusiWarning(GisSf6Pressure cacEntity, String cacMonitorTypeCode, String sensorId,
        EquipmentInfoDto equipmentInfo) {
        // 阈值
        GisSf6ThresholdVo gisThreshold = gisSF6ThresholdService.queryGisSF6Threshold(sensorId);
        if (gisThreshold == null) {
            log.warn("GisSf6ThresholdVo not exist! sensorCode: {}", sensorId);
            return;
        }
        final StringBuilder warningMsg = new StringBuilder();

        
        // 压力
        String pressure20c = cacEntity.getPressure20c();
        // 微水
        String moisture = cacEntity.getMoisture();
        if(StringUtils.isNoneBlank(pressure20c) && new BigDecimal(pressure20c).compareTo(PRESSURE_VALID) > 0){
        	log.error("sensorCode: {},压力值{}无效", sensorId, pressure20c );
        	return ;
        }
        
        // 温度
        BusiGisSf6ItemVoBuilder builder1 = BusiGisSf6ItemVo.builder().phase(cacEntity.getPhase()).name("温度（℃）")
            .collectValue(cacEntity.getTemperature()).thresholdValue(gisThreshold.getSf6wd())
            .warningValue(gisThreshold.getSf6wdWarn()).equipmentSensitivity("--");
        if(isWarning(cacEntity.getTemperature(),gisThreshold.getSf6wdWarn()))
        {
        	  append(warningMsg, format("Sf6温度超标：{}", cacEntity.getTemperature()));
	    	  builder1.thresholdValue(gisThreshold.getSf6wd());
	          builder1.warningValue(gisThreshold.getSf6wdWarn());
        }
        // 微水
		BusiGisSf6ItemVoBuilder builder2 = BusiGisSf6ItemVo.builder().phase(cacEntity.getPhase()).name("微水（μL/L）")
            .collectValue(moisture).thresholdValue(gisThreshold.getSf6wd())
            .warningValue(gisThreshold.getSf6wdWarn()).equipmentSensitivity("--");
         if(isWarning(moisture,gisThreshold.getSf6wsWarn()))
         {
        	 append(warningMsg, format("Sf6微水超标：{}", moisture));
        	 builder2.thresholdValue(gisThreshold.getSf6ws());
             builder2.warningValue(gisThreshold.getSf6wsWarn());
         }
      
         
         /**
          * 计算SF6灵敏度
          */
         String equipmentSensitivity = "--";
         BusiGisSensor sensorInfo = this.getSensorInfo(sensorId);
         String standardPressure="";
         if (null != sensorInfo) {
             standardPressure = sensorInfo.getStandardPressure();
             try {
                 Double standerdPressure = Double.valueOf(standardPressure);
                 Double absolutePressure = Double.valueOf(cacEntity.getAbsolutePressure());
                 Double temperature = Double.valueOf(cacEntity.getTemperature());
                 equipmentSensitivity =
                     AlgorithmSingleton.getInstance().calcSensitivity(temperature, absolutePressure, standerdPressure);
             } catch (Exception e) {
                 log.error("计算灵敏度异常:[{}]", e.getMessage());
             }
         }
         
         /**
          * 折合20度的绝对压力
          */
         String absolutePressure = CalcUtil.pressionInfo(new BigDecimal(standardPressure.trim()),
                 new BigDecimal(cacEntity.getTemperature()), new BigDecimal(cacEntity.getAbsolutePressure())).toString();
         
         
      	BusiGisSf6ItemVoBuilder builder3 = BusiGisSf6ItemVo.builder().phase(cacEntity.getPhase()).name("压力（kPa）")
            .collectValue(pressure20c).thresholdValue(gisThreshold.getSf6wd())
            .warningValue(gisThreshold.getSf6wdWarn()).equipmentSensitivity(equipmentSensitivity);
//         if(isWarning( gisThreshold.getSf6ylWarn(),cacEntity.getPressure20c()))
      	if(isWarning( gisThreshold.getSf6ylWarn(),absolutePressure))
         {
        	append(warningMsg, format("Sf6压力未达标：{}", absolutePressure));
            builder3.alarmValue(pressure20c);
            builder3.thresholdValue(gisThreshold.getSf6yl());
            builder3.warningValue(gisThreshold.getSf6ylWarn());
         }
         
         //告警则保存告警
         if(warningMsg.length() > 0)
         { 
        	 // 保存告警
             BusiEqmWarning busiEqmWarning =
                 newEw(EqType.EQ_TYPE2, GzType.GZ_TYPE5, warningMsg.toString(), cacMonitorTypeCode,"1");
             busiEqmWarning.setWarningTime(cacEntity.getTimeStamp());
             busiEqmWarning.setWarningFlag("1");
             busiEqmWarning = this.buildWarning(busiEqmWarning, equipmentInfo);
             // 保存告警详情
             BusiGisSf6Vo busiGisSf6Vo = new BusiGisSf6Vo();
             busiGisSf6Vo.setEquipmentName(equipmentInfo.getSubEquipmentName());
             busiGisSf6Vo.setList(Arrays.asList(builder1.build(),builder2.build(),builder3.build()));
             busiGisSf6Vo.setCollectDate(cacEntity.getTimeStamp());
             this.buildWarningInfo(busiEqmWarning, JSON.toJSONString(busiGisSf6Vo));
             return;
         }
         
         if(isThreshold(cacEntity.getTemperature(),gisThreshold.getSf6wd(),gisThreshold.getSf6wdWarn()))
 		 {
        	 append(warningMsg, format("SF6温度超标：{}", cacEntity.getTemperature()));
             builder1.alarmValue(cacEntity.getTemperature());
             builder1.thresholdValue(gisThreshold.getSf6wd());
             builder1.warningValue(gisThreshold.getSf6wdWarn());
             
 		 }
         
         if(isThreshold(cacEntity.getMoisture(), gisThreshold.getSf6ws(),gisThreshold.getSf6wsWarn()))
 		 {
        	 append(warningMsg, format("SF6微水超标：{}", cacEntity.getMoisture()));
             builder2.alarmValue(cacEntity.getMoisture());
             builder2.thresholdValue(gisThreshold.getSf6ws());
             builder2.warningValue(gisThreshold.getSf6wsWarn());
 		 }
         
         //折合20度的绝对压力值

//         if(isThreshold(cacEntity.getPressure20c(),  gisThreshold.getSf6ylWarn(),gisThreshold.getSf6yl()))
         if(isThreshold(absolutePressure,  gisThreshold.getSf6ylWarn(),gisThreshold.getSf6yl()))
 		 {
        	 append(warningMsg, format("SF6压力未达标：{}", absolutePressure));
             builder3.alarmValue(cacEntity.getPressure20c());
             builder3.thresholdValue(gisThreshold.getSf6yl());
             builder3.warningValue(gisThreshold.getSf6ylWarn());
 		 }
         
         if(warningMsg.length() > 0)
         {
        	 // 保存告警
             BusiEqmWarning busiEqmWarning =
                 newEw(EqType.EQ_TYPE2, GzType.GZ_TYPE5, warningMsg.toString(), cacMonitorTypeCode,"2");
             busiEqmWarning.setWarningTime(cacEntity.getTimeStamp());
             busiEqmWarning.setWarningFlag("2");
             busiEqmWarning = this.buildWarning(busiEqmWarning, equipmentInfo);
             // 保存告警详情
             BusiGisSf6Vo busiGisSf6Vo = new BusiGisSf6Vo();
             busiGisSf6Vo.setEquipmentName(equipmentInfo.getSubEquipmentName());
             busiGisSf6Vo.setList(Arrays.asList(builder1.build(),builder2.build(),builder3.build()));
             busiGisSf6Vo.setCollectDate(cacEntity.getTimeStamp());
             this.buildWarningInfo(busiEqmWarning, JSON.toJSONString(busiGisSf6Vo));
             return;
         }
         if (warningMsg.length() == 0) {
             return;
         }
    }

    @Override
    public void updateCurrentData(GisSf6Pressure cacEntity, EquipmentInfoDto equipmentInfo) {
        // 设置缺失率
//        String standardPressure = "";
//        BusiSensorVo sensor = busiGisSensorService.getBusiSensorVo(cacEntity.getSensorId());
//        if (sensor != null && sensor.getStandardPressure() != null) {
//            standardPressure = sensor.getStandardPressure();
//        }
        
//        if (!"".equals(standardPressure) && standardPressure != null) {
//            cacEntity.setDailyLeakLate(CalcUtil.calcLoseRate(new BigDecimal(standardPressure.trim()),
//                new BigDecimal(cacEntity.getTemperature()), new BigDecimal(cacEntity.getPressure20c())).toString());
//        }
//        LocalDate localDate = cacEntity.getTimeStamp().toLocalDate().minusDays(1);
        
        LocalDate localDate = cacEntity.getTimeStamp().toLocalDate().minusDays(1);
        GisSf6IncreaseRateCache  sf6IncreaseRate = gisSf6IncreaseRateCacheMapper.getItem(cacEntity.getSensorId(), localDate);
        if(sf6IncreaseRate != null)
        {
        	cacEntity.setDailyLeakLate(sf6IncreaseRate.getIncreasePressure20C());
        }
        String equipmentSensitivity = "--";
        BusiGisSensor sensorInfo = this.getSensorInfo(cacEntity.getSensorId());
        if (null != sensorInfo) {
            String standardPressure = sensorInfo.getStandardPressure();
            try {
                Double standerdPressure = Double.valueOf(standardPressure);
                Double absolutePressure = Double.valueOf(cacEntity.getAbsolutePressure());
                Double temperature = Double.valueOf(cacEntity.getTemperature());
                equipmentSensitivity =AlgorithmSingleton.getInstance().calcSensitivity(temperature, absolutePressure, standerdPressure);
            } catch (Exception e) {
                log.error("计算灵敏度异常:[{}]", e.getMessage());
            }
        }
        // 增加保存灵敏度信息
        cacEntity.setEquipmentSensitivity(equipmentSensitivity);
        rptGisMonitorSf6Service.saveRptGisMonitorSf6(cacEntity);
    }

    /**
     * 返回 aVal.compareTo(bVal)>0的结果，判断aVal是否大于bVal
     * 
     * @param aVal  报文数据
     * @param bVal  阈值
     * @param cVal  预警值
     * @return  0,正常；1预警；2告警
     */
//    private static String gt(String aVal, String bVal,String cVal) {
//    	String flag = "0";
//    	
//    	if (StringUtils.isEmpty(bVal)) {
//    		return "0";
//    	}
//    	//预警
//    	if( DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(bVal)) > 0)
//    	{
//    		if( DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(cVal)) < 0)
//    		{
//    			flag = "2";
//    		}
//    	}
//    	//告警
//    	if(DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(cVal)) > 0)
//    	{
//    		flag = "1";
//    	}
//    	return flag;
//    }

    /**
     * 返回 aVal.compareTo(bVal)>0的结果，判断aVal是否大于bVal
     * 
     * @param aVal  报文数据
     * @param bVal  阈值
     * @param cVal  预警值
     * @return  0,正常；1预警；2告警
     */
//    private static String gtyl(String aVal, String bVal,String cVal) {
//    	String flag = "0";
//    	
//    	if (StringUtils.isEmpty(bVal)) {
//    		return "0";
//    	}
//    	//预警
//    	if( DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(bVal)) < 0)
//    	{
//    		if( DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(cVal)) > 0)
//    		{
//    			flag = "2";
//    		}
//    	}
//    	//告警
//    	if(DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(cVal)) < 0)
//    	{
//    		flag = "1";
//    	}
//    	return flag;
//    }
    
    /**
     * 判断告警
     * 返回 aVal.compareTo(bVal)>0的结果，判断aVal是否大于bVal
     * 
     * @param aVal  报文数据
     * @param bVal  阈值
     */
    private static boolean isWarning(String aVal, String bVal) {
        if (StringUtils.isEmpty(aVal)) {
            return false;
        }
    	if (StringUtils.isEmpty(bVal)) {
    		return false;
    	}
    	return DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(bVal)) > 0;
    }
    
    /**
     * 判断预警
     * 返回 aVal.compareTo(bVal)>0的结果，判断aVal是否大于bVal
     * 
     * @param aVal  报文数据
     * @param bVal  阈值
     * @param cVal  预警值
     * @return  0,正常；1预警；2告警
     */
    private static boolean isThreshold(String aVal, String bVal,String cVal) {
    	boolean flag = false;
        if (StringUtils.isEmpty(aVal)) {
            flag = false;
        }
    	if (StringUtils.isEmpty(bVal)) {
    		flag = false;
    	}
    	//预警
    	if(DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(bVal)) > 0 && DecimalUtil.getVal(aVal).compareTo(DecimalUtil.getVal(cVal)) < 0)
    	{
    		flag = true;
    	}
    	return flag;
    }
    
    @Override
    public Map<String, Object> findCACPageData(Map<String, Object> params) {
        if (params.get("page") != null && params.get("limit") != null) {
            PageHelper.startPage(page(params), limit(params));
        }
        Page<Map<String, Object>> pageInfo = gisSf6PressureMapper.findCACPageData(params);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "", pageInfo.getResult());
    }

    @Override
    public Map<String, Object> exportCacMonitorData(Map<String, Object> mapParams) {
        Map<String, Object> returnMap = new HashMap<>();
        if (mapParams.containsKey("mainTreeId") && StringUtils.isNotEmpty(mapParams.get("mainTreeId") + "")) {
            BusiSiteTree busiSiteTree = busiSiteTreeService.findByPK(mapParams.get("mainTreeId") + "");
            List<GisSf6PressureVo> gisSf6PressureList = gisSf6PressureMapper.exportCacMonitorData(mapParams);
            String replaceRegex = "[\\\\n`~!@#$%^&*()+=|{}':;',\\\\\\\\[\\\\\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
            String treeName = busiSiteTree.getName().replaceAll(replaceRegex, "-");
            returnMap.put("fileName", String.format("%s%s", treeName, "SF6监测数据"));
            returnMap.put("title", String.format("%s%s", treeName, "SF6监测数据"));
            if (gisSf6PressureList.isEmpty()) {
                gisSf6PressureList = new ArrayList<>();
                gisSf6PressureList.add(new GisSf6PressureVo());
            }
            returnMap.put("data", gisSf6PressureList);
        } else {
            throw new RuntimeException("主设备编码不正确");
        }
        return returnMap;
    }

    @Override
    public List<SF6StabilityVo> getByStatus(String sensorCode, String status, LocalDateTime begin, LocalDateTime end) {
        return gisSf6PressureMapper.selectByStatus(sensorCode, status, begin, end);
    }

    @Override
    protected List<Map<String, Object>> queryMonitorDataList(LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> mapList = gisSf6PressureMapper.queryMonitorDataList(startTime, endTime);
        if (!mapList.isEmpty()) {
            for (Map<String, Object> map : mapList) {
                DecimalFormat df = new DecimalFormat("0.00");
                if(map.get("dailyLeakRate") != null)
                {
                	 // 获取前一天的
                	BigDecimal prePression  =  BigDecimal.ZERO;
                    List<Map<String, Object>> listObj = gisSf6PressureMapper.getRecordBySensorCode(map.get("sensorCode").toString(), startTime, endTime);
                    List<BigDecimal> listRes = new ArrayList<BigDecimal>();
                    if(listObj == null)
                    {
                    	  map.put("dailyLeakRate","0");
                    }else {
	                    for(Map<String, Object> mapObj:listObj)
	                    {
	                    	if(mapObj.get("pressure") != null)
	                    	{
	                    		listRes.add(new BigDecimal(mapObj.get("pressure").toString()));
	                    	}
	                    }
	                    if(!listRes.isEmpty())
	                    {
	                    	prePression = CalcUtil.avgInfo(listRes);
	                    }
                    }
                    //获取前两天数据
                    BigDecimal prePression1  =  BigDecimal.ZERO;
                    LocalDate localday = startTime.toLocalDate().minusDays(1);
                    List<Map<String, Object>> listObj1 = gisSf6PressureMapper.getRecordBySensorCode(map.get("sensorCode").toString(), localday.atStartOfDay(), localday.plusDays(1).atStartOfDay());
                    List<BigDecimal> listRes1 = new ArrayList<BigDecimal>();
                    if(listObj1 == null)
                    {
                    	  map.put("dailyLeakRate","0");
                    }else {
	                    for(Map<String, Object> mapObj1:listObj1)
	                    {
	                    	if(mapObj1.get("pressure") != null)
	                    	{
	                    		listRes1.add(new BigDecimal(mapObj1.get("pressure").toString()));
	                    	}
	                    }
	                    if(!listRes1.isEmpty())
	                    {
	                    	prePression1 = CalcUtil.avgInfo(listRes1);
	                    }
                    }
                    //计算泄露率
                    String rate =df.format(CalcUtil.calcRateEight(prePression.subtract(prePression1), prePression1).multiply(BigDecimal.valueOf(100)));
                    //如果泄露率超标，则告警                    
                    map.put("dailyLeakRate",rate);
//                    map.put("dailyLeakRate",
//                        df.format(new BigDecimal(map.get("dailyLeakRate").toString()).multiply(BigDecimal.valueOf(100))));
                    
                }
            }
        }
        return mapList;
    }

    @Override
    protected void saveBusiOnlineMonitorData(BusiOnlineMonitorData busiOnlineMonitorData, Map<String, Object> item) {
        busiOnlineMonitorData.setSubEquipmentType(GisTreeEnum.SF6_EQM.getValue());
        busiOnlineMonitorData.setExtType(ExternalTypeEnum.GIS.getValue());
        busiOnlineMonitorData.setEquipmentType(SiteTreeEnum.GIS_HL_EQM.getValue());
        // 这里将保存的任务交给父类方法完成，子类只需要修改指定几个字段就可以了
        super.saveBusiOnlineMonitorData(busiOnlineMonitorData, item);
    }

    @Override
    protected Map<String, Object> thresholdDataMap(BusiOnlineMonitorDataVo vo) {
    	GisSf6ThresholdVo thresholdVo = null;
    	if (StringUtils.isNotEmpty(vo.getSensorCode())) {
    		thresholdVo = gisSF6ThresholdService.queryGisSF6Threshold(vo.getSensorCode());
    	}
        return Tools.beanToMap(thresholdVo, "id");
    }

//    @Override
//    protected Map<String, Object> otherDataMap(BusiOnlineMonitorDataVo vo) {
//        Map<String, Object> map = Maps.newHashMap();
//        GisSf6IncreaseRateCache gisSf6IncreaseRateCache =
//            gisSf6IncreaseRateCacheMapper.getItem(vo.getSensorCode(), vo.getDay());
//        if (gisSf6IncreaseRateCache != null) {
//            map.put("increasePressure", gisSf6IncreaseRateCache.getIncreasePressure20C());
//        } else {
//            map.put("increasePressure", 0);
//        }
//        return map;
//    }

    @Override
    public GisSf6PressureStatisticsVo getListEquInfo(String cacMonitorTypeCode, LocalDate day, String sensorCode) {
        GisSf6PressureStatisticsDto param = new GisSf6PressureStatisticsDto();
        param.setStartTime(day.atStartOfDay());
        param.setEndTime(day.plusDays(1).atStartOfDay());
        param.setCacMonitorTypeCode(cacMonitorTypeCode);
        param.setSensorCode(sensorCode);
        List<GisSf6PressureStatisticsVo> list = gisSf6PressureMapper.getListEquInfo(param);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    /**
     * @Title: getSensorInfo
     * @Description: 获取传感器信息
     * @createDate: Sep 29, 2019 5:43:13 PM
     * @param
     * @return BusiGisSensor
     */
    private BusiGisSensor getSensorInfo(String sensorCode) {
        return this.busiGisSensorService.findSensorBySensorCode(sensorCode);
    }

    // *****************************趋势图部分********************************\\
    @Override
    public List<BaseCurveQueryDto> findSensorCodeList(LocalDate day) {
        return gisSf6PressureMapper.findSensorCodeList(day.atStartOfDay(), day.plusDays(1).atStartOfDay());
    }

    @Override
    public List<PointItemVo> findDaylyPointList(BaseCurveQueryDto sensorCode, LocalDate day, String subType) {
        return gisSf6PressureMapper.findDaylyPointList(sensorCode, subType, day.atStartOfDay(),
            day.plusDays(1).atStartOfDay());
    }

    @Override
    public PointItemDto getDaylyPointStatistics(BaseCurveQueryDto param) {
        return gisSf6PressureMapper.getDaylyPointStatistics(param);
    }

	@Override
	public void updateSF6() {
//		File file = new File("D:\\pressionFile.txt");
		List<GisSf6Pressure> list = gisSf6PressureMapper.queryAll();
		for(GisSf6Pressure gisSf6Pressure:list)
		{
			String standardPressure = "";
	        BusiSensorVo sensor = busiGisSensorService.getBusiSensorVo(gisSf6Pressure.getSensorId());
	        if (sensor != null && sensor.getStandardPressure() != null) {
	            standardPressure = sensor.getStandardPressure();
	        }
	        if (!"".equals(standardPressure) && standardPressure != null) {
	        	String res = CalcUtil.pressionInfo(new BigDecimal(standardPressure.trim()),
		                new BigDecimal(gisSf6Pressure.getTemperature()), new BigDecimal(gisSf6Pressure.getPressure20c())).toString();
	        	gisSf6Pressure.setPressure(res);
	        	
	        	log.info("-----------------gis-sf6标准压力（页面输入值）："+standardPressure.trim()+",  报文温度："+gisSf6Pressure.getTemperature()+",  报文压力："+gisSf6Pressure.getPressure20c()+",  折合到20度的压力值："+res);
	            
//	        	CalcUtil.dataWriterFile(file, gisSf6Pressure.getSensorId()+", "+gisSf6Pressure.getTimeStamp()+",  标准压力（页面输入值）："+standardPressure.trim()+",  报文温度："+gisSf6Pressure.getTemperature()+",  报文压力："+gisSf6Pressure.getPressure20c()+",  折合到20度的压力值："+res);
	        }
	        gisSf6PressureMapper.updateData(gisSf6Pressure);
		}
	}
}