package com.njcn.supervision.service.device.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.common.utils.HarmonicTimesUtil;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.device.pq.api.*;
import com.njcn.device.pq.pojo.param.LineBaseQueryParam;
import com.njcn.device.pq.pojo.po.DeptLine;
import com.njcn.device.pq.pojo.vo.OnlineMonitorVo;
import com.njcn.device.pq.pojo.vo.ReportLineInfoVo;
import com.njcn.harmonic.api.RStatLimitRateDClient;
import com.njcn.harmonic.pojo.param.RStatLimitQueryParam;
import com.njcn.harmonic.pojo.po.day.RStatLimitRateDPO;
import com.njcn.harmonic.pojo.po.day.RStatLimitTargetDPO;
import com.njcn.harmonic.pojo.vo.RStatLimitTargetVO;
import com.njcn.harmonic.utils.WordUtil2;
import com.njcn.influx.constant.InfluxDbSqlConstant;
import com.njcn.influx.imapper.*;
import com.njcn.influx.pojo.po.*;
import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.supervision.enums.ProblemTypeEnum;
import com.njcn.supervision.mapper.device.LineWarningMapper;
import com.njcn.supervision.pojo.param.device.OnlineParam;
import com.njcn.supervision.pojo.po.device.LineWarning;
import com.njcn.supervision.pojo.po.leaflet.WarningLeaflet;
import com.njcn.supervision.pojo.vo.device.LineLimitDetailVo;
import com.njcn.supervision.pojo.vo.device.OnlineVo;
import com.njcn.supervision.service.device.ILineWarningService;
import com.njcn.supervision.service.leaflet.IWarningLeafletService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.regex.Pattern.compile;

/**
 * <p>
 * 监测点每日稳态指标超标天数统计表 服务实现类
 * </p>
 *
 * @author xy
 * @since 2024-06-17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LineWarningServiceImpl extends MppServiceImpl<LineWarningMapper, LineWarning> implements ILineWarningService {

    private final DicDataFeignClient dicDataFeignClient;
    private final RStatLimitRateDClient limitRateDClient;
    private final CommTerminalGeneralClient commTerminalGeneralClient;
    private final IWarningLeafletService warningLeafletService;
    private final DeptLineFeignClient deptLineFeignClient;
    private final LineFeignClient lineFeignClient;
    private final FileStorageUtil fileStorageUtil;
    private final DeptFeignClient deptFeignClient;
    private final WordUtil2 wordUtil2;

    private final DataVMapper dataVMapper;
    private final DataIMapper dataIMapper;
    private final DataHarmRateVMapper dataHarmRateVMapper;
    private final DataInHarmVMapper dataInHarmVMapper;
    private final DataPltMapper dataPltMapper;
    private final LineIntegrityClient lineIntegrityClient;
    private final PqDataVerifyCountClient pqDataVerifyCountClient;
    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLineWarning() {
        List<LineWarning> addList = new ArrayList<>();
        List<LineWarning> updateList = new ArrayList<>();
        //获取指标集合(10个指标，包含总指标)
        List<DictData> dataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
        Map<String, DictData> targetMap = dataList.stream().collect(Collectors.toMap(DictData::getCode, Function.identity()));
        //获取当前表的数据
        List<LineWarning> lineWarningList = this.baseMapper.selectList(null);
        Map<String, List<LineWarning>> lineWarningMap = lineWarningList.stream().collect(Collectors.groupingBy(LineWarning::getLineId));
        //获取所有监测点id
        List<String> lineList = commTerminalGeneralClient.getRunMonitorIds().getData();
        RStatLimitQueryParam param = new RStatLimitQueryParam();
        String date = DateUtil.format(LocalDateTime.now().minusDays(1), DatePattern.NORM_DATE_PATTERN);
        param.setDate(date);
        param.setIds(lineList);
        //获取监测点越限信息
        List<RStatLimitTargetDPO> limitTarget = limitRateDClient.monitorIdsGetLimitTargetInfo(param).getData();
        Map<String, RStatLimitTargetDPO> limitMap = limitTarget.stream().collect(Collectors.toMap(RStatLimitTargetDPO::getLineId, Function.identity()));

        for (RStatLimitTargetDPO item : limitTarget) {
            List<LineWarning> lineWarnings = lineWarningMap.get(item.getLineId());
            DeptLine deptLine = deptLineFeignClient.getLineByLineIds(item.getLineId()).getData();
            String deptId = Objects.isNull(deptLine) ? null : deptLine.getId();
            if (CollUtil.isEmpty(lineWarnings)) {
                addList.addAll(getTargetInfo(item.getLineId(), targetMap, limitMap, deptId));
            } else {
                //1.查询各指标越限时间不超过10天，超标则每天递增，不超标则清零
                //2.越限时间超过10天未超过15天，超标则每天递增，不超标保存当前记录，新增一条记录
                //3.越限时间超过15天，超标则每天递增，不超标保存当前记录，新增一条记录
                //4.发过告警单，则重新生成一条数据
                RStatLimitTargetDPO dpo = limitMap.get(item.getLineId());
                //频率偏差
                targetInfo(lineWarnings, targetMap, DicDataEnum.PLPC_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //电压偏差
                targetInfo(lineWarnings, targetMap, DicDataEnum.DYPC_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //长时闪变
                targetInfo(lineWarnings, targetMap, DicDataEnum.CSSB_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //谐波电压
                targetInfo(lineWarnings, targetMap, DicDataEnum.XBDY_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //谐波电流
                targetInfo(lineWarnings, targetMap, DicDataEnum.XBDL_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //间谐波电压
                targetInfo(lineWarnings, targetMap, DicDataEnum.JXBDY_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //负序电压不平衡度
                targetInfo(lineWarnings, targetMap, DicDataEnum.SXDYBPHD_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
                //负序电流
                targetInfo(lineWarnings, targetMap, DicDataEnum.FXDL_ENUM.getCode(), dpo, item.getLineId(), addList, updateList, deptId);
            }
        }
        this.saveBatch(addList);
        this.updateBatchById(updateList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addHeBeiNorthLineWarning(String startTime, String endTime) {
        List<LineWarning> result = new ArrayList<>();
        List<LineWarning> channelData = new ArrayList<>();
        //获取指标集合(10个指标)
        List<DictData> dataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
        Map<String, DictData> targetMap = dataList.stream().collect(Collectors.toMap(DictData::getCode, Function.identity()));
        //获取监测点和部门表关系
        List<DeptLine> deptLines = deptLineFeignClient.getAllData().getData();
        Map<String, DeptLine> deptLineMap = deptLines.stream().collect(Collectors.toMap(DeptLine::getLineId, Function.identity()));

        //获取监测点按时间统计越限天数
        LocalDate firstDayOfMonth = Objects.isNull(startTime) ? LocalDate.now().minusDays(1).with(TemporalAdjusters.firstDayOfMonth()) : LocalDate.parse(startTime);
        String date = Objects.isNull(startTime) ? DateUtil.format(firstDayOfMonth.atStartOfDay(), DatePattern.NORM_DATE_PATTERN) : startTime;
        String endDate = Objects.isNull(endTime) ? DateUtil.format(LocalDateTime.now().minusDays(1), DatePattern.NORM_DATE_PATTERN) : endTime;
        RStatLimitQueryParam rStatLimitQueryParam = new RStatLimitQueryParam(null, date, endDate);
        List<RStatLimitTargetVO> limitTarget = limitRateDClient.monitorOverLimitDays(rStatLimitQueryParam).getData();
        //按各指标统计越限天数
        if (CollUtil.isNotEmpty(limitTarget)) {
            limitTarget.forEach(item -> {
                String deptId = Objects.isNull(deptLineMap.get(item.getLineId())) ? null : deptLineMap.get(item.getLineId()).getId();
                //频率偏差
                LineWarning l1 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.FREQUENCY_DEV.getCode()).getId(), item.getFreqDevOvertime());
                //电压偏差
                LineWarning l2 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.VOLTAGE_DEV.getCode()).getId(), item.getVoltageDevOvertime());
                //长时闪变
                LineWarning l3 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.FLICKER.getCode()).getId(), item.getFlickerOvertime());
                //谐波电压
                LineWarning l4 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.HARMONIC_VOLTAGE.getCode()).getId(), item.getUharmOvertime());
                //谐波电流
                LineWarning l5 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.HARMONIC_CURRENT.getCode()).getId(), item.getIharmOvertime());
                //间谐波电压
                LineWarning l6 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.INTERHARMONIC_VOLTAGE.getCode()).getId(), item.getInuharmOvertime());
                //负序电压不平衡度
                LineWarning l7 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.PHASE_VOLTAGE.getCode()).getId(), item.getUbalanceOvertime());
                //负序电流
                LineWarning l8 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.NEG_CURRENT.getCode()).getId(), item.getINegOvertime());
                //电压总谐波畸变率
                LineWarning l9 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.THD_V.getCode()).getId(), item.getUaberranceOvertime());
                //总稳态指标
                LineWarning l10 = overData(firstDayOfMonth, item.getLineId(), deptId, targetMap.get(DicDataEnum.TOTAL_INDICATOR.getCode()).getId(), item.getAllOvertime());
                result.addAll(Arrays.asList(l1, l2, l3, l4, l5, l6, l7, l8, l9, l10));
            });
        }
        //完整性为0的数据
        LineBaseQueryParam param = new LineBaseQueryParam();
        param.setStartTime(date);
        param.setEndTime(endDate);
        List<OnlineMonitorVo> list = lineIntegrityClient.getNoData(param).getData();
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(item -> {
                String deptId = Objects.isNull(deptLineMap.get(item.getLineId())) ? null : deptLineMap.get(item.getLineId()).getId();
                LineWarning lineWarning = new LineWarning();
                lineWarning.setAlarmTime(firstDayOfMonth);
                lineWarning.setDeptId(deptId);
                lineWarning.setLineId(item.getLineId());
                lineWarning.setTargetType("0");
                lineWarning.setOverLimitDay(item.getLastDay());
                result.add(lineWarning);
            });
        }
        //异常数据
        List<OnlineMonitorVo> list2 = pqDataVerifyCountClient.getAnomalousData(param).getData();
        if (CollUtil.isNotEmpty(list2)) {
            list2.forEach(item -> {
                String deptId = Objects.isNull(deptLineMap.get(item.getLineId())) ? null : deptLineMap.get(item.getLineId()).getId();
                LineWarning lineWarning = new LineWarning();
                lineWarning.setAlarmTime(firstDayOfMonth);
                lineWarning.setDeptId(deptId);
                lineWarning.setLineId(item.getLineId());
                lineWarning.setTargetType("2");
                lineWarning.setOverLimitDay(item.getLastDay());
                result.add(lineWarning);
            });
        }
        //获取时间范围内数据库的数据，然后仅替换累计超标时间
        LambdaQueryWrapper<LineWarning> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(LineWarning::getAlarmTime,date,endDate);
        List<LineWarning> oldData = this.list(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(oldData) && CollUtil.isNotEmpty(result)) {
            // 创建结果数据的查找Map
            Map<String, LineWarning> resultMap = result.stream()
                    .collect(Collectors.toMap(
                            item -> buildKey(item.getDeptId(), item.getLineId(), item.getTargetType()),
                            Function.identity()
                    ));
            for (LineWarning oldItem : oldData) {
                String key = buildKey(oldItem.getDeptId(), oldItem.getLineId(), oldItem.getTargetType());
                LineWarning matchingResult = resultMap.get(key);
                if (matchingResult != null) {
                    oldItem.setOverLimitDay(matchingResult.getOverLimitDay());
                    oldItem.setUpdateTime(LocalDateTime.now());
                    channelData.add(oldItem);
                }
            }
        }
        if (CollUtil.isNotEmpty(channelData)) {
            this.saveOrUpdateBatchByMultiId(channelData);
        } else {
            this.saveOrUpdateBatchByMultiId(result);
        }
    }


    private static String buildKey(String deptId, String lineId, String targetType) {
        return deptId + "|" + lineId + "|" + targetType;
    }

    @Override
    public Page<OnlineVo> getLineWarningList(OnlineParam param) {
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptId());
        deptGetLineParam.setServerName(ServerEnum.HARMONIC.getName());
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetAllLine(deptGetLineParam).getData();
        List<String> lineList = list.stream()
                .flatMap(dto -> dto.getLineBaseList().stream().map(LineDevGetDTO::getPointId))
                .distinct()
                .collect(Collectors.toList());
        QueryWrapper<LineWarning> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(param.getSearchBeginTime()) && Objects.nonNull(param.getSearchEndTime())) {
            queryWrapper.between("A.alarm_time", param.getSearchBeginTime(), param.getSearchEndTime());
        }
        //监测点id
        if (CollUtil.isNotEmpty(lineList)) {
            queryWrapper.in("A.line_id", lineList);
        }
        //监测点类型
        if (StringUtils.isNotBlank(param.getLineType())) {
            queryWrapper.eq("B.Power_Flag", Integer.parseInt(param.getLineType()));
        }
        //监测点名称
        if (StringUtils.isNotBlank(param.getSearchValue()) && !Objects.equals(param.getSearchValue(),"")) {
            queryWrapper.like("p1.Name", param.getSearchValue());
        }
        //查询无数据的监测点
        if (Objects.equals(param.getDataType(), 0)) {
            queryWrapper.eq("A.target_type", "0");
        }
        //异常数据
        else if (Objects.equals(param.getDataType(), 2)) {
            queryWrapper.eq("A.target_type", "2");
        }
        //查询指标超标的监测点
        else {
            queryWrapper.ge("A.over_limit_day", param.getAlarmThreshold());
            if (CollUtil.isNotEmpty(param.getTargetList())) {
                queryWrapper.in("A.target_type", param.getTargetList());
            }
        }
        queryWrapper.orderBy(true, true, "D.Name", "p4.Name", "p3.Name");
        Page<OnlineVo> page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), queryWrapper);
        page.getRecords().forEach(item -> {
            item.setDataType(param.getDataType());
        });
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startReport(OnlineParam.ReportParam param) {
        List<LineWarning> allLineWarnings = new ArrayList<>();
        //获取年份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(param.getSearchBeginTime(), formatter);
        int year = date.getYear();
        param.setYear(String.valueOf(year));
        param.setNumber(getNumber(year));
        //获取部门名称
        String deptName = deptFeignClient.getDeptById(param.getDeptId()).getData().getName();
        param.setDeptName(deptName);
        String inputUrl = "file/warningReport.docx";
        String alarmType = param.getType() == 1 ? "预" : "告";
        //前端下载有问题将【】改成()
        String fileName = "电能(" + alarmType + ")" + param.getYear() + "年" + param.getNumber() + "号-" + param.getDeptName() + "地市 电能质量技术监督" + alarmType + "警单.docx";
        //获取无数据监测点集合
        List<ReportLineInfoVo> list1 = getReportLineInfo(true, param.getIdList(), null, param.getSearchBeginTime(), param.getSearchEndTime(), param.getDeptId(), allLineWarnings);
        //获取谐波电压超标监测点集合
        String vCode = dicDataFeignClient.getDicDataByCode(DicDataEnum.HARMONIC_VOLTAGE.getCode()).getData().getId();
        List<ReportLineInfoVo> list2 = getReportLineInfo(false, param.getIdList(), vCode, param.getSearchBeginTime(), param.getSearchEndTime(), null, allLineWarnings);
        //获取谐波电流超标监测点集合
        String iCode = dicDataFeignClient.getDicDataByCode(DicDataEnum.HARMONIC_CURRENT.getCode()).getData().getId();
        List<ReportLineInfoVo> list3 = getReportLineInfo(false, param.getIdList(), iCode, param.getSearchBeginTime(), param.getSearchEndTime(), null, allLineWarnings);
        try {
            Map<String, Object> dataMap = new HashMap<>(16);
            dataMap.put("${year}", param.getYear());
            dataMap.put("${number}", param.getNumber());
            dataMap.put("${deptName}", param.getDeptName());
            dataMap.put("${startTime}", new SimpleDateFormat(DatePattern.CHINESE_DATE_PATTERN).format(new SimpleDateFormat(DatePattern.NORM_DATE_PATTERN).parse(param.getSearchBeginTime())));
            dataMap.put("${endTime}", new SimpleDateFormat(DatePattern.CHINESE_DATE_PATTERN).format(new SimpleDateFormat(DatePattern.NORM_DATE_PATTERN).parse(param.getSearchEndTime())));
            dataMap.put("${harmonicV}", CollUtil.isEmpty(list2) ? "0" : String.valueOf(list2.size()));
            dataMap.put("${harmonicI}", CollUtil.isEmpty(list3) ? "0" : String.valueOf(list3.size()));
            dataMap.put("${alarmDay}", String.valueOf(param.getAlarmThreshold()));
            dataMap.put("${title}", alarmType + "警");
            dataMap.put("${alarmType}", alarmType);
            dataMap.put("${gdName}", getGdName(param.getDeptName()));
            dataMap.put("${time}", LocalDate.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));

            List<String[]> dataList1 = new ArrayList<>(), dataList2 = new ArrayList<>(), dataList3 = new ArrayList<>();
            if (CollUtil.isNotEmpty(list1)) {
                list1.forEach(item -> {
                    if (Objects.isNull(param.getLineType()) || Objects.equals("", param.getLineType())) {
                        dataList1.add(new String[]{deptName, item.getLineVoltage(), item.getLineName(), item.getSubName(), item.getObjName(), item.getSubVName(), item.getUpdateTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)), item.getIp()});
                    } else if (Integer.parseInt(param.getLineType()) == item.getPowerFlag()) {
                        dataList1.add(new String[]{deptName, item.getLineVoltage(), item.getLineName(), item.getSubName(), item.getObjName(), item.getSubVName(), item.getUpdateTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)), item.getIp()});
                    }
                });
                dataMap.put("${noData}", CollUtil.isEmpty(dataList1) ? "0" : String.valueOf(dataList1.size()));
            } else {
                dataMap.put("${noData}", "0");
            }
            if (CollUtil.isNotEmpty(list2)) {
                list2.forEach(item -> {
                    dataList2.add(new String[]{deptName, item.getLineName(), item.getSubName(), item.getObjName(), String.valueOf(item.getOverDays())});
                });
            }
            if (CollUtil.isNotEmpty(list3)) {
                list3.forEach(item -> {
                    dataList3.add(new String[]{deptName, item.getLineName(), item.getSubName(), item.getObjName(), String.valueOf(item.getOverDays()), String.valueOf(item.getShortCapacity()), String.valueOf(item.getDevCapacity()), String.valueOf(item.getDealCapacity())});
                });
            }

            List<List<String[]>> tableList = Arrays.asList(dataList1, dataList2, dataList3);
            InputStream inputStream = wordUtil2.getReportFile(inputUrl, dataMap, tableList);
            //上传文件服务器
            String path = fileStorageUtil.uploadStreamSpecifyName(inputStream, OssPath.ONLINE_REPORT, fileName);
            //1.生成预告警单数据
            String leafletId = warningLeafletService.createLeaflet(
                    ProblemTypeEnum.ONLINE.getName()
                    , param.getDeptId()
                    , IdWorker.get32UUID()
                    , null
                    , ProblemTypeEnum.ONLINE.getCode()
                    , param.getType()
                    , param.getIssueDetail()
                    , param.getReformAdvice()
                    , path);
            //2.将选择的数据状态改成预警或者告警 && 将选择的数据添加预告警单id
            if (CollUtil.isNotEmpty(allLineWarnings)) {
                LambdaQueryWrapper<LineWarning> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.in(LineWarning::getId, param.getIdList())
                        .notIn(LineWarning::getTargetType, Arrays.asList(vCode, iCode))
                        .between(LineWarning::getAlarmTime, param.getSearchBeginTime(), param.getSearchEndTime());
                allLineWarnings.addAll(this.baseMapper.selectList(lambdaQueryWrapper));
                allLineWarnings.forEach(item -> {
                    item.setStep(param.getType());
                    item.setInitiateWarningFlag(1);
                    if (!Objects.equals(item.getTargetType(), "0")) {
                        item.setAlertThreshold(param.getAlertThreshold());
                        item.setAlarmThreshold(param.getAlarmThreshold());
                    }
                    item.setLeafletId(leafletId);
                });
                this.updateBatchByMultiId(allLineWarnings);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<LineLimitDetailVo> getOverLimitDetail(OnlineParam.DetailParam param) {
        List<LineLimitDetailVo> result = new ArrayList<>();
        String targetCode = dicDataFeignClient.getDicDataById(param.getTargetId()).getData().getCode();
        //获取监测点统计间隔
        Integer timeInterval = commTerminalGeneralClient.getMonitorDetail(param.getLineId()).getData().getInterval();
        //获取限值
        Overlimit overlimit = commTerminalGeneralClient.getOverLimitData(param.getLineId()).getData();
        //处理数据
        List<LineLimitDetailVo> data = chanelTarget(param, overlimit, timeInterval, targetCode);
        if (CollUtil.isNotEmpty(data)) {
            result = data.stream().sorted(Comparator.comparing(LineLimitDetailVo::getTime)).collect(Collectors.toList());
        }
        return result;
    }

    //指标数据处理
    public List<LineLimitDetailVo> chanelTarget(OnlineParam.DetailParam param, Overlimit overlimit, Integer timeInterval, String targetCode) {
        List<LineLimitDetailVo> result = new ArrayList<>(), finalList = new ArrayList<>();
        //频率偏差
        if (Objects.equals(targetCode, DicDataEnum.FREQUENCY_DEV.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 1).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataV> freqDevList = getFreqDev(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(freqDevList)) {
                        double maxData = freqDevList.get(0).getFreqDev();
                        channelEachData(item, maxData > 0 ? overlimit.getFreqDev() : -overlimit.getFreqDev(), "getFreqDev", result, DicDataEnum.FREQUENCY_DEV.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //电压偏差
        if (Objects.equals(targetCode, DicDataEnum.VOLTAGE_DEV.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 2).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    Float overLimit;
                    Double maxData;
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataV> voltageList = getVoltageDev(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(voltageList)) {
                        List<Double> voltage = voltageList.stream().map(DataV::getVuDev).collect(Collectors.toList());
                        if (Math.abs(voltage.get(0)) >= Math.abs(voltage.get(1))) {
                            overLimit = overlimit.getUvoltageDev();
                            maxData = voltage.get(0);
                        } else {
                            overLimit = overlimit.getVoltageDev();
                            maxData = voltage.get(1);
                        }
                        channelEachData(item, overLimit, "getVoltageDev", result, DicDataEnum.VOLTAGE_DEV.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //长时闪变
        if (Objects.equals(targetCode, DicDataEnum.FLICKER.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 3).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataPlt> dataPltList = getFlicker(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(dataPltList)) {
                        double maxData = dataPltList.get(0).getPlt();
                        channelEachData(item, overlimit.getFlicker(), "getFlicker", result, DicDataEnum.FLICKER.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //电压总谐波畸变率
        if (Objects.equals(targetCode, DicDataEnum.THD_V.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 4).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataV> dataVList = getVThd(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(dataVList)) {
                        double maxData = dataVList.get(0).getVThd();
                        channelEachData(item, overlimit.getUaberrance(), "getUaberrance", result, DicDataEnum.THD_V.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //谐波电压
        if (Objects.equals(targetCode, DicDataEnum.HARMONIC_VOLTAGE.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            //电压总谐波畸变率
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 4).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataV> dataVList = getVThd(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(dataVList)) {
                        double maxData = dataVList.get(0).getVThd();
                        channelEachData(item, overlimit.getUaberrance(), "getUaberrance", result, DicDataEnum.THD_V.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
            //谐波电压含有率2~25次
            List<RStatLimitRateDPO> list2 = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 7).getData();
            if (CollUtil.isNotEmpty(list2)) {
                list2.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataHarmRateV> dataHarmRateVList = getDataHarmRateV(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59");
                    if (CollUtil.isNotEmpty(dataHarmRateVList)) {
                        DataHarmRateV dataHarmRateV = dataHarmRateVList.get(0);
                        channelHarmonicData(dataHarmRateV, null, null, item, overlimit, result, "getUharm", DicDataEnum.HARMONIC_VOLTAGE.getName(), timeInterval, 2, 25);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //谐波电流
        if (Objects.equals(targetCode, DicDataEnum.HARMONIC_CURRENT.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 8).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataI> dataIList = getDataI(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59");
                    if (CollUtil.isNotEmpty(dataIList)) {
                        DataI dataI = dataIList.get(0);
                        channelHarmonicData(null, dataI, null, item, overlimit, result, "getIharm", DicDataEnum.HARMONIC_CURRENT.getName(), timeInterval, 2, 25);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //间谐波电压
        if (Objects.equals(targetCode, DicDataEnum.INTERHARMONIC_VOLTAGE.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 9).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataInHarmV> dataInHarmVList = getDataInHarmV(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59");
                    if (CollUtil.isNotEmpty(dataInHarmVList)) {
                        DataInHarmV dataInHarmV = dataInHarmVList.get(0);
                        channelHarmonicData(null, null, dataInHarmV, item, overlimit, result, "getInuharm", DicDataEnum.INTERHARMONIC_VOLTAGE.getName(), timeInterval, 1, 16);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //负序电压不平衡度
        if (Objects.equals(targetCode, DicDataEnum.PHASE_VOLTAGE.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 5).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataV> dataVList = getUnbalance(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(dataVList)) {
                        double maxData = dataVList.get(0).getVUnbalance();
                        channelEachData(item, overlimit.getUbalance(), "getUbalance", result, DicDataEnum.PHASE_VOLTAGE.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        //负序电流
        if (Objects.equals(targetCode, DicDataEnum.NEG_CURRENT.getCode()) || Objects.equals(targetCode, DicDataEnum.TOTAL_INDICATOR.getCode())) {
            List<RStatLimitRateDPO> list = limitRateDClient.getOverData(param.getLineId(), param.getSearchBeginTime(), param.getSearchEndTime(), 6).getData();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    String time = item.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                    List<DataI> dataIList = getINeg(param.getLineId()
                            , time + " 00:00:00"
                            , time + " 23:59:59"
                    );
                    if (CollUtil.isNotEmpty(dataIList)) {
                        double maxData = dataIList.get(0).getINeg();
                        channelEachData(item, overlimit.getINeg(), "getINeg", result, DicDataEnum.NEG_CURRENT.getName(), timeInterval, maxData);
                    } else {
                        log.info("{}原始数据缺失", time);
                    }
                });
            }
        }
        if (CollUtil.isNotEmpty(result)) {
            Map<LocalDate, List<LineLimitDetailVo>> map = result.stream().collect(Collectors.groupingBy(LineLimitDetailVo::getTime, LinkedHashMap::new, Collectors.toList()));
            map.forEach((k, v) -> {
                StringBuilder describe = new StringBuilder();
                LineLimitDetailVo lineLimitDetailVo = new LineLimitDetailVo();
                lineLimitDetailVo.setTime(k);
                v.forEach(item -> {
                    describe.append(item.getOverLimitInfo());
                });
                lineLimitDetailVo.setOverLimitInfo(describe.toString());
                finalList.add(lineLimitDetailVo);
            });
        }
        return finalList;
    }

    //处理单指标
    public void channelEachData(RStatLimitRateDPO dpo, float limit, String getColum, List<LineLimitDetailVo> result, String targetName, Integer timeInterval, double maxData) {
        try {
            Class<?> clazz = dpo.getClass();
            String methodName = getColum + "Overtime";
            Method method;
            method = clazz.getMethod(methodName);
            int value = (int) method.invoke(dpo);
            LineLimitDetailVo vo = new LineLimitDetailVo();
            vo.setTime(dpo.getTime());
            vo.setOverLimitInfo(targetName + "最大幅值:" + PubUtils.doubleRound(2, maxData) + ",限值:" + limit + ",超标时间:" + value * timeInterval + "分钟;");
            result.add(vo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //处理谐波数据 谐波电压、谐波电流、间谐波电压
    public void channelHarmonicData(DataHarmRateV dataHarmRateV, DataI dataI, DataInHarmV dataInHarmV, RStatLimitRateDPO dpo, Overlimit overlimit, List<LineLimitDetailVo> result, String getColum, String targetName, Integer timeInterval, Integer startTimes, Integer endTimes) {
        LinkedHashMap<Integer, Integer> overMap = new LinkedHashMap<>();
        StringBuilder describe = new StringBuilder();
        LineLimitDetailVo vo = new LineLimitDetailVo();
        vo.setTime(dpo.getTime());
        //查看具体哪几次超标
        Class<?> clazz = dpo.getClass();
        for (int i = startTimes; i <= endTimes; i++) {
            String methodName = getColum + i + "Overtime";
            try {
                Method method = clazz.getMethod(methodName);
                int value = (int) method.invoke(dpo);
                if (value > 0) {
                    overMap.put(i, value);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        Class<?> clazz2 = null;
        String targetName2 = null;
        double value2;
        if (Objects.nonNull(dataHarmRateV)) {
            clazz2 = dataHarmRateV.getClass();
            targetName2 = "getV";
        } else if (Objects.nonNull(dataI)) {
            clazz2 = dataI.getClass();
            targetName2 = "getI";
        } else if (Objects.nonNull(dataInHarmV)) {
            clazz2 = dataInHarmV.getClass();
            targetName2 = "getV";
        }
        for (Integer key : overMap.keySet()) {
            int value = overMap.get(key);
            String methodName = targetName2 + key;
            Method method;
            try {
                method = clazz2.getMethod(methodName);
                if (Objects.nonNull(dataHarmRateV)) {
                    value2 = (double) method.invoke(dataHarmRateV);
                    describe.append(key).append("次").append(targetName).append("CP95值最大幅值:").append(PubUtils.doubleRound(2, value2)).append("%,限值:").append(getOverLimitData(overlimit, getColum, key)).append("%,超标时间:").append(value * timeInterval).append("分钟;");
                } else if (Objects.nonNull(dataI)) {
                    value2 = (double) method.invoke(dataI);
                    describe.append(key).append("次").append(targetName).append("CP95值最大幅值:").append(PubUtils.doubleRound(2, value2)).append("%,限值:").append(getOverLimitData(overlimit, getColum, key)).append("%,超标时间:").append(value * timeInterval).append("分钟;");
                } else if (Objects.nonNull(dataInHarmV)) {
                    value2 = (double) method.invoke(dataInHarmV);
                    describe.append((key - 0.5)).append("次").append(targetName).append("CP95值最大幅值:").append(PubUtils.doubleRound(2, value2)).append("%,限值:").append(getOverLimitData(overlimit, getColum, key)).append("%,超标时间:").append(value * timeInterval).append("分钟;");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        vo.setOverLimitInfo(describe.toString().trim());
        result.add(vo);
    }

    /**
     * 获取供电公司名称
     */
    public String getGdName(String deptName) {
        String gdName;
        if (Objects.equals(deptName, "风光储") || Objects.equals(deptName, "超高压")) {
            gdName = deptName + "公司";
        } else {
            gdName = deptName + "供电公司";
        }
        return gdName;
    }

    public List<ReportLineInfoVo> getReportLineInfo(boolean type, List<String> idList, String codeId, String startTime, String endTime, String deptId, List<LineWarning> allLineWarnings) {
        List<ReportLineInfoVo> list = new ArrayList<>();
        LambdaQueryWrapper<LineWarning> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (type) {
            lambdaQueryWrapper.eq(LineWarning::getTargetType, "0")
                    .eq(LineWarning::getDeptId, deptId)
                    .between(LineWarning::getAlarmTime, startTime, endTime);
        } else {
            lambdaQueryWrapper.eq(LineWarning::getTargetType, codeId)
                    .in(LineWarning::getId, idList)
                    .between(LineWarning::getAlarmTime, startTime, endTime);
        }
        List<LineWarning> warnings = this.baseMapper.selectList(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(warnings)) {
            allLineWarnings.addAll(warnings);
            List<String> lineList = warnings.stream().map(LineWarning::getLineId).collect(Collectors.toList());
            list = lineFeignClient.getReportLineInfo(lineList).getData();
            if (!type) {
                Map<String, Integer> lineIdOverLimitDayMap = warnings.stream().collect(Collectors.toMap(LineWarning::getLineId, LineWarning::getOverLimitDay));
                list.forEach(item1 -> {
                    String lineId = item1.getLineId();
                    Integer overLimitDay = lineIdOverLimitDayMap.getOrDefault(lineId, null);
                    if (overLimitDay != null) {
                        item1.setOverDays(overLimitDay);
                    }
                });
            }
        }
        return list;
    }

    /**
     * 获取监测点各指标的超标天数
     */
    public List<LineWarning> getTargetInfo(String lineId, Map<String, DictData> map, Map<String, RStatLimitTargetDPO> limitMap, String deptId) {
        List<LineWarning> result = new ArrayList<>();
        map.forEach((k, v) -> {
            LineWarning lineWarning = new LineWarning();
            lineWarning.setAlarmTime(LocalDate.now().minusDays(1));
            lineWarning.setDeptId(deptId);
            lineWarning.setLineId(lineId);
            lineWarning.setTargetType(v.getId());
            lineWarning.setOverLimitDay(overDay(k, limitMap.get(lineId)));
            lineWarning.setInitiateWarningFlag(0);
            lineWarning.setStep(0);
            result.add(lineWarning);
        });
        return result;
    }

    public LineWarning overData(LocalDate date, String lineId, String deptId, String codeId, Integer overDays) {
        LineWarning lineWarning = new LineWarning();
        lineWarning.setAlarmTime(date);
        lineWarning.setDeptId(deptId);
        lineWarning.setLineId(lineId);
        lineWarning.setTargetType(codeId);
        lineWarning.setOverLimitDay(overDays);
        return lineWarning;
    }

    public int overDay(String code, RStatLimitTargetDPO limitTarget) {
        int result = 0;
        try {
            //频率偏差
            if (Objects.equals(code, DicDataEnum.PLPC_ENUM.getCode())) {
                result = limitTarget.getFreqDevOvertime();
            }
            //电压偏差
            else if (Objects.equals(code, DicDataEnum.DYPC_ENUM.getCode())) {
                result = limitTarget.getVoltageDevOvertime();
            }
            //长时闪变
            else if (Objects.equals(code, DicDataEnum.CSSB_ENUM.getCode())) {
                result = limitTarget.getFlickerOvertime();
            }
            //谐波电压
            else if (Objects.equals(code, DicDataEnum.XBDY_ENUM.getCode())) {
                int sum = 0;
                Class<?> clazz = limitTarget.getClass();
                for (int i = 2; i <= 25; i++) {
                    String methodName = "getUharm" + i + "Overtime";
                    Method method = clazz.getMethod(methodName);
                    int value = (int) method.invoke(limitTarget);
                    sum += value;
                }
                result = limitTarget.getUaberranceOvertime() + sum;
            }
            //谐波电流
            else if (Objects.equals(code, DicDataEnum.XBDL_ENUM.getCode())) {
                int sum = 0;
                Class<?> clazz = limitTarget.getClass();
                for (int i = 2; i <= 25; i++) {
                    String methodName = "getIharm" + i + "Overtime";
                    Method method = clazz.getMethod(methodName);
                    int value = (int) method.invoke(limitTarget);
                    sum += value;
                }
                result = sum;
            }
            //间谐波电压
            else if (Objects.equals(code, DicDataEnum.JXBDY_ENUM.getCode())) {
                int sum = 0;
                Class<?> clazz = limitTarget.getClass();
                for (int i = 1; i <= 16; i++) {
                    String methodName = "getInuharm" + i + "Overtime";
                    Method method = clazz.getMethod(methodName);
                    int value = (int) method.invoke(limitTarget);
                    sum += value;
                }
                result = sum;
            }
            //负序电压不平衡度
            else if (Objects.equals(code, DicDataEnum.SXDYBPHD_ENUM.getCode())) {
                result = limitTarget.getUbalanceOvertime();
            }
            //负序电流
            else if (Objects.equals(code, DicDataEnum.FXDL_ENUM.getCode())) {
                result = limitTarget.getINegOvertime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result > 0 ? 1 : 0;
    }

    /**
     * 各指标计算 系统默认阈值:预警单10天 告警单15天
     */
    public void targetInfo(List<LineWarning> lineWarnings, Map<String, DictData> targetMap, String target, RStatLimitTargetDPO dpo, String item, List<LineWarning> addList, List<LineWarning> updateList, String deptId) {
        List<LineWarning> l1 = lineWarnings.stream().filter(o -> Objects.equals(o.getTargetType(), targetMap.get(target).getId())).collect(Collectors.toList());
        //获取最新的一条记录
        LineWarning line = l1.stream().max(Comparator.comparing(LineWarning::getAlarmTime)).orElse(null);
        //当前监测点连续越限天数
        int day = 0;
        if (line != null) {
            day = line.getOverLimitDay();
        }
        //当天是否越限 0:未越限 1:越限
        int result = overDay(target, dpo);
        if (result == 0) {
            if (day < 10) {
                line.setOverLimitDay(0);
                updateList.add(line);
            } else {
                LineWarning lineWarning = new LineWarning();
                lineWarning.setAlarmTime(LocalDate.now().minusDays(1));
                lineWarning.setDeptId(deptId);
                lineWarning.setLineId(item);
                lineWarning.setTargetType(targetMap.get(target).getId());
                lineWarning.setOverLimitDay(0);
                lineWarning.setInitiateWarningFlag(0);
                lineWarning.setStep(0);
                addList.add(lineWarning);
            }
        } else {
            if (day < 9) {
                line.setOverLimitDay(day + 1);
            } else if (day < 14) {
                line.setOverLimitDay(day + 1);
                line.setStep(1);
                line.setAlertThreshold(10);
                line.setAlarmThreshold(15);
                line.setThresholdResource(0);
            } else {
                //已发告警单，重新生成记录
                if (line.getInitiateWarningFlag() == 1 && line.getStep() == 2) {
                    LineWarning lineWarning = new LineWarning();
                    lineWarning.setAlarmTime(LocalDate.now().minusDays(1));
                    lineWarning.setDeptId(deptId);
                    lineWarning.setLineId(item);
                    lineWarning.setTargetType(targetMap.get(target).getId());
                    lineWarning.setOverLimitDay(result);
                    lineWarning.setInitiateWarningFlag(0);
                    lineWarning.setStep(0);
                    addList.add(lineWarning);
                }
                //未发告警单，继续添加越限天数
                else {
                    line.setOverLimitDay(day + 1);
                    line.setStep(2);
                }
            }
            updateList.add(line);
        }
    }

    private float getOverLimitData(Overlimit overlimit, String targetName, Integer times) {
        float result;
        Class<?> clazz = overlimit.getClass();
        String methodName = targetName + times;
        try {
            Method method = clazz.getMethod(methodName);
            result = (float) method.invoke(overlimit);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 查询库里面的编号
     */
    public String getNumber(Integer year) {
        LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
        LocalDate lastDayOfYear = LocalDate.of(year + 1, 1, 1).minusDays(1);
        LambdaQueryWrapper<WarningLeaflet> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarningLeaflet::getState, 1)
                .eq(WarningLeaflet::getProblemType, 2)
                .like(WarningLeaflet::getFilePath,year);
//                .between(WarningLeaflet::getCreateTime, firstDayOfYear, lastDayOfYear);
        List<WarningLeaflet> list = warningLeafletService.list(lambdaQueryWrapper);
        if (list.isEmpty()) {
            return "1";
        }
        // 编译正则表达式，用于匹配文件中的编号
        Pattern pattern = compile("年(\\d+)号");
        int maxNumber = 0;
        for (WarningLeaflet leaflet : list) {
            String filePath = leaflet.getFilePath();
            Matcher matcher = pattern.matcher(filePath);
            if (matcher.find()) {
                int number = Integer.parseInt(matcher.group(1));
                maxNumber = Math.max(maxNumber, number);
            }
        }
        return String.valueOf(maxNumber + 1);
    }

    public static void main(String[] args) {
        Pattern pattern = compile("年(\\d+)号");
        String filePath = "onlineReport/电能[告]2025年28号-海口地市 电能质量技术监督告警单.docx";
        Matcher matcher = pattern.matcher(filePath);

        if (matcher.find()) {
            int number = Integer.parseInt(matcher.group(1));
            System.out.println(number);
        }
    }


    /**
     * 获取频率偏差-日最大值-最大值
     */
    public List<DataV> getFreqDev(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper2 = new InfluxQueryWrapper(DataV.class);
        influxQueryWrapper2.eq(DataV::getLineId, lineIndex)
                .eq(DataV::getValueType, InfluxDbSqlConstant.MAX)
                .eq(DataV::getPhaseType, "T")
                .max(DataV::getFreqDev)
                .between(DataV::getTime, startTime, endTime);
        return dataVMapper.getStatisticsByWraper(influxQueryWrapper2);
    }

    /**
     * 获取电压偏差-日最大值&&日最小值 日最大值的最大值 日最小值的最小值
     */
    public List<DataV> getVoltageDev(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataV.class);
        influxQueryWrapper.eq(DataV::getLineId, lineIndex)
                .eq(DataV::getValueType, InfluxDbSqlConstant.MIN)
                .regular(DataV::getPhaseType, Arrays.asList("A", "B", "C"))
                .min(DataV::getVuDev)
                .between(DataV::getTime, startTime, endTime);
        List<DataV> result = new ArrayList<>(dataVMapper.getStatisticsByWraper(influxQueryWrapper));
        InfluxQueryWrapper influxQueryWrapper2 = new InfluxQueryWrapper(DataV.class);
        influxQueryWrapper2.eq(DataV::getLineId, lineIndex)
                .eq(DataV::getValueType, InfluxDbSqlConstant.MAX)
                .regular(DataV::getPhaseType, Arrays.asList("A", "B", "C"))
                .max(DataV::getVuDev)
                .between(DataV::getTime, startTime, endTime);
        result.addAll(dataVMapper.getStatisticsByWraper(influxQueryWrapper2));
        return result;
    }

    /**
     * 获取长时闪变-日最大值-最大值
     */
    public List<DataPlt> getFlicker(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataPlt.class);
        influxQueryWrapper.eq(DataPlt::getLineId, lineIndex)
                .regular(DataPlt::getPhaseType, Arrays.asList("A", "B", "C"))
                .max(DataPlt::getPlt)
                .between(DataPlt::getTime, startTime, endTime);
        return dataPltMapper.getStatisticsByWraper(influxQueryWrapper);
    }

    /**
     * 获取电压总谐波畸变率-日CP95-最大值
     */
    public List<DataV> getVThd(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataV.class);
        influxQueryWrapper.eq(DataV::getLineId, lineIndex)
                .eq(DataV::getValueType, InfluxDbSqlConstant.CP95)
                .regular(DataV::getPhaseType, Arrays.asList("A", "B", "C"))
                .max(DataV::getVThd)
                .between(DataV::getTime, startTime, endTime);
        return dataVMapper.getStatisticsByWraper(influxQueryWrapper);
    }

    /**
     * 获取负序电压不平衡度-日最大值-CP95
     */
    public List<DataV> getUnbalance(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataV.class);
        influxQueryWrapper.eq(DataV::getLineId, lineIndex)
                .eq(DataV::getValueType, InfluxDbSqlConstant.CP95)
                .eq(DataV::getPhaseType, "T")
                .max(DataV::getVUnbalance)
                .between(DataV::getTime, startTime, endTime);
        return dataVMapper.getStatisticsByWraper(influxQueryWrapper);
    }

    /**
     * 获取负序电流-日最大值-CP95
     */
    public List<DataI> getINeg(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class);
        influxQueryWrapper.eq(DataI::getLineId, lineIndex)
                .eq(DataI::getValueType, InfluxDbSqlConstant.CP95)
                .eq(DataI::getPhaseType, "T")
                .max(DataI::getINeg)
                .between(DataI::getTime, startTime, endTime);
        return dataIMapper.getStatisticsByWraper(influxQueryWrapper);
    }

    /**
     * 获取谐波电压含有率 2~25次数据
     */
    public List<DataHarmRateV> getDataHarmRateV(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class);
        influxQueryWrapper.maxSamePrefixAndSuffix(InfluxDbSqlConstant.V, "", HarmonicTimesUtil.harmonicTimesList(2, 25, 1));
        influxQueryWrapper.eq(DataHarmRateV::getLineId, lineIndex)
                .eq(DataHarmRateV::getValueType, InfluxDbSqlConstant.CP95)
                .regular(DataHarmRateV::getPhaseType, Arrays.asList("A", "B", "C"))
                .between(DataHarmRateV::getTime, startTime, endTime);
        return dataHarmRateVMapper.getStatisticsByWraper(influxQueryWrapper);
    }

    /**
     * 获取谐波电流含有率 2~25次数据
     */
    public List<DataI> getDataI(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class);
        influxQueryWrapper.maxSamePrefixAndSuffix(InfluxDbSqlConstant.I, "", HarmonicTimesUtil.harmonicTimesList(2, 25, 1));
        influxQueryWrapper.eq(DataI::getLineId, lineIndex)
                .eq(DataI::getValueType, InfluxDbSqlConstant.CP95)
                .regular(DataI::getPhaseType, Arrays.asList("A", "B", "C"))
                .between(DataI::getTime, startTime, endTime);
        return dataIMapper.getStatisticsByWraper(influxQueryWrapper);
    }

    /**
     * 获取间谐波电压含有率 2~25次数据
     */
    public List<DataInHarmV> getDataInHarmV(String lineIndex, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataInHarmV.class);
        influxQueryWrapper.maxSamePrefixAndSuffix(InfluxDbSqlConstant.V, "", HarmonicTimesUtil.harmonicTimesList(1, 16, 1));
        influxQueryWrapper.eq(DataInHarmV::getLineId, lineIndex)
                .eq(DataInHarmV::getValueType, InfluxDbSqlConstant.CP95)
                .regular(DataInHarmV::getPhaseType, Arrays.asList("A", "B", "C"))
                .between(DataInHarmV::getTime, startTime, endTime);
        return dataInHarmVMapper.getStatisticsByWraper(influxQueryWrapper);
    }
}
