package com.njcn;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONTokener;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsCommTerminalFeignClient;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csharmonic.CsHarmonicBootApplication;
import com.njcn.csharmonic.enums.CsHarmonicResponseEnum;
import com.njcn.csharmonic.service.ICsSysExcelRelationService;
import com.njcn.csharmonic.service.ILineTargetService;
import com.njcn.device.biz.pojo.po.PqsDeviceUnit;
import com.njcn.harmonic.common.mapper.ExcelRptTempMapper;
import com.njcn.harmonic.common.pojo.dto.DeviceUnitCommDTO;
import com.njcn.harmonic.common.pojo.vo.ReportTemplateVO;
import com.njcn.harmonic.common.service.CustomReportTableService;
import com.njcn.harmonic.enums.HarmonicResponseEnum;
import com.njcn.harmonic.pojo.dto.ReportTemplateDTO;
import com.njcn.harmonic.pojo.param.ReportSearchParam;
import com.njcn.harmonic.pojo.po.ExcelRptTemp;
import com.njcn.oss.constant.GeneralConstant;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.enums.OssResponseEnum;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年12月10日 15:05
 */
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = CsHarmonicBootApplication.class)
public class BaseJunitTest {

    @Autowired
    private ILineTargetService lineTargetService;
    @Autowired
    private ICsSysExcelRelationService sysExcelService;
    @Autowired
    private DicDataFeignClient dicDataFeignClient;
    @Autowired
    private CsLineFeignClient csLineFeignClient;
    @Autowired
    private ExcelRptTempMapper excelRptTempMapper;
    @Autowired
    private CsCommTerminalFeignClient csCommTerminalFeignClient;
    @Autowired
    private CustomReportTableService customReportTableService;
    @Autowired
    private FileStorageUtil fileStorageUtil;
    @Autowired
    private EpdFeignClient epdFeignClient;

    private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);

    private static final Map<String, String> PHASE_MAPPING = new HashMap<String, String>() {
        {
            this.put("AB", "A");
            this.put("BC", "B");
            this.put("CA", "C");
            this.put("M", "T");
        }
    };


    public void getCustomReport(ReportSearchParam reportSearchParam, Map<String, String> newMap, DeviceUnitCommDTO deviceUnitCommDTO, HttpServletResponse response) {
        TimeInterval timeInterval = new TimeInterval();
        ExcelRptTemp excelRptTemp = (ExcelRptTemp)this.excelRptTempMapper.selectById(reportSearchParam.getTempId());
        if (Objects.isNull(excelRptTemp)) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_ACTIVE);
        } else {
            if (Objects.isNull(reportSearchParam.getCustomType())) {
                this.analyzeReport(reportSearchParam, excelRptTemp, newMap, deviceUnitCommDTO, response);
            }

        }
    }

    private void analyzeReport(ReportSearchParam reportSearchParam, ExcelRptTemp excelRptTemp, Map<String, String> newMap, DeviceUnitCommDTO deviceUnitCommDTO, HttpServletResponse response) {
        List<Future<?>> futures = new ArrayList();
        List<ReportTemplateDTO> reportTemplateDTOList = new ArrayList();
        List<ReportTemplateDTO> reportLimitList = new ArrayList();
        List<ReportTemplateDTO> terminalList = new ArrayList();

        JSONArray jsonArray;
        try {
            InputStream fileStream = this.fileStorageUtil.getFileStream(excelRptTemp.getContent());
            Throwable var12 = null;

            try {
                jsonArray = new JSONArray(new JSONTokener(fileStream, new JSONConfig()));
                this.parseTemplate(jsonArray, reportTemplateDTOList, reportLimitList, terminalList);
            } catch (Throwable var32) {
                var12 = var32;
                throw var32;
            } finally {
                if (fileStream != null) {
                    if (var12 != null) {
                        try {
                            fileStream.close();
                        } catch (Throwable var30) {
                            var12.addSuppressed(var30);
                        }
                    } else {
                        fileStream.close();
                    }
                }

            }
        } catch (Exception var34) {
            Exception e = var34;
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            }

            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_JSON);
        }

        DictData dictData = (DictData)this.dicDataFeignClient.getDicDataByCodeAndType(DicDataEnum.EPD.getCode(), DicDataTypeEnum.CS_DATA_TYPE.getCode()).getData();
        if (Objects.isNull(dictData)) {
            throw new BusinessException(CommonResponseEnum.FAIL, "字典类型模板缺少!");
        } else {
            DictData epdDic = (DictData)this.dicDataFeignClient.getDicDataByCodeAndType(DicDataEnum.EPD.getCode(), DicDataTypeEnum.CS_DATA_TYPE.getCode()).getData();
            List<EleEpdPqd> eleEpdPqdList = (List)this.epdFeignClient.dictMarkByDataType(epdDic.getId()).getData();
            Map<String, String> tMap = new HashMap();
            eleEpdPqdList.forEach((item) -> {
                String phase;
                if (Objects.isNull(PHASE_MAPPING.get(item.getPhase()))) {
                    phase = item.getPhase();
                } else {
                    phase = (String)PHASE_MAPPING.get(item.getPhase());
                }

                if (ObjectUtils.isNotNull(new Object[]{item.getHarmStart()}) && ObjectUtils.isNotNull(new Object[]{item.getHarmEnd()})) {
                    for(int i = item.getHarmStart(); i <= item.getHarmEnd() + 1; ++i) {
                        tMap.put((item.getOtherName() + "_" + i + phase + item.getResourcesId()).toUpperCase(), item.getPrimaryFormula());
                    }
                } else {
                    tMap.put((item.getOtherName() + phase + item.getResourcesId()).toUpperCase(), item.getPrimaryFormula());
                }

            });
            eleEpdPqdList = (List)eleEpdPqdList.stream().filter((it) -> {
                return "T".equals(it.getPhase()) || "M".equals(it.getPhase());
            }).collect(Collectors.toList());
            List<String> noPhaseList = (List)eleEpdPqdList.stream().filter((it) -> {
                return StrUtil.isNotBlank(it.getOtherName());
            }).map((it) -> {
                return it.getOtherName().toUpperCase();
            }).collect(Collectors.toList());
             reportLimitList = (List)(new LinkedHashSet(reportLimitList)).stream().sorted(Comparator.comparing(ReportTemplateDTO::getItemName)).collect(Collectors.toList());
            Map<String, Float> limitMap = this.overLimitDeal(reportLimitList, reportSearchParam);
            Map<String, ReportTemplateDTO> limitTargetMapX = (Map)reportLimitList.stream().collect(Collectors.toMap(ReportTemplateDTO::getItemName, Function.identity()));
            List<ReportTemplateDTO> endList = new CopyOnWriteArrayList();
            if (CollUtil.isNotEmpty(reportTemplateDTOList)) {
                reportTemplateDTOList = (List)(new LinkedHashSet(reportTemplateDTOList)).stream().sorted(Comparator.comparing(ReportTemplateDTO::getItemName)).collect(Collectors.toList());
                Map<String, List<ReportTemplateDTO>> classMap = (Map)reportTemplateDTOList.stream().collect(Collectors.groupingBy(ReportTemplateDTO::getResourceId));
                Map<String, ReportTemplateDTO> assNoPassMap = new HashMap();
                classMap.forEach((classKey, templateValue) -> {
                    Map<String, List<ReportTemplateDTO>> valueTypeMap = (Map)templateValue.stream().collect(Collectors.groupingBy(ReportTemplateDTO::getStatMethod));
                    futures.add(this.executorService.submit(() -> {
                        DynamicDataSourceContextHolder.push("sjzx");

                        try {
                            valueTypeMap.forEach((valueTypeKey, valueTypeVal) -> {
                                Map<String, List<ReportTemplateDTO>> phaseMap = (Map)valueTypeVal.stream().collect(Collectors.groupingBy(ReportTemplateDTO::getPhase));
                                phaseMap.forEach((phaseKey, phaseVal) -> {
                                    StringBuilder sql = new StringBuilder("SELECT ");
                                    if ("MAX".equalsIgnoreCase(valueTypeKey)) {
                                        this.assSqlByMysql(tMap, (String)newMap.get("LEVEL"), (String)newMap.get("PT"), (String)newMap.get("CT"), phaseVal, sql, endList, "MAX", reportSearchParam, limitTargetMapX, limitMap, assNoPassMap, noPhaseList);
                                    } else if ("MIN".equalsIgnoreCase(valueTypeKey)) {
                                        this.assSqlByMysql(tMap, (String)newMap.get("LEVEL"), (String)newMap.get("PT"), (String)newMap.get("CT"), phaseVal, sql, endList, "MIN", reportSearchParam, limitTargetMapX, limitMap, assNoPassMap, noPhaseList);
                                    } else if ("AVG".equalsIgnoreCase(valueTypeKey)) {
                                        this.assSqlByMysql(tMap, (String)newMap.get("LEVEL"), (String)newMap.get("PT"), (String)newMap.get("CT"), phaseVal, sql, endList, "AVG", reportSearchParam, limitTargetMapX, limitMap, assNoPassMap, noPhaseList);
                                    } else if ("CP95".equalsIgnoreCase(valueTypeKey)) {
                                        this.assSqlByMysql(tMap, (String)newMap.get("LEVEL"), (String)newMap.get("PT"), (String)newMap.get("CT"), phaseVal, sql, endList, "CP95", reportSearchParam, limitTargetMapX, limitMap, assNoPassMap, noPhaseList);
                                    }

                                });
                            });
                        } finally {
                            DynamicDataSourceContextHolder.poll();
                        }

                    }));
                });
                Iterator var21 = futures.iterator();

                while(var21.hasNext()) {
                    Future<?> future = (Future)var21.next();

                    try {
                        future.get();
                    } catch (ExecutionException | InterruptedException var31) {
                        Exception e = var31;
                        e.printStackTrace();
                    }
                }

                this.dealTargetResult(assNoPassMap, limitTargetMapX, endList);
            }

            Map<String, Object> dataMap = new HashMap();

            this.resultAssemble(endList, reportSearchParam, newMap, deviceUnitCommDTO, jsonArray,dataMap);
            this.downReport(jsonArray, dataMap);
        }
    }

    @SneakyThrows
    @Test
    public void test() {
        HttpServletResponse response = null;
        ReportSearchParam reportSearchParam = new ReportSearchParam();
        reportSearchParam.setLineId("00B78D00A87A1");
        reportSearchParam.setTempId("58f0be3e6360e73fa47dae1defcee23b");
        reportSearchParam.setStartTime("2026-03-01");
        reportSearchParam.setEndTime("2026-03-19");
        reportSearchParam.setResourceType(1);

        String tempId = getTempId("58f0be3e6360e73fa47dae1defcee23b", "00B78D01840B0");
        //修改模板id
        reportSearchParam.setTempId(tempId);
        //原代码
        TimeInterval timeInterval = new TimeInterval();
        //ExcelRptTemp excelRptTemp = excelRptTempMapper.selectById(reportSearchParam.getTempId());
        ExcelRptTemp excelRptTemp = excelRptTempMapper.selectById(tempId);
        if (Objects.isNull(excelRptTemp)) {
            throw new BusinessException(CsHarmonicResponseEnum.CUSTOM_REPORT_ACTIVE);
        }
        if (Objects.isNull(reportSearchParam.getCustomType())) {
            //通用报表
            Map<String,String> map = csLineFeignClient.getCustomDetailByLineId(reportSearchParam.getLineId()).getData();
            Map<String,String> newMap = convertKeysToUpperCase(map);

            PqsDeviceUnit deviceUnit  = csCommTerminalFeignClient.lineUnitDetail(reportSearchParam.getLineId()).getData();
            DeviceUnitCommDTO deviceUnitCommDTO = BeanUtil.copyProperties(deviceUnit, DeviceUnitCommDTO.class);

            this.getCustomReport(reportSearchParam,newMap,deviceUnitCommDTO,response);
        }
    }

    private void downReport(JSONArray jsonArray, Map<String, Object> dataMap) {
        Workbook workbook = new XSSFWorkbook();

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String sheetName = jsonObject.getStr("name");
            JSONArray data = jsonObject.getJSONArray("data");

            Sheet sheet = workbook.createSheet(sheetName);

            if (data != null) {
                for (int j = 0; j < data.size(); j++) {
                    Row row = sheet.createRow(j);
                    JSONArray rowData = data.getJSONArray(j);

                    if (rowData != null) {
                        for (int k = 0; k < rowData.size(); k++) {
                            Cell cell = row.createCell(k);
                            JSONObject cellObj = rowData.getJSONObject(k);

                            if (cellObj != null && !cellObj.isEmpty()) {
                                Object v = cellObj.get("v");
                                if (v != null) {
                                    Object vData = dataMap.get(v);
                                    if (vData != null) {
                                        if (vData instanceof String) {
                                            cell.setCellValue((String) vData);
                                        } else if (vData instanceof Number) {
                                            cell.setCellValue(((Number) vData).doubleValue());
                                        } else if (vData instanceof Boolean) {
                                            cell.setCellValue((Boolean) vData);
                                        } else {
                                            cell.setCellValue(vData.toString());
                                        }
                                    } else {
                                        if (v instanceof String) {
                                            cell.setCellValue((String) v);
                                        } else if (v instanceof Number) {
                                            cell.setCellValue(((Number) v).doubleValue());
                                        } else if (v instanceof Boolean) {
                                            cell.setCellValue((Boolean) v);
                                        } else {
                                            cell.setCellValue(v.toString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            workbook.write(baos);
            workbook.close();
        } catch (IOException e) {
            throw new BusinessException(OssResponseEnum.DOWNLOAD_FILE_STREAM_ERROR);
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        fileStorageUtil.uploadStream(bais, OssPath.ALGORITHM, "稳态报表.xlsx");

        try {
            bais.close();
            baos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    private void downReport(JSONArray jsonArray, HttpServletResponse response) {
//        InputStream reportStream = IoUtil.toStream(jsonArray.toString(), "UTF-8");
//        fileStorageUtil.uploadStream(reportStream, OssPath.ALGORITHM,"报表测试.xlsx");
//        //jsonArray 这边解析发现 存储的是Luckysheet 相关的数据，想把这部分数据解析为excel表格存储，怎么处理
//    }

    public void resultAssemble(List<ReportTemplateDTO> endList, ReportSearchParam reportSearchParam, Map<String, String> finalTerminalMap, DeviceUnitCommDTO deviceUnitCommDTO, JSONArray jsonArray,Map<String, Object> dataMap) {
        if (CollUtil.isNotEmpty(endList)) {
            Map<String, String> unit = this.unitMap(deviceUnitCommDTO);
            Map<String, List<ReportTemplateDTO>> assMap = (Map)endList.stream().collect(Collectors.groupingBy(ReportTemplateDTO::getItemName));
            jsonArray.forEach((item) -> {
                JSONObject jsonObject = (JSONObject)item;
                JSONArray itemArr = (JSONArray)jsonObject.get("celldata");
                itemArr.forEach((it) -> {
                    if (Objects.nonNull(it) && !"null".equals(it.toString())) {
                        JSONObject data = (JSONObject)it;
                        JSONObject son = (JSONObject)data.get("v");
                        if (son.containsKey("v")) {
                            String v = son.getStr("v");
                            String tem;
                            List rDto;
                            if (v.charAt(0) == '$' && v.contains("#")) {
                                tem = "";
                                rDto = (List)assMap.get(v.replace("$", "").toUpperCase());
                                if (Objects.nonNull(rDto)) {
                                    tem = ((ReportTemplateDTO)rDto.get(0)).getValue();
                                    if (StringUtils.isBlank(tem)) {
                                        tem = "/";
                                    }

                                    son.set("v", tem);
                                    dataMap.put(v, tem);
                                    if (Objects.nonNull(((ReportTemplateDTO)rDto.get(0)).getOverLimitFlag()) && ((ReportTemplateDTO)rDto.get(0)).getOverLimitFlag() == 1) {
                                        son.set("fc", "#990000");
                                    }
                                }
                            } else if (v.charAt(0) == '%' && v.contains("#")) {
                                tem = "";
                                rDto = (List)assMap.get(v.replace("%", "").toUpperCase());
                                if (Objects.nonNull(rDto)) {
                                    tem = ((ReportTemplateDTO)rDto.get(0)).getValue();
                                    if (StringUtils.isBlank(tem)) {
                                        tem = "/";
                                    }

                                    son.set("v", tem);
                                    dataMap.put(v, tem);
                                    if ("不合格".equals(tem)) {
                                        son.set("fc", "#990000");
                                        dataMap.put("fc", "#990000");
                                    }
                                }
                            } else if (v.charAt(0) == '&') {
                                tem = v.replace("&", "").toUpperCase();
                                if (finalTerminalMap.size() > 0) {
                                    if ("STATIS_TIME".equals(tem)) {
                                        String localTime = " 23:59:59";
                                        LocalDate localDate = LocalDateTimeUtil.parseDate(reportSearchParam.getEndTime(), "yyyy-MM-dd");
                                        LocalDate nowDate = LocalDate.now();
                                        if (nowDate.isAfter(localDate)) {
                                            son.set("v", reportSearchParam.getStartTime() + " 00:00:00" + "_" + reportSearchParam.getEndTime() + localTime);
                                            dataMap.put(v, reportSearchParam.getStartTime() + " 00:00:00" + "_" + reportSearchParam.getEndTime() + localTime);
                                        } else {
                                            localTime = " " + LocalTime.now().format(DatePattern.NORM_TIME_FORMATTER);
                                            son.set("v", reportSearchParam.getStartTime() + " 00:00:00" + "_" + nowDate + localTime);
                                            dataMap.put(v, reportSearchParam.getStartTime() + " 00:00:00" + "_" + nowDate + localTime);
                                        }
                                    } else {
                                        son.set("v", finalTerminalMap.getOrDefault(tem, "/"));
                                        dataMap.put(v,  finalTerminalMap.getOrDefault(tem, "/"));
                                    }
                                }
                            }

                            if (v.charAt(0) == '@' && v.contains("#")) {
                                tem = v.replace("@", "");
                                son.set("v", unit.getOrDefault(tem, "/"));
                                dataMap.put(v, unit.getOrDefault(tem, "/"));
                            }
                        }
                    }
                });
            });
        }
    }

    private Map<String, String> unitMap(DeviceUnitCommDTO deviceUnit) {
        List<DictData> dictData = (List)this.dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEVICE_UNIT.getCode()).getData();
        Map<String, String> unit = new HashMap();
        List<String> list = (List)dictData.stream().map(DictData::getCode).collect(Collectors.toList());
        Iterator var5 = list.iterator();

        while(var5.hasNext()) {
            String s = (String)var5.next();
            if (s.equals(DicDataEnum.EFFECTIVE.getCode())) {
                unit.put(s + "#i", deviceUnit.getIeffective());
                unit.put(s + "#v", deviceUnit.getLineVoltage());
            }

            if (s.equals(DicDataEnum.POWER.getCode())) {
                unit.put(s + "#p", deviceUnit.getTotalActiveP());
                unit.put(s + "#q", deviceUnit.getTotalNoP());
                unit.put(s + "#s", deviceUnit.getTotalViewP());
            }

            if (s.equals(DicDataEnum.DISTORTION.getCode())) {
                unit.put(s + "#v", deviceUnit.getVdistortion());
            }

            if (s.equals(DicDataEnum.VOLTAGE.getCode())) {
                unit.put(s + "#v", deviceUnit.getVoltageDev());
            }

            if (s.equals(DicDataEnum.UNIT_FREQUENCY.getCode())) {
                unit.put(s + "#freq", deviceUnit.getUnitFrequency());
                unit.put(s + "#freqDev", deviceUnit.getUnitFrequencyDev());
            }

            if (s.equals(DicDataEnum.UNBALANCE.getCode())) {
                unit.put(s + "#v", "%");
                unit.put(s + "#vPos", deviceUnit.getPositiveV());
                unit.put(s + "#vNeg", deviceUnit.getNoPositiveV());
                unit.put(s + "#vZero", deviceUnit.getNoPositiveV());
                unit.put(s + "#i", "%");
                unit.put(s + "#iPos", "A");
                unit.put(s + "#iNeg", "A");
                unit.put(s + "#iZero", "A");
            }

            if (s.equals(DicDataEnum.FUND.getCode())) {
                unit.put(s + "#i", deviceUnit.getIfund());
                unit.put(s + "#v", deviceUnit.getVfundEffective());
            }
        }

        return unit;
    }

    private void dealTargetResult(Map<String, ReportTemplateDTO> assNoPassMap, Map<String, ReportTemplateDTO> limitTargetMapX, List<ReportTemplateDTO> endList) {
        assNoPassMap.forEach((key, val) -> {
            limitTargetMapX.remove(key);
            if ("Freq_Dev".toUpperCase().equals(val.getTemplateName())) {
                val.setValue("±" + val.getValue());
            }

            String expend = "";
            if (Objects.nonNull(val.getLowValue())) {
                expend = val.getLowValue() + ",";
            }

            if (val.getOverLimitFlag() == 1) {
                val.setValue("不合格 (" + expend + val.getValue() + ")");
            } else {
                val.setValue("合格 (" + expend + val.getValue() + ")");
            }

            endList.add(val);
        });
        limitTargetMapX.forEach((key, val) -> {
            if (Objects.isNull(val.getOverLimitFlag())) {
                val.setValue("/");
            } else {
                val.setValue("合格");
            }

            endList.add(val);
        });
    }


    private void assSqlByMysql(Map<String, String> tMap, String dataLevel, String pt, String ct, List<ReportTemplateDTO> data, StringBuilder sql, List<ReportTemplateDTO> endList, String method, ReportSearchParam reportSearchParam, Map<String, ReportTemplateDTO> limitMap, Map<String, Float> overLimitMap, Map<String, ReportTemplateDTO> assNoPassMap, List<String> noPhaseList) {
        int i;
        if ("CP95".equals(method)) {
            for(i = 0; i < data.size(); ++i) {
                if (i == data.size() - 1) {
                    sql.append("MAX").append("(").append(((ReportTemplateDTO)data.get(i)).getTemplateName()).append(")").append(Objects.equals(dataLevel, "Secondary") ? " " + this.appendData(tMap, ((ReportTemplateDTO)data.get(i)).getTemplateName() + ((ReportTemplateDTO)data.get(i)).getPhase() + ((ReportTemplateDTO)data.get(0)).getResourceId(), this.getData(pt), this.getData(ct)) : "").append(" as ").append("\"" + ((ReportTemplateDTO)data.get(i)).getItemName() + "\"");
                } else {
                    sql.append("MAX").append("(").append(((ReportTemplateDTO)data.get(i)).getTemplateName()).append(")").append(Objects.equals(dataLevel, "Secondary") ? " " + this.appendData(tMap, ((ReportTemplateDTO)data.get(i)).getTemplateName() + ((ReportTemplateDTO)data.get(i)).getPhase() + ((ReportTemplateDTO)data.get(0)).getResourceId(), this.getData(pt), this.getData(ct)) : "").append(" as ").append("\"" + ((ReportTemplateDTO)data.get(i)).getItemName() + "\"").append(",");
                }
            }
        } else {
            for(i = 0; i < data.size(); ++i) {
                if (i == data.size() - 1) {
                    sql.append(method).append("(").append(((ReportTemplateDTO)data.get(i)).getTemplateName()).append(")").append(Objects.equals(dataLevel, "Secondary") ? " " + this.appendData(tMap, ((ReportTemplateDTO)data.get(i)).getTemplateName() + ((ReportTemplateDTO)data.get(i)).getPhase() + ((ReportTemplateDTO)data.get(0)).getResourceId(), this.getData(pt), this.getData(ct)) : "").append(" as ").append("\"" + ((ReportTemplateDTO)data.get(i)).getItemName() + "\"");
                } else {
                    sql.append(method).append("(").append(((ReportTemplateDTO)data.get(i)).getTemplateName()).append(")").append(Objects.equals(dataLevel, "Secondary") ? " " + this.appendData(tMap, ((ReportTemplateDTO)data.get(i)).getTemplateName() + ((ReportTemplateDTO)data.get(i)).getPhase() + ((ReportTemplateDTO)data.get(0)).getResourceId(), this.getData(pt), this.getData(ct)) : "").append(" as ").append("\"" + ((ReportTemplateDTO)data.get(i)).getItemName() + "\"").append(",");
                }
            }
        }

        sql.append(' ').append("FROM ").append(((ReportTemplateDTO)data.get(0)).getResourceId());
        sql.append(" WHERE ").append("line_id").append("=").append("'").append(reportSearchParam.getLineId()).append("'");
        if (!"M".equals(((ReportTemplateDTO)data.get(0)).getPhase())) {
            sql.append(" AND ").append("phasic_type").append("=").append("'").append(((ReportTemplateDTO)data.get(0)).getPhase()).append("'");
        }

        sql.append(" AND ").append("value_type").append("=").append("'").append(((ReportTemplateDTO)data.get(0)).getStatMethod()).append("'");
        if (noPhaseList.contains(((ReportTemplateDTO)data.get(0)).getTemplateName())) {
            if (((ReportTemplateDTO)data.get(0)).getTemplateName().equalsIgnoreCase("v_unbalance")) {
                System.out.println(44);
            }

            sql.append(" AND ").append("phasic_type").append("=").append("'").append("T").append("'");
        }

        sql.append(" AND ").append("time ").append(">=").append("'").append(reportSearchParam.getStartTime()).append(" 00:00:00").append("'").append(" AND ").append("time ").append("<").append("'").append(reportSearchParam.getEndTime()).append(" 23:59:59").append("'");
        System.out.println(sql);
        List<Map<String, Object>> mapList = SqlRunner.DEFAULT.selectList(sql.toString(), new Object[0]);
        if (!CollUtil.isEmpty(mapList) && !Objects.isNull(mapList.get(0))) {
            Map<String, Object> map = this.convertKeysToUpperCase((Map)mapList.get(0));
            Iterator var16 = data.iterator();

            label124:
            while(true) {
                while(true) {
                    while(true) {
                        double v;
                        String key;
                        do {
                            ReportTemplateDTO item;
                            do {
                                while(true) {
                                    if (!var16.hasNext()) {
                                        break label124;
                                    }

                                    item = (ReportTemplateDTO)var16.next();
                                    if (map.containsKey(item.getItemName())) {
                                        v = Double.parseDouble(map.get(item.getItemName()).toString());
                                        item.setValue(String.format("%.3f", v));
                                        if (overLimitMap.containsKey(item.getLimitName())) {
                                            Float tagVal = (Float)overLimitMap.get(item.getLimitName());
                                            if (item.getLimitName().equalsIgnoreCase("UVOLTAGE_DEV")) {
                                                Float tagVal_U = (Float)overLimitMap.get("UVOLTAGE_DEV");
                                                if (!(v > (double)tagVal) && !(v < (double)tagVal_U)) {
                                                    item.setOverLimitFlag(0);
                                                } else {
                                                    item.setOverLimitFlag(1);
                                                }
                                            } else if (v > (double)tagVal) {
                                                item.setOverLimitFlag(1);
                                            } else {
                                                item.setOverLimitFlag(0);
                                            }
                                        }
                                        break;
                                    }

                                    item.setValue("/");
                                }
                            } while(limitMap.isEmpty());

                            key = item.getLimitName() + "#" + item.getStatMethod() + "#PQ_OVERLIMIT";
                        } while(!limitMap.containsKey(key));

                        ReportTemplateDTO tem = (ReportTemplateDTO)limitMap.get(key);
                        double limitVal = Double.parseDouble(tem.getValue());
                        if ("VOLTAGE_DEV".equalsIgnoreCase(tem.getLimitName())) {
                            double limitLowVal = Double.parseDouble(tem.getLowValue());
                            if (!(v > limitVal) && !(v < limitLowVal)) {
                                if (!assNoPassMap.containsKey(key)) {
                                    tem.setOverLimitFlag(0);
                                    assNoPassMap.put(key, tem);
                                }
                            } else {
                                tem.setOverLimitFlag(1);
                                assNoPassMap.put(key, tem);
                            }
                        } else if (v > limitVal) {
                            tem.setOverLimitFlag(1);
                            assNoPassMap.put(key, tem);
                        } else if (!assNoPassMap.containsKey(key)) {
                            tem.setOverLimitFlag(0);
                            assNoPassMap.put(key, tem);
                        }
                    }
                }
            }
        } else {
            data = (List)data.stream().peek((itemx) -> {
                itemx.setValue("/");
            }).collect(Collectors.toList());
        }

        endList.addAll(data);
    }

    public Double getData(String data) {
        double ratio = 1.0;
        String[] parts = data.split(":");
        if (parts.length == 2) {
            try {
                int num1 = Integer.parseInt(parts[0]);
                int num2 = Integer.parseInt(parts[1]);
                ratio = (double)num1 / (double)num2;
            } catch (NumberFormatException var7) {
                System.out.println("字符串格式错误");
            }
        }

        return ratio;
    }

    public String appendData(Map<String, String> tMap, String name, double pt, double ct) {
        String format = (String)tMap.get(name);
        String result;
        if (Objects.equals(format, "*PT")) {
            result = "*" + pt + "/1000";
        } else if (Objects.equals(format, "*CT")) {
            result = "*" + ct;
        } else if (Objects.equals(format, "*PT*CT")) {
            result = "*" + pt + "*" + ct + "/1000";
        } else {
            result = "";
        }

        return result;
    }


    private Map<String, Float> overLimitDeal(List<ReportTemplateDTO> reportLimitList, ReportSearchParam reportSearchParam) {
        Map<String, Float> limitMap = new HashMap();
        if (CollUtil.isNotEmpty(reportLimitList)) {
            StringBuilder sql = new StringBuilder("SELECT ");

            for(int i = 0; i < reportLimitList.size(); ++i) {
                if (i == reportLimitList.size() - 1) {
                    sql.append("UVOLTAGE_DEV").append(",");
                    sql.append(((ReportTemplateDTO)reportLimitList.get(i)).getTemplateName()).append(' ');
                } else {
                    sql.append(((ReportTemplateDTO)reportLimitList.get(i)).getTemplateName()).append(",");
                }
            }

            sql.append("FROM ").append(((ReportTemplateDTO)reportLimitList.get(0)).getResourceId()).append(" WHERE ").append("id ='").append(reportSearchParam.getLineId()).append("'");
            limitMap = this.excelRptTempMapper.dynamicSqlMap(sql.toString());
            if (Objects.isNull(limitMap)) {
                throw new BusinessException("当前报表测点限值缺失!");
            }

            Iterator var8 = reportLimitList.iterator();

            while(var8.hasNext()) {
                ReportTemplateDTO item = (ReportTemplateDTO)var8.next();
                if (((Map)limitMap).containsKey(item.getTemplateName())) {
                    if (item.getTemplateName().equalsIgnoreCase("VOLTAGE_DEV")) {
                        item.setLowValue(((Float)((Map)limitMap).get("UVOLTAGE_DEV")).toString());
                    }

                    item.setValue(((Float)((Map)limitMap).get(item.getTemplateName())).toString());
                }
            }
        }

        limitMap = this.convertKeysToUpperCase((Map)limitMap);
        return limitMap;
    }

    private void parseTemplate(JSONArray jsonArray, List<ReportTemplateDTO> reportTemplateDTOList, List<ReportTemplateDTO> reportLimitList, List<ReportTemplateDTO> terminalList) {
        try {
            jsonArray.forEach((item) -> {
                JSONObject jsonObject = (JSONObject)item;
                JSONArray itemArr = (JSONArray)jsonObject.get("celldata");
                itemArr.forEach((it) -> {
                    if (Objects.nonNull(it) && !"null".equals(it.toString())) {
                        JSONObject data = (JSONObject)it;
                        JSONObject son = (JSONObject)data.get("v");
                        if (son.containsKey("v")) {
                            String v = son.getStr("v");
                            ReportTemplateDTO reportTemplateDTO;
                            String[] vItem;
                            if (v.charAt(0) == '$' && v.contains("#")) {
                                v = v.replace("$", "");
                                reportTemplateDTO = new ReportTemplateDTO();
                                reportTemplateDTO.setItemName(v.toUpperCase());
                                vItem = v.split("#");
                                if (vItem.length == 5) {
                                    reportTemplateDTO.setTemplateName(vItem[0].toUpperCase());
                                    reportTemplateDTO.setPhase(vItem[1].substring(0, 1).toUpperCase());
                                    reportTemplateDTO.setStatMethod(vItem[2].toUpperCase());
                                    reportTemplateDTO.setResourceId(vItem[3].toUpperCase());
                                    reportTemplateDTO.setLimitName(vItem[4].toUpperCase());
                                } else if (vItem.length == 4) {
                                    reportTemplateDTO.setTemplateName(vItem[0].toUpperCase());
                                    reportTemplateDTO.setPhase("T");
                                    reportTemplateDTO.setStatMethod(vItem[1].toUpperCase());
                                    reportTemplateDTO.setResourceId(vItem[2].toUpperCase());
                                    reportTemplateDTO.setLimitName(vItem[3].toUpperCase());
                                }

                                reportTemplateDTOList.add(reportTemplateDTO);
                            } else if (v.charAt(0) == '%' && v.contains("#")) {
                                reportTemplateDTO = new ReportTemplateDTO();
                                v = v.replace("%", "");
                                reportTemplateDTO.setItemName(v.toUpperCase());
                                vItem = v.split("#");
                                if (vItem.length == 3) {
                                    reportTemplateDTO.setTemplateName(vItem[0].toUpperCase());
                                    reportTemplateDTO.setStatMethod(vItem[1].toUpperCase());
                                    reportTemplateDTO.setResourceId(vItem[2].toUpperCase());
                                }

                                reportLimitList.add(reportTemplateDTO);
                            } else if (v.charAt(0) == '&') {
                                reportTemplateDTO = new ReportTemplateDTO();
                                v = v.replace("&", "");
                                reportTemplateDTO.setItemName(v.toUpperCase());
                                reportTemplateDTO.setTemplateName(v.toUpperCase());
                                terminalList.add(reportTemplateDTO);
                            }
                        }
                    }

                });
            });
        } catch (Exception var6) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_JSON);
        }
    }


    /**
     * map key转大写
     */
    public <V> Map<String, V> convertKeysToUpperCase(Map<String, V> originalMap) {
        Map<String, V> newMap = new HashMap<>();
        if (CollUtil.isNotEmpty(originalMap)) {
            for (Map.Entry<String, V> entry : originalMap.entrySet()) {
                newMap.put(entry.getKey().toUpperCase(), entry.getValue());
            }
        }

        return newMap;
    }


    //获取模板id
    public String getTempId(String oldTempId, String lineId) {
        //根据模板类型的id获取模板
        List<ReportTemplateVO> result = sysExcelService.queryList(oldTempId);
        if (CollUtil.isEmpty(result)) {
            throw new BusinessException("未配置相关模板");
        }
        //根据监测点获取接线方式
        CsLinePO po = csLineFeignClient.getById(lineId).getData();
        //根据接线方式获取模板id
        int conType = po.getConType();

        DictData dicData;
        //角型
        if (conType == 1) {
            dicData = dicDataFeignClient.getDicDataByCode(DicDataEnum.STAR_TRIANGLE.getCode()).getData();
        }
        //v型
        else if (conType == 2){
            dicData = dicDataFeignClient.getDicDataByCode(DicDataEnum.OPEN_DELTA.getCode()).getData();
        }
        //星型 或 其他
        else {
            dicData = dicDataFeignClient.getDicDataByCode(DicDataEnum.STAR.getCode()).getData();
        }
        String tempId;
        Optional<ReportTemplateVO> vo = result.stream().filter(item -> Objects.equals(dicData.getId(),item.getWiringMethod())).findFirst();
        if (vo.isPresent()) {
            tempId = vo.get().getId();
        } else {
            throw new BusinessException("未找到此接线方式的模板");
        }
        return tempId;
    }

    public static void main(String[] args) {
        String fullPath =  "comtrade/00:B7:8D:00:A8:7A/PQMonitor_PQM1_00100_20260204_162453_071_WAV.hdr";
        int lastSlashIndex = fullPath.lastIndexOf('/');
        String hdrPath = fullPath.substring(0, lastSlashIndex + 1);
        String hdrName = fullPath.substring(lastSlashIndex + 1);
        System.out.println(hdrPath);
        System.out.println(hdrName);
    }


}
