package cn.cecep.talroad.service.impl.analysis;

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.common.core.utils.bean.BeanUtils;
import cn.cecep.talroad.domain.*;
import cn.cecep.talroad.domain.analysis.SRaAreaTransferRateAnalysis;
import cn.cecep.talroad.domain.analysis.SRaFactoryTransferRateAnalysis;
import cn.cecep.talroad.enums.EnIndustry;
import cn.cecep.talroad.enums.TimeTypeEnum;
import cn.cecep.talroad.mapper.analysis.SRaFactoryTransferRateAnalysisMapper;
import cn.cecep.talroad.service.*;
import cn.cecep.talroad.service.analysis.ISRaAreaTransferRateAnalysisService;
import cn.cecep.talroad.service.analysis.ISRaFactoryTransferRateAnalysisService;
import cn.cecep.talroad.vo.FactoryDeviceVo;
import cn.cecep.talroad.vo.analysis.AvgValueVo;
import cn.cecep.talroad.vo.analysis.FactoryOutletStaticsVo;
import cn.cecep.talroad.vo.analysis.FactoryOutletVo;
import cn.cecep.talroad.vo.analysis.FactoryTransferRateParamVo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.transaction.annotation.Transactional;

/**
 * 企业传输率分析Service业务层处理
 *
 * @author szhpt
 * @date 2023-03-28*/
@Slf4j
@Service
public class SRaFactoryTransferRateAnalysisServiceImpl extends ServiceImpl<SRaFactoryTransferRateAnalysisMapper, SRaFactoryTransferRateAnalysis> implements ISRaFactoryTransferRateAnalysisService
{
    @Autowired
    private SRaFactoryTransferRateAnalysisMapper sRaFactoryTransferRateAnalysisMapper;

    @Autowired
    private IBasDeviceService basDeviceService;
    @Autowired
    private IBasDeviceParamService iBasDeviceParamService;
    @Autowired
    private IMonDevRealService iMonDevRealService;
    @Autowired
    private IMonDevJhRealService iMonDevJhRealService;
    @Autowired
    private IMonDevSnRealService iMonDevSnRealService;
    @Autowired
    private IMonDevBlRealService iMonDevBlRealService;
    @Autowired
    private IMonDevDlRealService iMonDevDlRealService;
    @Autowired
    private IMonDevFsRealService iMonDevFsRealService;

    @Autowired
    private IMonElecRealService iMonElecRealService;

    @Autowired
    private ISEnvGasMonRealService isEnvGasMonRealService;
    @Autowired
    private ISEnvGasMonHourService isEnvGasMonHourService;
    @Autowired
    private ISEnvGasMonDayService isEnvGasMonDayService;

    @Autowired
    private ISEnvWaterMonRealService isEnvWaterMonRealService;
    @Autowired
    private ISEnvWaterMonHourService isEnvWaterMonHourService;
    @Autowired
    private ISEnvWaterMonDayService isEnvWaterMonDayService;
    @Autowired
    private ISEnvGasRealService isEnvGasRealService;
    @Autowired
    private IOdsInorganizationWeiStationHourIService iOdsInorganizationWeiStationHourIService;
    @Autowired
    private IOdsMeshingShStationHourIService iOdsMeshingShStationHourIService;
    @Autowired
    private IOdsMeshingWeiStationHourIService iOdsMeshingWeiStationHourIService;
    @Autowired
    private IPcFactoryService iPcFactoryService;
    @Autowired
    private ISRaAreaTransferRateAnalysisService isRaAreaTransferRateAnalysisService;
    /**
     * 查询企业传输率分析列表
     *
     * @param sRaFactoryTransferRateAnalysis 企业传输率分析
     * @return 企业传输率分析
     */
    @Override
    public List<SRaFactoryTransferRateAnalysis> selectSRaFactoryTransferRateAnalysisList(SRaFactoryTransferRateAnalysis sRaFactoryTransferRateAnalysis)
    {
        return sRaFactoryTransferRateAnalysisMapper.selectSRaFactoryTransferRateAnalysisList(sRaFactoryTransferRateAnalysis);
    }

    /**
     * 定时任务先跑完企业的数据，之后，根据企业的传输率分析来汇总区域的。
     * @param statisticsDate
     */
    @Override
    public void generateAreaDayRecord(LocalDate statisticsDate){
        Date lastDate = DateUtils.addDateDays(new Date(),-1);
        String lastDay = DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDateDays(new Date(),-1));

        List<SRaFactoryTransferRateAnalysis> factoryTransList = sRaFactoryTransferRateAnalysisMapper.selectListByArea(lastDay,"D");
        List<SRaAreaTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:factoryTransList) {
            SRaAreaTransferRateAnalysis data = new SRaAreaTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("D");
            data.setCreateTime(new Date());
            data.setStatisticsTime(lastDay);
            data.setDataTime(DateUtils.parseFormatDate("yyyy-MM-dd 00:00:00",lastDate));
            addList.add(data);
        }

        if(addList.size()>0){
            isRaAreaTransferRateAnalysisService.saveBatch(addList);
            addList.clear();
        }
    }

    /**
     * 生成企业月度报表
     * 逻辑如下，查询该月下所有的日数据，根据企业+outletCode为维度，进行数据求和组装
     * @param statisticsDate yyyyMM
     */
    @Override
    public void generateFactoryMonthRecord(String statisticsDate){
        Date lastMonth = DateUtils.addDateMonths(new Date() ,-1);
        DateTime beginTime = DateUtil.beginOfMonth(lastMonth);
        List<SRaFactoryTransferRateAnalysis> dataList = sRaFactoryTransferRateAnalysisMapper.selectStatisticsLastMonthData(DateUtils.parseDateToStr("yyyy-MM",lastMonth),"D");
        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:dataList) {
            SRaFactoryTransferRateAnalysis data = new SRaFactoryTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("M");
            data.setStatisticsTime(statisticsDate);
            data.setCreateTime(new Date());
            data.setDataTime(beginTime);
            addList.add(data);
        }
        if(addList.size()>0){
            this.saveBatch(addList);
            addList.clear();
        }
    }

    /**
     * 生成企业季度报表
     * 逻辑如下，查询该季度下所有的月数据，根据企业+outletCode为维度，进行数据求和组装
     * @param year
     */
    @Override
    public void generateFactorySeasonRecord(String year){
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        if(StringUtils.isEmpty(year)) {
            year = DateUtils.parseDateToStr("yyyy", lastMonth);
        }
        int quarter = DateUtil.date(lastMonth).quarter();
        String season = year +"-"+ quarter;
        DateTime beginOfSeason = DateUtil.beginOfQuarter(lastMonth);
        DateTime endOfSeason = DateUtil.endOfQuarter(lastMonth);

        List<SRaFactoryTransferRateAnalysis> dataList = sRaFactoryTransferRateAnalysisMapper.selectStatisticsSeasonData(DateUtils.getRangeTimes("N",beginOfSeason,endOfSeason));
        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:dataList) {
            SRaFactoryTransferRateAnalysis data = new SRaFactoryTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("S");
            data.setStatisticsTime(season);
            data.setCreateTime(new Date());
            data.setDataTime(beginOfSeason);
            addList.add(data);
        }
        if(addList.size()>0){
            this.saveBatch(addList);
            addList.clear();
        }
    }

    /**
     * 生成企业年报表
     * 逻辑如下，查询该年所有的季度数据，根据企业+outletCode为维度，进行数据求和组装
     * @param year
     */
    @Override
    public void generateFactoryYearRecord(String year){
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        DateTime beginOfYear = DateUtil.beginOfYear(lastMonth);
        DateTime endOfYear = DateUtil.endOfYear(lastMonth);
        //查询过去1年
        List<SRaFactoryTransferRateAnalysis> dataList = sRaFactoryTransferRateAnalysisMapper.selectStatisticsSeasonData(DateUtils.getRangeTimes("N",beginOfYear,endOfYear));

        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:dataList) {
            SRaFactoryTransferRateAnalysis data = new SRaFactoryTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("Y");
            data.setStatisticsTime(year);
            data.setCreateTime(new Date());
            data.setDataTime(beginOfYear);
            addList.add(data);
        }
        if(addList.size()>0){
            this.saveBatch(addList);
            addList.clear();
        }
    }


    /**
     * 生成企业月度报表
     * 逻辑如下，查询该月下所有的日数据，根据区域编码维度，进行数据求和组装
     * @param statisticsDate yyyy-MM
     */
    @Override
    public void generateAreaMonthRecord(String statisticsDate){
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        String lastMonthStr = DateUtils.parseDateToStr("yyyy-MM",lastMonth);
        DateTime beginOfMonth = DateUtil.beginOfMonth(lastMonth);

        List<SRaFactoryTransferRateAnalysis> factoryTransList = sRaFactoryTransferRateAnalysisMapper.selectListByArea(lastMonthStr,"M");
        List<SRaAreaTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:factoryTransList) {
            SRaAreaTransferRateAnalysis data = new SRaAreaTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("M");
            data.setCreateTime(new Date());
            data.setStatisticsTime(statisticsDate);
            data.setDataTime(beginOfMonth);
            addList.add(data);
        }

        if(addList.size()>0){
            isRaAreaTransferRateAnalysisService.saveBatch(addList);
            addList.clear();
        }
    }

    /**
     * 生成区域季度报表
     * 逻辑如下，查询该季度下所有的月数据，根据区域编码维度，进行数据求和组装
     * @param year
     */
    @Override
    public void generateAreaSeasonRecord(String year){
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        if(StringUtils.isEmpty(year)) {
            year = DateUtils.parseDateToStr("yyyy", lastMonth);
        }
        DateTime beginOfSeason = DateUtil.beginOfQuarter(lastMonth);
        String quarterTime = year+"-"+beginOfSeason.quarter();

        List<SRaFactoryTransferRateAnalysis> dataList = sRaFactoryTransferRateAnalysisMapper.selectListByArea(quarterTime, "S");

        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:dataList) {
            SRaFactoryTransferRateAnalysis data = new SRaFactoryTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("S");
            data.setStatisticsTime(quarterTime);
            data.setCreateTime(new Date());
            data.setDataTime(beginOfSeason);
            addList.add(data);
        }
        if(addList.size()>0){
            this.saveBatch(addList);
            addList.clear();
        }

    }

    /**
     * 生成企业年度报表
     * 逻辑如下，查询该年所有的季度 数据，根据区域编码维度，进行数据求和组装
     * @param year
     */
    @Override
    public void generateAreaYearRecord(String year){
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        year = DateUtils.parseDateToStr("yyyy", lastMonth);
        DateTime beginOfYear = DateUtil.beginOfYear(lastMonth);

        List<SRaFactoryTransferRateAnalysis> dataList = sRaFactoryTransferRateAnalysisMapper.selectListByArea(year,"Y");

        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        for (SRaFactoryTransferRateAnalysis tmp:dataList) {
            SRaFactoryTransferRateAnalysis data = new SRaFactoryTransferRateAnalysis();
            BeanUtils.copyProperties(tmp,data);
            data.setId(UUID.randomUUID().toString());
            data.setCountType("Y");
            data.setStatisticsTime(year);
            data.setCreateTime(new Date());
            data.setDataTime(beginOfYear);
            addList.add(data);
        }
        if(addList.size()>0){
            this.saveBatch(addList);
            addList.clear();
        }
    }


    /**
     * 生成日数据
     * 逻辑说明：根据排口维度，查询数据进行封装
     * @param statisticsDate
     */
    @Override
    @Transactional
    public void generateFactoryDayRecord2(LocalDate statisticsDate){

        String statisticsTime =statisticsDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String queryDate = statisticsDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        DateTime queryBeginTime = DateUtil.parse(queryDate+" 00:00:00");
        DateTime queryEndTime =DateUtil.parse(queryDate+" 23:59:59");

        try {
            processDcsTransRate(statisticsTime, queryBeginTime, queryEndTime);
        } catch (Exception e) {
            log.error("DCS设备传输率分析异常:"+e.getMessage());
        }

        try {
            doProcessElecData(statisticsTime, queryBeginTime, queryEndTime);
        } catch (Exception e) {
            log.error("分表计电设备传输率分析异常:"+e.getMessage());
        }
        try {
            // 处理废气传输率分析
            doProcessGasRateData(statisticsTime, queryBeginTime, queryEndTime);
        } catch (Exception e) {
            log.error("废气在线监测设备传输率分析异常："+e.getMessage());
        }

        try {
            doProcessWaterRateData(statisticsTime, queryBeginTime, queryEndTime);
        } catch (Exception e) {
            log.error("废水在线监测设备传输率分析异常："+e.getMessage());
        }

        try {
            doProcessUnorgTransRateData(statisticsTime, queryBeginTime, queryEndTime);
        } catch (Exception e) {
            log.error("无组织在线监测设备传输率分析异常："+e.getMessage());
        }
    }

    /**
     * 无组织监测设备传输率
     * @param statisticsTime
     * @param queryBeginTime
     * @param queryEndTime
     */
    private void doProcessUnorgTransRateData(String statisticsTime, DateTime queryBeginTime, DateTime queryEndTime) {
        List<SRaFactoryTransferRateAnalysis> rateList = new ArrayList<>();
        Integer ycCount = 24;

        List<FactoryOutletStaticsVo> realList = isEnvGasRealService.selectLastDayData(queryBeginTime,queryEndTime);
        realList.forEach(pcOutlet ->{
            SRaFactoryTransferRateAnalysis rateAnalysis = getOrgTransferRateAnalysis(statisticsTime,queryBeginTime, pcOutlet,ycCount,pcOutlet.getActualCount());
            if(rateAnalysis!=null) {
                rateList.add(rateAnalysis);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }
    }

    /**
     * 无组织在线监测
     * @param statisticsTime
     * @param fv
     * @param ycCount
     * @param realHourCout
     * @return
     */
    private SRaFactoryTransferRateAnalysis getOrgTransferRateAnalysis(String statisticsTime,DateTime dataTime, FactoryOutletStaticsVo fv, Integer ycCount, Integer realHourCout) {
        // 传输率
        BigDecimal rate = new BigDecimal(realHourCout).divide(new BigDecimal(ycCount),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        // 查询企业信息
        FactoryOutletVo vo = iPcFactoryService.selectByFactoryAndOutletId(fv.getFactoryId(),fv.getOutletId());
        if(vo!=null) {
            SRaFactoryTransferRateAnalysis rateAnalysis = new SRaFactoryTransferRateAnalysis();
            rateAnalysis.setId(UUID.randomUUID().toString());
            rateAnalysis.setFactoryId(vo.getFactoryId());
            rateAnalysis.setStatisticsTime(statisticsTime);
            rateAnalysis.setDataTime(dataTime);
            rateAnalysis.setOutletCode(vo.getOutletId());
            rateAnalysis.setOutletName(vo.getOutletName());
            rateAnalysis.setCountType("D");
            rateAnalysis.setFactoryName(vo.getFactoryName());
            rateAnalysis.setDistrictCode(vo.getCityCode());
            rateAnalysis.setDistrictName(vo.getCityName());
            rateAnalysis.setIndustryCategoryCode(vo.getIndustry());
            rateAnalysis.setIndustryCategoryName(vo.getIndustryName());
            rateAnalysis.setCreateTime(new Date());
            rateAnalysis.setUnorganizedTransmittHourNum(ycCount);
            rateAnalysis.setUnorganizedActualTransmittHourNum(realHourCout);
            rateAnalysis.setUnorganizedTransmissionHourRate(rate);

            return rateAnalysis;
        }
        return null;
    }

    /**
     * 废水在线监测传输率分析
     * @param statisticsTime
     * @param queryBeginTime
     * @param queryEndTime
     */
    private void doProcessWaterRateData(String statisticsTime, DateTime queryBeginTime, DateTime queryEndTime) {
        List<SRaFactoryTransferRateAnalysis> rateList = new ArrayList<>();
        Integer gasMinCount  = 1440;
        Integer gasHourCount = 24;
        Integer gasDayCount = 1;

        List<FactoryOutletStaticsVo> realList = isEnvWaterMonRealService.selectLastDayCountData(queryBeginTime,queryEndTime);
        realList.forEach(fv->{
            // 通用方法
            SRaFactoryTransferRateAnalysis rateAnalysis = getGasTransferRateAnalysis(statisticsTime,queryBeginTime, fv,gasMinCount,fv.getActualCount(),TimeTypeEnum.REAL);
            if(rateAnalysis!=null) {
                rateList.add(rateAnalysis);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }
        List<FactoryOutletStaticsVo> hourList = isEnvWaterMonHourService.selectLastDayCountData(queryBeginTime,queryEndTime);
        hourList.forEach(fv->{
            // 通用方法
            SRaFactoryTransferRateAnalysis rateAnalysis = getGasTransferRateAnalysis(statisticsTime,queryBeginTime, fv,gasHourCount,fv.getActualCount(),TimeTypeEnum.HOUR);
            if(rateAnalysis!=null) {
                rateList.add(rateAnalysis);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }
        List<FactoryOutletStaticsVo> dayList = isEnvWaterMonDayService.selectLastDayCountData(queryBeginTime,queryEndTime);
        dayList.forEach(fv->{
            // 通用方法
            SRaFactoryTransferRateAnalysis rateAnalysisDay = getGasTransferRateAnalysis(statisticsTime,queryBeginTime, fv,gasDayCount,fv.getActualCount(),TimeTypeEnum.DAY);
            if(rateAnalysisDay!=null) {
                rateList.add(rateAnalysisDay);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }

    }

    /**
     * 废气在线监测传输率分析
     * @param statisticsTime
     * @param queryBeginTime
     * @param queryEndTime
     */
    private void doProcessGasRateData(String statisticsTime, DateTime queryBeginTime, DateTime queryEndTime) {
        List<SRaFactoryTransferRateAnalysis> rateList = new ArrayList<>();
        Integer gasMinCount  = 1440;
        Integer gasHourCount = 24;
        Integer gasDayCount = 1;

        List<FactoryOutletStaticsVo> realList = isEnvGasMonRealService.selectLastDayData(queryBeginTime,queryEndTime);
        realList.forEach(fv->{
            // 通用方法
            SRaFactoryTransferRateAnalysis rateAnalysis = getGasTransferRateAnalysis(statisticsTime,queryBeginTime, fv,gasMinCount,fv.getActualCount(),TimeTypeEnum.REAL);
            if(rateAnalysis!=null) {
                rateList.add(rateAnalysis);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }
        List<FactoryOutletStaticsVo> hourList = isEnvGasMonHourService.selectLastDayCountData(queryBeginTime,queryEndTime);
        hourList.forEach(fv->{
            // 通用方法
            SRaFactoryTransferRateAnalysis rateAnalysis = getGasTransferRateAnalysis(statisticsTime,queryBeginTime, fv,gasHourCount,fv.getActualCount(),TimeTypeEnum.HOUR);
            if(rateAnalysis!=null) {
                rateList.add(rateAnalysis);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }
        List<FactoryOutletStaticsVo> dayList = isEnvGasMonDayService.selectLastDayData(queryBeginTime,queryEndTime);
        dayList.forEach(fv->{
            // 通用方法
            SRaFactoryTransferRateAnalysis rateAnalysisDay = getGasTransferRateAnalysis(statisticsTime,queryBeginTime, fv,gasDayCount,fv.getActualCount(),TimeTypeEnum.DAY);
            if(rateAnalysisDay!=null) {
                rateList.add(rateAnalysisDay);
            }
        });
        if(rateList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(rateList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            rateList.clear();
        }
    }

    /**
     * 在线监测传输率
     * @param statisticsTime
     * @param gasCount
     * @param realCount
     * @return
     */
    private SRaFactoryTransferRateAnalysis getGasTransferRateAnalysis(String statisticsTime,DateTime dataTime, FactoryOutletStaticsVo fv, Integer gasCount, Integer realCount,TimeTypeEnum typeEnum) {
        // 传输率
        BigDecimal rate = new BigDecimal(realCount).divide(new BigDecimal(gasCount),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        // 查询企业信息
        FactoryOutletVo vo = iPcFactoryService.selectByFactoryAndOutletId(fv.getFactoryId(),fv.getOutletId());
        if(vo!=null) {
            SRaFactoryTransferRateAnalysis rateAnalysis = new SRaFactoryTransferRateAnalysis();
            rateAnalysis.setId(UUID.randomUUID().toString());
            rateAnalysis.setFactoryId(vo.getFactoryId());
            rateAnalysis.setStatisticsTime(statisticsTime);
            rateAnalysis.setDataTime(dataTime.toJdkDate());
            rateAnalysis.setOutletCode(vo.getOutletId());
            rateAnalysis.setOutletName(vo.getOutletName());
            rateAnalysis.setCountType("D");
            rateAnalysis.setFactoryName(vo.getFactoryName());
            rateAnalysis.setDistrictCode(vo.getCityCode());
            rateAnalysis.setDistrictName(vo.getCityName());
            rateAnalysis.setIndustryCategoryCode(vo.getIndustry());
            rateAnalysis.setIndustryCategoryName(vo.getIndustryName());
            rateAnalysis.setCreateTime(new Date());
            if (TimeTypeEnum.REAL.getCode().equals(typeEnum.getCode())) {
                rateAnalysis.setOnlineMonitoringActualMinuteNum(realCount);
                rateAnalysis.setOnlineMonitoringMinuteNum(gasCount);
                rateAnalysis.setOnlineMonitoringMinuteRate(rate);
            } else if (TimeTypeEnum.HOUR.getCode().equals(typeEnum.getCode())) {
                rateAnalysis.setOnlineMonitoringActualHourNum(realCount);
                rateAnalysis.setOnlineMonitoringHourNum(gasCount);
                rateAnalysis.setOnlineMonitoringHourRate(rate);
            } else {
                rateAnalysis.setOnlineMonitoringActualDayNum(realCount);
                rateAnalysis.setOnlineMonitoringDayNum(gasCount);
                rateAnalysis.setOnlineMonitoringDayRate(rate);
            }
            return rateAnalysis;
        }
        return null;
    }

    /**
     * 分表计电
     * @param statisticsTime
     * @param queryBeginTime
     * @param queryEndTime
     */
    private void doProcessElecData(String statisticsTime, DateTime queryBeginTime, DateTime queryEndTime) {
        Integer elecMinCount = 96;
        Integer pageSize = 2000;
        for(int i=0;i<20;i++) {
            List<AvgValueVo> elecList = iMonElecRealService.selectLastDayData(queryBeginTime, queryEndTime,pageSize,i*pageSize);
            if(elecList.size()>0) {
                // 处理分表计电设备传输率
                doProcessElecTransRate(statisticsTime,queryBeginTime, elecMinCount, elecList);
            }else{
                break;
            }
        }
    }

    /**
     * DCS设备传输率
     * @param statisticsTime
     * @param queryBeginTime
     * @param queryEndTime
     */
    private void processDcsTransRate(String statisticsTime, DateTime queryBeginTime, DateTime queryEndTime) {
        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        // 查询昨天设备上传次数
        List<AvgValueVo> gtList = iMonDevRealService.selectLastDayData(queryBeginTime,queryEndTime);
        doProcessCommonTransRate(statisticsTime,queryBeginTime, addList, gtList);
        // 查询昨天设备上传次数
        List<AvgValueVo> jhList = iMonDevJhRealService.selectLastDayData(queryBeginTime,queryEndTime);
        doProcessCommonTransRate(statisticsTime,queryBeginTime, addList, jhList);
        // 查询昨天设备上传次数
        List<AvgValueVo> snList = iMonDevSnRealService.selectLastDayData(queryBeginTime,queryEndTime);
        doProcessCommonTransRate(statisticsTime,queryBeginTime, addList, snList);
        // 查询昨天设备上传次数
        List<AvgValueVo> blList = iMonDevBlRealService.selectLastDayData(queryBeginTime,queryEndTime);
        doProcessCommonTransRate(statisticsTime,queryBeginTime, addList, blList);
        // 查询昨天设备上传次数
        List<AvgValueVo> dlList = iMonDevDlRealService.selectLastDayData(queryBeginTime,queryEndTime);
        doProcessCommonTransRate(statisticsTime,queryBeginTime, addList, dlList);
        // 查询昨天设备上传次数
        List<AvgValueVo> fsList = iMonDevFsRealService.selectLastDayData(queryBeginTime,queryEndTime);
        doProcessCommonTransRate(statisticsTime,queryBeginTime, addList, fsList);

    }

    /**
     * 通用企业传输率分析
     * @param statisticsTime
     * @param addList
     * @param gtList
     */
    private void doProcessCommonTransRate(String statisticsTime,DateTime dataTime, List<SRaFactoryTransferRateAnalysis> addList, List<AvgValueVo> gtList) {
        gtList.forEach(device -> {
            // 查询所有需要统计的设备参数
            List<FactoryTransferRateParamVo> paramVoList = this.baseMapper.selectFactoryTransferRateParamVoList(device.getDeviceId());
            if(paramVoList.size()>0) {
                // 应传个数
                Integer ycCount = 24 * 60 * paramVoList.size();
                Integer realCount = device.getAvgValue().intValue() * paramVoList.size();

                log.info("实际上传数量:" + realCount + "#应传数量:" + ycCount);
                // 通用方法
                SRaFactoryTransferRateAnalysis rateAnalysis = getDcsTransferRateAnalysis(statisticsTime,dataTime, device.getDeviceId(), ycCount, realCount);
                if(rateAnalysis!=null) {
                    addList.add(rateAnalysis);
                }
            }
        });
        if(addList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(addList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            addList.clear();
        }
    }

    /**
     * 处理分表计电设备传输率
     * @param statisticsTime
     * @param elecMinCount
     * @param elecList
     */
    private void doProcessElecTransRate(String statisticsTime,DateTime dataTime, Integer elecMinCount,List<AvgValueVo> elecList) {
        List<SRaFactoryTransferRateAnalysis> addList = new ArrayList<>();
        elecList.forEach(basDevice -> {
            SRaFactoryTransferRateAnalysis rateAnalysis = getElecTransferRateAnalysis(statisticsTime,dataTime, basDevice.getDeviceId(), elecMinCount, basDevice.getAvgValue().intValue());
            if(rateAnalysis!=null) {
                addList.add(rateAnalysis);
            }
        });

        if(addList.size()>0){
            List<List<SRaFactoryTransferRateAnalysis>> partList = Lists.partition(addList,2000);
            partList.forEach(i->{
                this.saveBatch(i);
            });
            addList.clear();
        }
    }

    /**
     * 企业分表计电传输率通用方法
     * @param statisticsTime
     * @param deviceId
     * @param ycCount
     * @param realCount
     * @return
     */
    private SRaFactoryTransferRateAnalysis getElecTransferRateAnalysis(String statisticsTime,DateTime dataTime, String deviceId,Integer ycCount,Integer realCount) {
        // 传输率
        BigDecimal rate = new BigDecimal(realCount).divide(new BigDecimal(ycCount),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        // 查询企业信息
        FactoryDeviceVo vo = basDeviceService.selectFactoryDeviceVoByDeviceId(deviceId);
        if(vo!=null) {
            SRaFactoryTransferRateAnalysis rateAnalysis = new SRaFactoryTransferRateAnalysis();
            rateAnalysis.setId(UUID.randomUUID().toString());
            rateAnalysis.setFactoryId(vo.getFactoryId());
            rateAnalysis.setStatisticsTime(statisticsTime);
            rateAnalysis.setDataTime(dataTime.toJdkDate());
            rateAnalysis.setOutletCode(vo.getDeviceId());
            rateAnalysis.setOutletName(vo.getDeviceName());
            rateAnalysis.setCountType("D");
            rateAnalysis.setFactoryName(vo.getFactoryName());
            rateAnalysis.setDistrictCode(vo.getCityCode());
            rateAnalysis.setDistrictName(vo.getCityName());
            rateAnalysis.setIndustryCategoryCode(vo.getIndustry());
            rateAnalysis.setIndustryCategoryName(vo.getIndustryName());
            rateAnalysis.setCreateTime(new Date());
            rateAnalysis.setElecActualTransmittNum(realCount);
            rateAnalysis.setElecTransmittNum(ycCount);
            rateAnalysis.setElecTransmissionRate(rate);
            return rateAnalysis;
        }
        return  null;
    }

    /**
     * 企业DCS传输率通用方法
     * @param statisticsTime
     * @param deviceId
     * @param ycCount
     * @param realCount
     * @return
     */
    private SRaFactoryTransferRateAnalysis getDcsTransferRateAnalysis(String statisticsTime,DateTime dataTime, String deviceId,Integer ycCount,Integer realCount) {
        // 传输率
        BigDecimal rate = new BigDecimal(realCount).divide(new BigDecimal(ycCount),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        // 查询企业信息
        FactoryDeviceVo vo = basDeviceService.selectFactoryDeviceVoByDeviceId(deviceId);
        if(vo!=null) {
            SRaFactoryTransferRateAnalysis rateAnalysis = new SRaFactoryTransferRateAnalysis();
            rateAnalysis.setId(UUID.randomUUID().toString());
            rateAnalysis.setFactoryId(vo.getFactoryId());
            rateAnalysis.setStatisticsTime(statisticsTime);
            rateAnalysis.setDataTime(dataTime.toJdkDate());
            rateAnalysis.setOutletCode(vo.getDeviceId());
            rateAnalysis.setOutletName(vo.getDeviceName());
            rateAnalysis.setCountType("D");
            rateAnalysis.setFactoryName(vo.getFactoryName());
            rateAnalysis.setDistrictCode(vo.getCityCode());
            rateAnalysis.setDistrictName(vo.getCityName());
            rateAnalysis.setIndustryCategoryCode(vo.getIndustry());
            rateAnalysis.setIndustryCategoryName(vo.getIndustryName());
            rateAnalysis.setCreateTime(new Date());
            rateAnalysis.setDcsActualTransmittNum(realCount);
            rateAnalysis.setDcsTransmittMinuteNum(ycCount);
            rateAnalysis.setDcsTransmissionRate(rate);
            return rateAnalysis;
        }
        return null;
    }

}
