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


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
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 com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.SiteConstants.Status;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.dao.RptGisMonitorSf6Dao;
import com.huatek.busi.dto.RptGisMonitorSf6Dto;
import com.huatek.busi.entity.BusiSiteTree;
import com.huatek.busi.entity.GisSf6IncreaseRateCache;
import com.huatek.busi.entity.GisSf6Pressure;
import com.huatek.busi.entity.RptGisMonitorSf6;
import com.huatek.busi.mapper.GisSf6IncreaseRateCacheMapper;
import com.huatek.busi.mapper.RptGisMonitorSf6Mapper;
import com.huatek.busi.service.BusiCommonService;
import com.huatek.busi.service.BusiEqmWarningService;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.PageUtility;
import com.huatek.busi.service.gis.RptGisMonitorSf6Service;
import com.huatek.busi.vo.RptGisMonitorSf6Vo;
import com.huatek.busi.vo.datainput.GisBreakerMonitorVo;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;

/**
 * GIS开关-SF6压力微水温度--实时界面数据 ServiceImpl
 *
 * @author anker_cheng
 * @date Jul 1, 2019 3:06:45 PM
 */
@Component
@Service(interfaceClass = RptGisMonitorSf6Service.class)
@Transactional(rollbackFor = Exception.class)
public class RptGisMonitorSf6ServiceImpl implements RptGisMonitorSf6Service,PageUtility {

    @Autowired
    private RptGisMonitorSf6Mapper rptGisMonitorSf6Mapper;
    @Autowired
    private RptGisMonitorSf6Dao rptGisMonitorSf6Dao;
    @Autowired
    private BusiCommonService busiCommonService;
    @Autowired
    private BusiEqmWarningService busiEqmWarningService;
    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;
    @Autowired
    private GisSf6IncreaseRateCacheMapper gisSf6IncreaseRateCacheMapper;

    @Override
    public PageInfo<RptGisMonitorSf6Vo> findRptGisMonitorSf6Page(RptGisMonitorSf6Dto rptGisMonitorSf6Dto) {
        PageInfo<RptGisMonitorSf6Vo> pageList =
            PageHelper.startPage(rptGisMonitorSf6Dto.getPage(), rptGisMonitorSf6Dto.getLimit())
                .doSelectPageInfo(() -> rptGisMonitorSf6Mapper.selectRptGisMonitorSf6Page(rptGisMonitorSf6Dto));
      
        pageList.getList().stream().forEach(sf6MonitorVo -> {
            // 维修次数
            sf6MonitorVo.setRepairCount(
                busiCommonService.getEquipHalfYearRepairCount(ExternalTypeEnum.GIS, sf6MonitorVo.getEquipmentId()));
            GisSf6IncreaseRateCache gisSf6IncreaseRateCache = gisSf6IncreaseRateCacheMapper.getItem(sf6MonitorVo.getSensorId(),
                sf6MonitorVo.getModifiedTime().toLocalDate().minusDays(1));
            if(gisSf6IncreaseRateCache != null)
            {
//                sf6MonitorVo.setDailyLeakageRate(gisSf6IncreaseRateCache.getIncreasePressure20C());
                
                sf6MonitorVo.setMonthlyGrowthRate(gisSf6IncreaseRateCache.getIncreaseMoisture());
            }
            
            DecimalFormat df = new DecimalFormat("0.00");
            if(sf6MonitorVo.getDailyLeakageRate() !=null)
            {
                sf6MonitorVo.setDailyLeakageRate(
                    df.format(new BigDecimal(sf6MonitorVo.getDailyLeakageRate()).multiply(BigDecimal.valueOf(100))));
            }
            sf6MonitorVo.setMonthlyLeakageRate(
                df.format(getCurrentAvgIncreasePressure(sf6MonitorVo.getSensorId(),sf6MonitorVo.getCreateTime().toLocalDate()).multiply(BigDecimal.valueOf(100))));

            // 误报率
            sf6MonitorVo.setFalseAlarmRate(busiEqmWarningService.getFalseAlarmRateBySensor(sf6MonitorVo.getSensorId(),
                DateUtil.getMonthStartDay(), DateUtil.getMonthLastDay()));
        });
        return pageList;
    }

    @Override
    public synchronized int saveRptGisMonitorSf6(GisSf6Pressure cacEntity) {
        RptGisMonitorSf6 rptGisMonitorSf6 =
            rptGisMonitorSf6Mapper.getRptGisMonitorSf6(cacEntity.getSiteId(), cacEntity.getSensorId());
        if (rptGisMonitorSf6 == null) {
            rptGisMonitorSf6 = new RptGisMonitorSf6();
            rptGisMonitorSf6.setCreateTime(LocalDateTime.now());
            rptGisMonitorSf6.setStatus(Status.NORMAL.getValue());
        }
        rptGisMonitorSf6.setSiteId(cacEntity.getSiteId());
        rptGisMonitorSf6.setEqmCode(cacEntity.getEquipmentCode());
        rptGisMonitorSf6.setEqmId(cacEntity.getEquipmentId());
        rptGisMonitorSf6.setMainTreeId(cacEntity.getMainTreeId());
        rptGisMonitorSf6.setSubTreeId(cacEntity.getSubTreeId());
        rptGisMonitorSf6.setSensorId(cacEntity.getSensorId());
        rptGisMonitorSf6.setModifiedTime(LocalDateTime.now());
        rptGisMonitorSf6.setMoisture(cacEntity.getMoisture());
        rptGisMonitorSf6.setPressure(cacEntity.getPressure20c());
        rptGisMonitorSf6.setTemper(cacEntity.getTemperature());
        rptGisMonitorSf6.setPhase(cacEntity.getPhase());
        rptGisMonitorSf6.setDailyLeakRate(cacEntity.getDailyLeakLate());
        rptGisMonitorSf6.setEquipmentSensitivity(cacEntity.getEquipmentSensitivity());
        return rptGisMonitorSf6Dao.saveOrUpdate(rptGisMonitorSf6);
    }

	@Override
	public Map<String, Object> findGisBreakerPage(Map<String, Object> params) {
		// TODO Auto-generated method stub
        if (params.get("page") != null && params.get("limit") != null) {
            PageHelper.startPage(page(params), limit(params));
        }
        Page<Map<String, Object>> page = rptGisMonitorSf6Mapper.findGisBreakerPage(params);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(), "", page.getResult());
	}

	@Override
	public Map<String, Object> exportBreakerMonitorList(String mainTreeId, String timeStamp,String timeStampEnd) {
		// TODO Auto-generated method stub
		Map<String, Object> returnMap = new HashMap<>();
		if (StringUtils.isNotEmpty(mainTreeId)) {
			BusiSiteTree busiSiteTree = busiSiteTreeService.findByPK(mainTreeId);
			List<GisBreakerMonitorVo> breakerMonitorList = rptGisMonitorSf6Mapper.exportBreakerMonitorList(mainTreeId,timeStamp,timeStampEnd);
			returnMap.put("fileName", String.format("%s%s", busiSiteTree.getName(),"GIS断路器监测数据"));
			returnMap.put("title", String.format("%s%s", busiSiteTree.getName(),"GIS断路器监测数据"));
			if (breakerMonitorList.isEmpty()) {
				breakerMonitorList = new ArrayList<>();
				breakerMonitorList.add(new GisBreakerMonitorVo());
			} else {
				breakerMonitorList.stream().forEach(breakerVo ->{
					breakerVo.setWorkState(returnWorkState(breakerVo.getWorkState()));
					breakerVo.setIsFault(returnFaultType(breakerVo.getIsFault()));
					breakerVo.setIsBreak(returnBreakType(breakerVo.getIsBreak()));
				});
			}
			returnMap.put("data", breakerMonitorList);
		} else {
			throw new RuntimeException("主设备编码不正确");
		}
		return returnMap;
	}
	
	private String returnWorkState(String workState) {
		if (workState.equals("1")) {
			return "发电状态";
		} else if (workState.equals("2")) {
			return "抽水状态";
		} else {
			return "空闲状态";
		}
	}
	
	private String returnFaultType(String faultType) {
		if (faultType.equals("0")) {
			return "否";
		} else {
			return "是";
		}
	}
	
	
	private String returnBreakType(String breakType) {
		if (breakType.equals("0")) {
			return "断开";
		} else {
			return "闭合";
		}
	}
	
	//获取月泄露率
    public BigDecimal getCurrentAvgIncreasePressure(String sensorCode,LocalDate day)
    {
        //获取月初的泄露率
        GisSf6IncreaseRateCache sf61 = gisSf6IncreaseRateCacheMapper.getItem(sensorCode, day);
        GisSf6IncreaseRateCache sf62 = gisSf6IncreaseRateCacheMapper.getItem(sensorCode, day.minusDays(30));
        if(sf61!=null && sf62 != null)
        {
            String rate1 = sf61.getIncreasePressure20C();
            //获取月末泄露率
            String rate2 = sf62.getIncreasePressure20C();
            BigDecimal b1 = new BigDecimal(rate1);
            BigDecimal b2 = new BigDecimal(rate2);        
            return b2.subtract(b1).setScale(4, RoundingMode.HALF_UP); //小数位 直接舍去
        }
        else
        {
            return BigDecimal.ZERO;
        }
        
    }
    
    public LocalDate getLastMontFirstDay()
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
        //获取前月的第一天 
        Calendar   cal_1=Calendar.getInstance();//获取当前日期 
        cal_1.add(Calendar.MONTH, -1);
        cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        LocalDate parseDate = LocalDate.parse(format.format(cal_1.getTime()));
        return parseDate;
    }
    
    public LocalDate getLastMontFinishDay()
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
         //获取前月的最后一天
         Calendar cale = Calendar.getInstance();   
         cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天 
         LocalDate parseDate = LocalDate.parse(format.format(cale.getTime()));
         return parseDate;
    }
}