package com.njcn.harmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.njcn.common.config.GeneralInfo;
import com.njcn.device.api.GeneralDeviceInfoClient;
import com.njcn.device.api.LineFeignClient;
import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.dto.PollutionLineDTO;
import com.njcn.device.pojo.dto.PollutionParamDTO;
import com.njcn.device.pojo.vo.LineDeviceStateVO;
import com.njcn.harmonic.constant.Param;
import com.njcn.harmonic.pojo.dto.AreaDTO;
import com.njcn.harmonic.pojo.param.HarmonicPublicParam;
import com.njcn.harmonic.pojo.po.LimitTarget;
import com.njcn.harmonic.pojo.vo.HarmonicDeptVO;
import com.njcn.harmonic.pojo.vo.HarmonicLineVO;
import com.njcn.harmonic.pojo.vo.HarmonicSubstationVO;
import com.njcn.harmonic.pojo.vo.PollutionVO;
import com.njcn.harmonic.service.IHarmonicService;
import com.njcn.influxdb.utils.InfluxDbUtils;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2021/12/31 9:50
 */
@Service
@AllArgsConstructor
public class HarmonicServiceImpl implements IHarmonicService {

    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    private final InfluxDbUtils influxDbUtils;

    private final GeneralInfo generalInfo;

    private final LineFeignClient lineFeignClient;

    @Override
    public List<PollutionVO> getDeptSubstationRelations(HarmonicPublicParam harmonicPublicParam) {
        harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
        List<PollutionVO> list = new ArrayList<>();
        List<String> lineList = new ArrayList<>();
        List<PollutionLineDTO> lineInfo = new ArrayList<>();
        PollutionParamDTO paramDTO = new PollutionParamDTO();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())){
            return list;
        }
        List<GeneralDeviceDTO> deptList = generalDeviceInfoClient.getPracticalRunDeviceInfo(harmonicPublicParam).getData();
        deptList.forEach(dept->{
            lineList.addAll(dept.getLineIndexes());
        });
        if (!CollectionUtils.isEmpty(lineList)){
            paramDTO.setLineList(lineList);
            lineInfo = lineFeignClient.getLineInfo(paramDTO).getData();
        }
        Map<String,List<PollutionLineDTO>> map = lineInfo.stream().collect(Collectors.groupingBy(PollutionLineDTO::getSubstationId));
        deptList.forEach(dept->{
            List<PollutionVO> childrenList = new ArrayList<>();
            PollutionVO pollutionVO = new PollutionVO();
            pollutionVO.setId(dept.getIndex());
            pollutionVO.setName(dept.getName());
            if (!CollectionUtils.isEmpty(dept.getSubIndexes())){
                dept.getSubIndexes().forEach(sub->{
                    List<PollutionLineDTO> l1 = map.get(sub);
                    PollutionVO children = new PollutionVO();
                    children.setId(sub);
                    children.setPid(dept.getIndex());
                    children.setName(l1.get(0).getSubstation());
                    children.setData(handleData(getLimitTarget(l1.stream().map(PollutionLineDTO::getId).collect(Collectors.toList()), harmonicPublicParam.getSearchBeginTime(),harmonicPublicParam.getSearchEndTime()),harmonicPublicParam.getStatisticalType().getCode(),l1.stream().map(PollutionLineDTO::getId).collect(Collectors.toList()), harmonicPublicParam.getSearchBeginTime(),harmonicPublicParam.getSearchEndTime()).getRatio());
                    childrenList.add(children);
                });
            }
            if (!CollectionUtils.isEmpty(childrenList)){
                pollutionVO.setChildren(childrenList.stream().sorted(Comparator.comparing(PollutionVO::getData).reversed().thenComparing(PollutionVO::getName)).collect(Collectors.toList()));
            }
            if (!CollectionUtils.isEmpty(dept.getLineIndexes())){
                pollutionVO.setData(handleData(getLimitTarget(lineList, harmonicPublicParam.getSearchBeginTime(),harmonicPublicParam.getSearchEndTime()),harmonicPublicParam.getStatisticalType().getCode(),lineList, harmonicPublicParam.getSearchBeginTime(),harmonicPublicParam.getSearchEndTime()).getRatio());
            }
            list.add(pollutionVO);
        });
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().sorted(Comparator.comparing(PollutionVO::getData).reversed().thenComparing(PollutionVO::getName)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<HarmonicDeptVO> getDeptInfo(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicDeptVO> list = new ArrayList<>();
        List<GeneralDeviceDTO> deptList = generalDeviceInfoClient.getPracticalRunDeviceInfo(param).getData();
        deptList.forEach(item->{
            List<String> lineList = item.getLineIndexes();
            HarmonicDeptVO harmonicDeptVO = new HarmonicDeptVO();
            if (!CollectionUtils.isEmpty(lineList)){
                List<LimitTarget> limitTargetList = getLimitTarget(lineList,param.getSearchBeginTime(),param.getSearchEndTime());
                AreaDTO areaDTO = handleData(limitTargetList,param.getStatisticalType().getCode(),lineList,param.getSearchBeginTime(),param.getSearchEndTime());
                BeanUtil.copyProperties(areaDTO,harmonicDeptVO);
            }
            harmonicDeptVO.setId(item.getIndex());
            harmonicDeptVO.setName(item.getName());
            list.add(harmonicDeptVO);
        });
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().sorted(Comparator.comparing(HarmonicDeptVO::getRatio).reversed().thenComparing(HarmonicDeptVO::getOnlineCount).thenComparing(HarmonicDeptVO::getOverLineCount)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<HarmonicSubstationVO> getSubstationInfoById(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicSubstationVO> list = new ArrayList<>();
        List<GeneralDeviceDTO> subList = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(param).getData();
        subList.forEach(item->{
            HarmonicSubstationVO harmonicSubstationVO = new HarmonicSubstationVO();
            harmonicSubstationVO.setId(item.getIndex());
            harmonicSubstationVO.setName(item.getName());
            List<String> lineList = item.getLineIndexes();
            if (!CollectionUtils.isEmpty(lineList)){
                AreaDTO areaDTO = handleData(getLimitTarget(lineList, param.getSearchBeginTime(),param.getSearchEndTime()),param.getStatisticalType().getCode(),lineList, param.getSearchBeginTime(),param.getSearchEndTime());
                BeanUtil.copyProperties(areaDTO,harmonicSubstationVO);
                int result = getWarningInfo(lineList, param.getSearchBeginTime(),param.getSearchEndTime(),param.getStatisticalType().getCode());
                if (result == -1){
                    harmonicSubstationVO.setWarningFreq(-1.0);
                } else {
                    if (areaDTO.getOverLineCount() == 0){
                        if (areaDTO.getOnlineCount() > 0){
                            harmonicSubstationVO.setWarningFreq(0.0);
                        } else {
                            harmonicSubstationVO.setWarningFreq(-1.0);
                        }
                    } else {
                        harmonicSubstationVO.setWarningFreq(BigDecimal.valueOf(result*1.0/areaDTO.getOverLineCount()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                }
            }
            list.add(harmonicSubstationVO);
        });
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().sorted(Comparator.comparing(HarmonicSubstationVO::getRatio).reversed().thenComparing(HarmonicSubstationVO::getOnlineCount).thenComparing(HarmonicSubstationVO::getOverLineCount)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<HarmonicLineVO> getLineInfoById(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicLineVO> list = new ArrayList<>();
        List<String> line = new ArrayList<>();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())){
            return list;
        }
        List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(param).getData();
        sub.forEach(item->{
            if (Objects.equals(param.getId(),item.getIndex())){
                if (!CollectionUtils.isEmpty(item.getLineIndexes())){
                    line.addAll(item.getLineIndexes());
                }
            }
        });
        if (!CollectionUtils.isEmpty(line)){
            List<LimitTarget> limitTargetList = getLineOverDays(line,param.getSearchBeginTime(),param.getSearchEndTime(),param.getStatisticalType().getCode());
            if (!CollectionUtils.isEmpty(limitTargetList)){
                buildData(list,limitTargetList,param.getStatisticalType().getCode());
            }
        }
        //获取监测点名称
        if (!CollectionUtils.isEmpty(list)){
            List<String> lineList = list.stream().map(HarmonicLineVO::getId).collect(Collectors.toList());
            List<LineDeviceStateVO> lineDeviceStateVOList = lineFeignClient.getAllLine(lineList).getData();
            list.stream().map(item1->lineDeviceStateVOList.stream().filter(item2->Objects.equals(item1.getId(),item2.getId())).findAny().map(item3->{
                item1.setName(item3.getName());
                return list;
            })).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().sorted(Comparator.comparing(HarmonicLineVO::getOverDays).reversed()).collect(Collectors.toList());
        }
        return list;
    }


    @Override
    public List<HarmonicLineVO> getLineRank(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicLineVO> list = new ArrayList<>();
        List<String> lineList = new ArrayList<>();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())){
            return list;
        }
        List<GeneralDeviceDTO> deviceList = generalDeviceInfoClient.getPracticalRunDeviceInfo(param).getData();
        deviceList.forEach(item->{
            if (!CollectionUtils.isEmpty(item.getLineIndexes())){
                lineList.addAll(item.getLineIndexes());
            }
        });
        if (!CollectionUtils.isEmpty(lineList)){
            List<LimitTarget> limitTargetList = getLineOverDays(lineList,param.getSearchBeginTime(),param.getSearchEndTime(),param.getStatisticalType().getCode());
            if (!CollectionUtils.isEmpty(limitTargetList)){
                buildData(list,limitTargetList,param.getStatisticalType().getCode());
            }
        }
        list.sort((item1,item2)->item2.getOverDays().compareTo(item1.getOverDays()));
        //获取监测点名称
        if (!CollectionUtils.isEmpty(list)){
            List<String> l1 = list.stream().map(HarmonicLineVO::getId).collect(Collectors.toList());
            List<LineDeviceStateVO> lineDeviceStateVOList = lineFeignClient.getAllLine(l1).getData();
            list.stream().map(item1->lineDeviceStateVOList.stream().filter(item2->Objects.equals(item1.getId(),item2.getId())).findAny().map(item3->{
                item1.setName(item3.getName());
                return list;
            })).collect(Collectors.toList());
        }
        if (list.size() > Param.UP_LIMIT){
            return list.subList(Param.DOWN_LIMIT,Param.UP_LIMIT);
        }
        return list;
    }

    /**
     * 功能描述: 获取limitTarget数据
     * @param lineList   部门列表
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @return java.util.List<com.njcn.harmonic.pojo.dto.PublicDTO>
     * @author xy
     * @date 2022/2/25 15:05
     */
    public List<LimitTarget> getLimitTarget(List<String> lineList, String startTime, String endTime){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(Param.TIME + " >= '").append(startTime).append("' and ").append(Param.TIME).append(" <= '").append(endTime).append("' and (");
        for (int i=0;i<lineList.size();i++){
            if (lineList.size() - i != 1){
                stringBuilder.append(Param.LINE_ID + "='").append(lineList.get(i)).append("' or ");
            } else {
                stringBuilder.append(Param.LINE_ID + "='").append(lineList.get(i)).append("')");
            }
        }
        stringBuilder.append(" tz('Asia/Shanghai')");
        String sql = "select * from limit_target where " + stringBuilder;
        QueryResult sqlResult = influxDbUtils.query(sql);
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return  resultMapper.toPOJO(sqlResult,LimitTarget.class);
    }

    /**
     * 功能描述: 处理区域(变电站)在线监测点数、超标监测点数、平均超标天数、占比
     * @param list 集合
     *        type 类型
     * @return
     * @author xy
     * @date 2022/2/25 15:05
     */
    public AreaDTO handleData(List<LimitTarget> list,String type,List<String> lineList,String startTime,String endTime) {
        int onlineCount = 0,overLineCount = 0,overCountByDay = 0;
        double avgOverDay = 0.0,ratio = 0.0;
        AreaDTO areaDTO = new AreaDTO();
        if (!CollectionUtils.isEmpty(list)){
            List<LimitTarget> data = getAllData(lineList,startTime,endTime);
            if (!CollectionUtils.isEmpty(data)) {
                onlineCount = data.size();
                //在线监测点个数
                areaDTO.setOnlineCount(onlineCount);
                //超标监测点数
                for (LimitTarget pojo : data) {
                    if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())){
                        if (pojo.getUHarm2OverTime()>0){
                            overLineCount = overLineCount + 1;
                        }
                    } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())){
                        if (pojo.getIHarm2OverTime()>0){
                            overLineCount = overLineCount + 1;
                        }
                    }
                }
            }
        }
        Map<Instant,List<LimitTarget>> map = list.stream().collect(Collectors.groupingBy(LimitTarget::getTime));
        for (Instant key : map.keySet()) {
            int overDay = 0;
            List<LimitTarget> l = map.get(key);
            for (LimitTarget pojo : l) {
                if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())){
                    if (pojo.getUAberranceOverTime()>0 || pojo.getUHarm2OverTime()>0 || pojo.getUHarm3OverTime()>0 || pojo.getUHarm4OverTime()>0 || pojo.getUHarm5OverTime()>0 || pojo.getUHarm6OverTime()>0 || pojo.getUHarm7OverTime()>0 || pojo.getUHarm8OverTime()>0 || pojo.getUHarm9OverTime()>0 || pojo.getUHarm10OverTime()>0 || pojo.getUHarm11OverTime()>0 || pojo.getUHarm12OverTime()>0 || pojo.getUHarm13OverTime()>0 || pojo.getUHarm14OverTime()>0 || pojo.getUHarm15OverTime()>0 || pojo.getUHarm16OverTime()>0 || pojo.getUHarm17OverTime()>0 || pojo.getUHarm18OverTime()>0 || pojo.getUHarm19OverTime()>0 || pojo.getUHarm20OverTime()>0 || pojo.getUHarm21OverTime()>0 || pojo.getUHarm22OverTime()>0 || pojo.getUHarm23OverTime()>0 || pojo.getUHarm24OverTime()>0 || pojo.getUHarm25OverTime()>0){
                        overCountByDay = overCountByDay + 1;
                        overDay = overDay + 1;
                    }
                } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())){
                    if (pojo.getIHarm2OverTime()>0 || pojo.getIHarm3OverTime()>0 || pojo.getIHarm4OverTime()>0 || pojo.getIHarm5OverTime()>0 || pojo.getIHarm6OverTime()>0 || pojo.getIHarm7OverTime()>0 || pojo.getIHarm8OverTime()>0 || pojo.getIHarm9OverTime()>0 || pojo.getIHarm10OverTime()>0 || pojo.getIHarm11OverTime()>0 || pojo.getIHarm12OverTime()>0 || pojo.getIHarm13OverTime()>0 || pojo.getIHarm14OverTime()>0 || pojo.getIHarm15OverTime()>0 || pojo.getIHarm16OverTime()>0 || pojo.getIHarm17OverTime()>0 || pojo.getIHarm18OverTime()>0 || pojo.getIHarm19OverTime()>0 || pojo.getIHarm20OverTime()>0 || pojo.getIHarm21OverTime()>0 || pojo.getIHarm22OverTime()>0 || pojo.getIHarm23OverTime()>0 || pojo.getIHarm24OverTime()>0 || pojo.getIHarm25OverTime()>0){
                        overCountByDay = overCountByDay + 1;
                        overDay = overDay + 1;
                    }
                }
            }
            ratio = ratio + overDay*1.0/l.size();
        }
        //平均超标天数
        if (CollectionUtils.isEmpty(list)){
            avgOverDay = -1.0;
        } else {
            avgOverDay = overLineCount == 0?0.0:BigDecimal.valueOf(overCountByDay*1.0/overLineCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }
         //月监测点超标占比
        ratio = map.size() == 0?-1.0:BigDecimal.valueOf(ratio*100/map.size()).setScale(2, RoundingMode.HALF_UP).doubleValue();
        areaDTO.setOnlineCount(onlineCount);
        areaDTO.setOverLineCount(overLineCount);
        areaDTO.setAverageOverDay(avgOverDay);
        areaDTO.setRatio(Math.min(ratio,100.0));
        return areaDTO;
    }

    /**
     * 功能描述: 处理区域在线监测点数、超标监测点数
     * @param list 集合
     * @return
     * @author xy
     * @date 2022/2/25 15:05
     */
    private List<LimitTarget> getAllData(List<String> list, String startTime, String endTime){
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder stringBuilder1 = new StringBuilder();
        stringBuilder.append(Param.TIME + " >= '").append(startTime).append("' and ").append(Param.TIME).append(" <= '").append(endTime).append("' and (");
        for (int i=0;i<list.size();i++){
            if (list.size() - i != 1){
                stringBuilder.append(Param.LINE_ID + "='").append(list.get(i)).append("' or ");
            } else {
                stringBuilder.append(Param.LINE_ID + "='").append(list.get(i)).append("')");
            }
        }
        stringBuilder.append(" group by line_id tz('Asia/Shanghai')");
        stringBuilder1.append("sum(uaberrance_overtime)+");
        for (int i = 2; i <= 25; i++) {
            if (i==25){
                stringBuilder1.append("sum(uharm_").append(i).append("_overtime) AS ").append("uharm_2").append("_overtime,");
            } else {
                stringBuilder1.append("sum(uharm_").append(i).append("_overtime)+");
            }
        }
        for (int i = 2; i <= 25; i++) {
            if (i==25){
                stringBuilder1.append("sum(iharm_").append(i).append("_overtime) AS ").append("iharm_2").append("_overtime");
            } else {
                stringBuilder1.append("sum(iharm_").append(i).append("_overtime)+");
            }
        }
        String sql = "select "+stringBuilder1+" from limit_target where " + stringBuilder;
        QueryResult sqlResult = influxDbUtils.query(sql);
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return resultMapper.toPOJO(sqlResult,LimitTarget.class);
    }


    /**
     * 功能描述: 获取告警频次
     * @author xy
     * @param lineList    监测点id
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param type        类型
     * @date 2022/4/24 16:47
     * @return
     */
    private Integer getWarningInfo(List<String> lineList, String startTime, String endTime, String type) {
        int result = 0;
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder stringBuilder1 = new StringBuilder();
        stringBuilder.append(Param.TIME + " >= '").append(startTime).append("' and ").append(Param.TIME).append(" <= '").append(endTime).append("' and (");
        for (int i=0;i<lineList.size();i++){
            if (lineList.size() - i != 1){
                stringBuilder.append(Param.LINE_ID + "='").append(lineList.get(i)).append("' or ");
            } else {
                stringBuilder.append(Param.LINE_ID + "='").append(lineList.get(i)).append("')");
            }
        }
        stringBuilder.append(" tz('Asia/Shanghai')");
        if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())){
            stringBuilder1.append("sum(uaberrance_overtime)+");
            for (int i = 2; i <= 25; i++) {
                if (i==25){
                    stringBuilder1.append("sum(uharm_").append(i).append("_overtime)");;
                } else {
                    stringBuilder1.append("sum(uharm_").append(i).append("_overtime)+");
                }
            }
        } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())){
            for (int i = 2; i <= 25; i++) {
                if (i==25){
                    stringBuilder1.append("sum(iharm_").append(i).append("_overtime)");;
                } else {
                    stringBuilder1.append("sum(iharm_").append(i).append("_overtime)+");
                }
            }
        }
        String sql = "select "+stringBuilder1+" from limit_rate where " + stringBuilder;
        QueryResult sqlResult = influxDbUtils.query(sql);
        List<QueryResult.Series> list = sqlResult.getResults().get(0).getSeries();
        if (!CollectionUtils.isEmpty(list)) {
            for (QueryResult.Series series : list) {
                List<List<Object>> valueList = series.getValues();
                if (!CollectionUtils.isEmpty(valueList)) {
                    for (List<Object> value : valueList) {
                        result = (int)Double.parseDouble(value.get(1).toString());
                    }
                }
            }
        } else {
            result = -1;
        }
        return result;
    }



    /**
     * 功能描述: 获取监测点超标天数
     * @author xy
     * @param lineList    监测点id
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param type        类型
     * @date 2022/4/24 16:47
     * @return
     */
    private List<LimitTarget> getLineOverDays(List<String> lineList, String startTime, String endTime, String type) {
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder stringBuilder1 = new StringBuilder();
        stringBuilder.append(Param.TIME + " >= '").append(startTime).append("' and ").append(Param.TIME).append(" <= '").append(endTime).append("' and (");
        for (int i=0;i<lineList.size();i++){
            if (lineList.size() - i != 1){
                stringBuilder.append(Param.LINE_ID + "='").append(lineList.get(i)).append("' or ");
            } else {
                stringBuilder.append(Param.LINE_ID + "='").append(lineList.get(i)).append("')");
            }
        }
        stringBuilder.append(" group by line_id tz('Asia/Shanghai')");
        if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())){
            stringBuilder1.append("sum(uaberrance_overtime) AS uaberrance_overtime,");
            for (int i = 2; i <= 25; i++) {
                if (i==25){
                    stringBuilder1.append("sum(uharm_").append(i).append("_overtime) AS ").append("uharm_").append(i).append("_overtime ");;
                } else {
                    stringBuilder1.append("sum(uharm_").append(i).append("_overtime) AS ").append("uharm_").append(i).append("_overtime,");
                }
            }
        } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())){
            for (int i = 2; i <= 25; i++) {
                if (i==25){
                    stringBuilder1.append("sum(iharm_").append(i).append("_overtime) AS ").append("iharm_").append(i).append("_overtime ");;
                } else {
                    stringBuilder1.append("sum(iharm_").append(i).append("_overtime) AS ").append("iharm_").append(i).append("_overtime,");
                }
            }
        }
        String sql = "select "+stringBuilder1+" from limit_target where " + stringBuilder;
        QueryResult sqlResult = influxDbUtils.query(sql);
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return resultMapper.toPOJO(sqlResult,LimitTarget.class);
    }

    /**
     * 数据组装
     */
    private void buildData(List<HarmonicLineVO> result,List<LimitTarget> list, String type) {
        list.forEach(item->{
            HarmonicLineVO harmonicLineVO = new HarmonicLineVO();
            harmonicLineVO.setId(item.getLineId());
            if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())){
                harmonicLineVO.setOverThreeTimes(item.getUHarm3OverTime());
                harmonicLineVO.setOverFiveTimes(item.getUHarm5OverTime());
                harmonicLineVO.setOverSevenTimes(item.getUHarm7OverTime());
                harmonicLineVO.setOverElevenTimes(item.getUHarm11OverTime());
                harmonicLineVO.setOverThirteenTimes(item.getUHarm13OverTime());
                harmonicLineVO.setOverTwentyThreeTimes(item.getUHarm23OverTime());
                harmonicLineVO.setOverTwentyFiveTimes(item.getUHarm25OverTime());
                int otherTimes = item.getUHarm2OverTime()+item.getUHarm4OverTime()+item.getUHarm6OverTime()+item.getUHarm8OverTime()+item.getUHarm9OverTime()+item.getUHarm10OverTime()+item.getUHarm12OverTime()+item.getUHarm14OverTime()+item.getUHarm15OverTime()+item.getUHarm16OverTime()+item.getUHarm17OverTime()+item.getUHarm18OverTime()+item.getUHarm19OverTime()+item.getUHarm20OverTime()+item.getUHarm21OverTime()+item.getUHarm22OverTime()+item.getUHarm24OverTime();
                harmonicLineVO.setOtherTimes(otherTimes);
                List<Integer> over = Stream.of(item.getUAberranceOverTime(),item.getUHarm2OverTime(),item.getUHarm3OverTime(),item.getUHarm4OverTime(),item.getUHarm5OverTime(),item.getUHarm6OverTime(),item.getUHarm7OverTime(),item.getUHarm8OverTime(),item.getUHarm9OverTime(),item.getUHarm10OverTime(),item.getUHarm11OverTime(),item.getUHarm12OverTime(),item.getUHarm13OverTime(),item.getUHarm14OverTime(),item.getUHarm15OverTime(),item.getUHarm16OverTime(),item.getUHarm17OverTime(),item.getUHarm18OverTime(),item.getUHarm19OverTime(),item.getUHarm20OverTime(),item.getUHarm21OverTime(),item.getUHarm22OverTime(),item.getUHarm23OverTime(),item.getUHarm24OverTime(),item.getUHarm25OverTime()).collect(Collectors.toList());
                harmonicLineVO.setOverDays(Collections.max(over));
            } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())){
                harmonicLineVO.setOverThreeTimes(item.getIHarm3OverTime());
                harmonicLineVO.setOverFiveTimes(item.getIHarm5OverTime());
                harmonicLineVO.setOverSevenTimes(item.getIHarm7OverTime());
                harmonicLineVO.setOverElevenTimes(item.getIHarm11OverTime());
                harmonicLineVO.setOverThirteenTimes(item.getIHarm13OverTime());
                harmonicLineVO.setOverTwentyThreeTimes(item.getIHarm23OverTime());
                harmonicLineVO.setOverTwentyFiveTimes(item.getIHarm25OverTime());
                int otherTimes = item.getIHarm2OverTime()+item.getIHarm4OverTime()+item.getIHarm6OverTime()+item.getIHarm8OverTime()+item.getIHarm9OverTime()+item.getIHarm10OverTime()+item.getIHarm12OverTime()+item.getIHarm14OverTime()+item.getIHarm15OverTime()+item.getIHarm16OverTime()+item.getIHarm17OverTime()+item.getIHarm18OverTime()+item.getIHarm19OverTime()+item.getIHarm20OverTime()+item.getIHarm21OverTime()+item.getIHarm22OverTime()+item.getIHarm24OverTime();
                harmonicLineVO.setOtherTimes(otherTimes);
                List<Integer> over = Stream.of(item.getIHarm2OverTime(),item.getIHarm3OverTime(),item.getIHarm4OverTime(),item.getIHarm5OverTime(),item.getIHarm6OverTime(),item.getIHarm7OverTime(),item.getIHarm8OverTime(),item.getIHarm9OverTime(),item.getIHarm10OverTime(),item.getIHarm11OverTime(),item.getIHarm12OverTime(),item.getIHarm13OverTime(),item.getIHarm14OverTime(),item.getIHarm15OverTime(),item.getIHarm16OverTime(),item.getIHarm17OverTime(),item.getIHarm18OverTime(),item.getIHarm19OverTime(),item.getIHarm20OverTime(),item.getIHarm21OverTime(),item.getIHarm22OverTime(),item.getIHarm23OverTime(),item.getIHarm24OverTime(),item.getIHarm25OverTime()).collect(Collectors.toList());
                harmonicLineVO.setOverDays(Collections.max(over));
            }
            result.add(harmonicLineVO);
        });
    }

}
