package com.njcn.harmonic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.FileUtil;
import com.njcn.harmonic.enums.HarmonicResponseEnum;
import com.njcn.harmonic.mapper.DeptTempMapper;
import com.njcn.harmonic.mapper.EleEpdMapper;
import com.njcn.harmonic.mapper.ExcelRptMapper;
import com.njcn.harmonic.mapper.ExcelRptTempMapper;
import com.njcn.harmonic.pojo.dto.ReportTemplateDTO;
import com.njcn.harmonic.pojo.param.ReportSearchParam;
import com.njcn.harmonic.pojo.param.ReportTemplateParam;
import com.njcn.influx.constant.InfluxDbSqlConstant;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.influx.service.CommonService;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.harmonic.pojo.po.ExcelRpt;
import com.njcn.harmonic.pojo.po.ExcelRptTemp;
import com.njcn.harmonic.pojo.po.SysDeptTemp;
import com.njcn.harmonic.pojo.vo.ReportTemplateVO;
import com.njcn.harmonic.pojo.vo.ReportTreeVO;
import com.njcn.harmonic.pojo.vo.SysDeptTempVO;
import com.njcn.harmonic.service.CustomReportService;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.web.utils.WebUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 自定义报表
 *
 * @author qijian
 * @date 2022/10/15
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CustomReportServiceImpl implements CustomReportService {

    private final ExcelRptTempMapper excelRptTempMapper;

    private final ExcelRptMapper excelRptMapper;

    private final DeptFeignClient deptFeignClient;

    private final EleEpdMapper eleEpdMapper;

    private final DeptTempMapper deptTempMapper;

    private final FileStorageUtil fileStorageUtil;

    private final CommonService commonService;


    @Override
    public boolean addCustomReportTemplate(ReportTemplateParam reportTemplateParam) {
        checkName(reportTemplateParam, false);
        MultipartFile fileContent = reportTemplateParam.getFileContent();
        //检验模板json数据规范
        try {
            String content = FileUtil.multipartFileToString(fileContent);
            new JSONArray(content);
        } catch (Exception e) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_JSON);
        }
        reportTemplateParam.setContent(fileStorageUtil.uploadMultipart(fileContent, OssPath.HARMONIC_EXCEL_TEMPLATE));
        //新增模板表
        ExcelRptTemp excelRptTemp = new ExcelRptTemp();
        BeanUtils.copyProperties(reportTemplateParam, excelRptTemp);
        excelRptTemp.setState(DataStateEnum.ENABLE.getCode());
        excelRptTempMapper.insert(excelRptTemp);

        //获取主键，并存入部门表
        String tempId = excelRptTemp.getId();
        for (String deptId : reportTemplateParam.getDeptId()) {
            SysDeptTemp sysDeptTemp = new SysDeptTemp();
            sysDeptTemp.setTempId(tempId);
            sysDeptTemp.setDeptId(deptId);
            //未激活状态
            sysDeptTemp.setActivation(DataStateEnum.DELETED.getCode());
            deptTempMapper.insert(sysDeptTemp);
        }

        return true;
    }

    @Override
    public boolean updateCustomReportTemplate(ReportTemplateParam.UpdateReportTemplateParam reportTemplateParam) {
        checkName(reportTemplateParam, true);
        MultipartFile fileContent = reportTemplateParam.getFileContent();
        //检验模板json数据规范
        try {
            String content = FileUtil.multipartFileToString(fileContent);
            new JSONArray(content);
        } catch (Exception e) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_JSON);
        }

        //删除之前的文件
        ExcelRptTemp excelRptTempOld = excelRptTempMapper.selectById(reportTemplateParam.getId());
        fileStorageUtil.deleteFile(excelRptTempOld.getContent());
        reportTemplateParam.setContent(fileStorageUtil.uploadMultipart(fileContent, OssPath.HARMONIC_EXCEL_TEMPLATE));
        //修改模板数据
        ExcelRptTemp excelRptTemp = new ExcelRptTemp();
        BeanUtils.copyProperties(reportTemplateParam, excelRptTemp);
        excelRptTemp.setUpdateTime(LocalDateTime.now());
        excelRptTempMapper.updateById(excelRptTemp);

        return true;
    }

    @Override
    public boolean updateBindTemplate(List<ReportSearchParam> reportSearchParams) {
        //1、根据模板主键删除绑定的部门数据
        LambdaQueryWrapper<SysDeptTemp> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(SysDeptTemp::getTempId, reportSearchParams.get(0).getTempId());
        deptTempMapper.delete(lambdaQuery);
        //2、新增部门
        for (ReportSearchParam reportSearchParam : reportSearchParams) {
            SysDeptTemp sysDeptTemp = new SysDeptTemp();
            sysDeptTemp.setTempId(reportSearchParam.getTempId());
            sysDeptTemp.setDeptId(reportSearchParam.getDeptId());
            sysDeptTemp.setActivation(reportSearchParam.getActivation());
            deptTempMapper.insert(sysDeptTemp);
        }
        return true;
    }

    @Override
    public List<SysDeptTempVO> getDataByTempId(String id) {
        return deptTempMapper.getDeptTempByTempId(id);
    }

    @Override
    public List<ReportTemplateVO> getTemplateByDept(String id) {
        //获取子孙部门，去重
        List<DeptDTO> depts = deptFeignClient.getDeptDescendantIndexes(id, WebUtil.filterDeptType()).getData().stream().distinct().collect(Collectors.toList());
        return excelRptTempMapper.getReportTemplateByDept(depts);
    }

    @Override
    public ExcelRptTemp getCustomReportTemplateById(String id) {
        ExcelRptTemp excelRptTemp = excelRptTempMapper.selectById(id);
        return excelRptTemp;
    }

    @Override
    public void viewCustomReportTemplateById(String id, HttpServletResponse response) {
        ExcelRptTemp excelRptTemp = excelRptTempMapper.selectById(id);
        try {
            fileStorageUtil.downloadStream(response, excelRptTemp.getContent());
        } catch (Exception exception) {
            throw new BusinessException(HarmonicResponseEnum.REPORT_TEMPLATE_DOWNLOAD_ERROR);
        }

    }

    @Override
    public List<ReportTemplateVO> getTemplateList(ReportSearchParam reportSearchParam) {
        return excelRptTempMapper.getReportTemplateList(reportSearchParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delTemplate(ReportSearchParam reportSearchParam) {
        //根据模板ID和部门ID删除绑定的数据
        LambdaQueryWrapper<SysDeptTemp> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(SysDeptTemp::getTempId, reportSearchParam.getTempId());
        deptTempMapper.delete(lambdaQuery);
        excelRptTempMapper.deleteById(reportSearchParam.getTempId());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(ReportSearchParam reportSearchParam) {
        //先全体把激活的改为未激活，再改单个的激活值
        deptTempMapper.updateAllActivation(reportSearchParam.getDeptId());

        SysDeptTemp sysDeptTemp = new SysDeptTemp();
        BeanUtils.copyProperties(reportSearchParam, sysDeptTemp);
        deptTempMapper.updateActivation(sysDeptTemp);
        return true;
    }


    @Override
    public void getCustomReport(ReportSearchParam reportSearchParam, HttpServletResponse response) {
        ExcelRptTemp excelRptTemp = excelRptTempMapper.selectById(reportSearchParam.getTempId());
        if (Objects.isNull(excelRptTemp)) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_ACTIVE);
        }
        //先查询库里是否存在已解析的报表数据，存在直接返回/不存在解析数据
        LambdaQueryWrapper<ExcelRpt> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery
                .eq(ExcelRpt::getLineId, reportSearchParam.getLineId())
                .eq(ExcelRpt::getTempId, reportSearchParam.getTempId())
                //年季月周日
                .eq(ExcelRpt::getType, reportSearchParam.getType())
                //报表日期
                .eq(ExcelRpt::getDataDate, reportSearchParam.getStartTime());
        try {
           List<ExcelRpt> excelRpts  = excelRptMapper.selectList(lambdaQuery);
            if (CollUtil.isNotEmpty(excelRpts)) {
                fileStorageUtil.downloadStream(response, excelRpts.get(0).getContent());
            } else {
                fileStorageUtil.downloadStream(response, analyzeReport(reportSearchParam, excelRptTemp));
            }
        } catch (Exception exception) {
            throw new BusinessException(HarmonicResponseEnum.REPORT_DOWNLOAD_ERROR);
        }

    }


    @Override
    public List<ReportTreeVO> reportChooseTree() {
        LambdaQueryWrapper<EleEpdPqd> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.isNotNull(EleEpdPqd::getOtherName);
        lambdaQueryWrapper.orderByAsc(EleEpdPqd::getSort);
        List<EleEpdPqd> list = eleEpdMapper.selectList(lambdaQueryWrapper);
        Map<String, List<EleEpdPqd>> map = list.stream().collect(Collectors.groupingBy(EleEpdPqd::getName));

        List<ReportTreeVO> tree = new ArrayList<>();
        map.forEach((key, value) -> {

            ReportTreeVO reportTreeVO = new ReportTreeVO();
            reportTreeVO.setName(value.get(0).getOtherName());
            reportTreeVO.setShowName(value.get(0).getShowName());

            //存在1-50次 2-50次情况
            if (Objects.nonNull(value.get(0).getHarmStart()) && Objects.nonNull(value.get(0).getHarmEnd())) {
                List<ReportTreeVO> reHarm = new ArrayList<>();
                for (int i = value.get(0).getHarmStart(); i <= value.get(0).getHarmEnd(); i++) {
                    ReportTreeVO reportTreeCount = new ReportTreeVO();
                    reportTreeCount.setName(value.get(0).getOtherName() + "_" + i);
                    reportTreeCount.setShowName(i + "次" + value.get(0).getShowName());
                    reportTreeVO.setFlag(1);
                    assPhase(value, reportTreeCount, reportTreeCount.getName());
                    reHarm.add(reportTreeCount);
                }
                reportTreeVO.setChildren(reHarm);
            } else {
                assPhase(value, reportTreeVO, value.get(0).getOtherName());
            }
            tree.add(reportTreeVO);
        });
        return tree;
    }

    /*组装相别*/
    private void assPhase(List<EleEpdPqd> value, ReportTreeVO reportTreeItem, String key) {
        List<ReportTreeVO> phaseTree = new ArrayList<>();
        value.forEach(item -> {
            if (Objects.nonNull(item.getPhase()) && !"M".equals(item.getPhase())) {
                List<ReportTreeVO> statTree = new ArrayList<>();
                ReportTreeVO reportTreePhase = new ReportTreeVO();
                reportTreePhase.setName(item.getPhase());
                reportTreePhase.setShowName(item.getPhase());

                assStatMethod(item, statTree, key, item.getPhase());
                reportTreePhase.setChildren(statTree);
                phaseTree.add(reportTreePhase);
                reportTreeItem.setChildren(phaseTree);

            } else {
                List<ReportTreeVO> statTree = new ArrayList<>();
                assStatMethod(item, statTree, key, "");
                reportTreeItem.setChildren(statTree);
            }
        });

    }


    private void assStatMethod(EleEpdPqd item, List<ReportTreeVO> statTree, String oneKey, String twoKey) {
        //存在向别为M但是Stat_Method不为空
        if (StrUtil.isNotBlank(item.getStatMethod())) {
            String[] arr = item.getStatMethod().split(",");
            List<String> stat = Stream.of(arr).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(stat)) {
                stat.forEach(statItem -> {
                    ReportTreeVO reportTreeStat = new ReportTreeVO();
                    if (StrUtil.isNotBlank(twoKey)) {
                        reportTreeStat.setName("$" + oneKey + "#" + twoKey + "#" + statItem + "#" + item.getClassId().trim() + "$");
                    } else {
                        reportTreeStat.setName("$" + oneKey + "#" + statItem + "#" + item.getClassId().trim() + "$");
                    }

                    reportTreeStat.setShowName(statItem);
                    statTree.add(reportTreeStat);
                });
            }
        }
    }


    /**
     * 检查名称是否已存在
     *
     * @param reportTemplateParam,isUpdate 参数
     * @return 结果
     */
    private void checkName(ReportTemplateParam reportTemplateParam, boolean isUpdate) {
        LambdaQueryWrapper<ExcelRptTemp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //条件组合：where state = 1 and name = ?
        lambdaQueryWrapper.eq(ExcelRptTemp::getState, DataStateEnum.ENABLE.getCode()).eq(ExcelRptTemp::getName, reportTemplateParam.getName());

        //and id <> ?
        if (isUpdate) {
            if (reportTemplateParam instanceof ReportTemplateParam.UpdateReportTemplateParam) {
                lambdaQueryWrapper.ne(ExcelRptTemp::getId, ((ReportTemplateParam.UpdateReportTemplateParam) reportTemplateParam).getId());
            }
        }

        //若存在条件数据抛出异常
        int count = excelRptTempMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_REPEAT);
        }

    }


    /**
     * 解析报表模板赋值数据
     */
    private String analyzeReport(ReportSearchParam reportSearchParam, ExcelRptTemp excelRptTemp) {
        //根据content，获取v值并进行处理
        List<ReportTemplateDTO> reportTemplateDTOList = new ArrayList<>();
        JSONArray jsonArray;
        try(InputStream fileStream = fileStorageUtil.getFileStream(excelRptTemp.getContent())) {
            //通过文件服务器获取
            jsonArray = new JSONArray(new JSONTokener(fileStream, new JSONConfig()));
            jsonArray.forEach(item -> {
                JSONObject jsonObject = (JSONObject) item;
                JSONArray itemArr = (JSONArray) jsonObject.get("celldata");
                itemArr.forEach((it) -> {
                    if (Objects.nonNull(it) && !"null".equals(it.toString())) {
                        //获取到1列
                        JSONObject data = (JSONObject) it;
                        JSONObject son = (JSONObject) data.get("v");
                        if (son.containsKey("v")) {
                            String v = son.getStr("v");
                            //数据格式：$HA[_25]#B#max#classId$ 或 $HA[_25]#max#classId$
                            if (v.charAt(0) == '$' && v.contains("#")) {
                                //剔除前后$
                                v = v.replace("$", "");
                                //封装ReportTemplateDTO
                                ReportTemplateDTO reportTemplateDTO = new ReportTemplateDTO();
                                reportTemplateDTO.setItemName(v);
                                //根据#分割数据
                                String[] vItem = v.split("#");
                                if (vItem.length == 4) {
                                    //$HA[_25]#B#max#classId$
                                    reportTemplateDTO.setTemplateName(vItem[0]);
                                    reportTemplateDTO.setPhase(vItem[1].substring(0, 1));
                                    reportTemplateDTO.setStatMethod(vItem[2].toUpperCase());
                                    reportTemplateDTO.setClassId(vItem[3]);
                                } else if (vItem.length == 3) {
                                    //$HA[_25]#max#classId$
                                    reportTemplateDTO.setTemplateName(vItem[0]);
                                    reportTemplateDTO.setPhase("M");
                                    reportTemplateDTO.setStatMethod(vItem[1].toUpperCase());
                                    reportTemplateDTO.setClassId(vItem[2]);
                                }
                                reportTemplateDTOList.add(reportTemplateDTO);
                            }
                        }
                    }
                });
            });
        } catch (Exception e) {
            throw new BusinessException(HarmonicResponseEnum.CUSTOM_REPORT_JSON);
        }

        List<ReportTemplateDTO> endList = new ArrayList<>();
        if (CollUtil.isNotEmpty(reportTemplateDTOList)) {
            //开始组织sql
            reportTemplateDTOList.stream().forEach(data -> {
                StringBuilder sql = new StringBuilder(InfluxDbSqlConstant.SELECT);
                if (InfluxDbSqlConstant.MAX.equalsIgnoreCase(data.getStatMethod())) {
                    assSql(data, sql, endList, InfluxDbSqlConstant.MAX, reportSearchParam);
                } else if (InfluxDbSqlConstant.MIN.equalsIgnoreCase(data.getStatMethod())) {
                    assSql(data, sql, endList, InfluxDbSqlConstant.MIN, reportSearchParam);
                } else if (InfluxDbSqlConstant.AVG.equalsIgnoreCase(data.getStatMethod())) {
                    assSql(data, sql, endList, InfluxDbSqlConstant.AVG, reportSearchParam);
                } else if (InfluxDbSqlConstant.CP95.equalsIgnoreCase(data.getStatMethod())) {
                    assSql(data, sql, endList, InfluxDbSqlConstant.CP95, reportSearchParam);
                }
            });
        }

        if (CollUtil.isNotEmpty(endList)) {
            //进行反向赋值到模板
            //1、根据itemName分组
            Map<String, List<ReportTemplateDTO>> assMap = endList.stream().collect(Collectors.groupingBy(ReportTemplateDTO::getItemName));
            //2、把itemName的value赋给v和m
            jsonArray.forEach(item -> {
                JSONObject jsonObject = (JSONObject) item;
                JSONArray itemArr = (JSONArray) jsonObject.get("celldata");
                itemArr.forEach((it) -> {
                    if (Objects.nonNull(it) && !"null".equals(it.toString())) {
                        //获取到1列
                        JSONObject data = (JSONObject) it;
                        JSONObject son = (JSONObject) data.get("v");
                        if (son.containsKey("v")) {
                            String v = son.getStr("v");
                            //数据格式：$HA[_25]#B#max#classId$ 或 $HA[_25]#max#classId$
                            if (v.charAt(0) == '$' && v.contains("#")) {
                                String str = assMap.get(v.replace("$", "")).get(0).getValue();
                                //没有值，赋"/"
                                if (StringUtils.isBlank(str)) {
                                    str = "/";
                                }
                                son.set("v", str);
                            }
                        }
                    }
                });
            });
        }

        InputStream reportStream = IoUtil.toStream(jsonArray.toString(), CharsetUtil.UTF_8);
        String newContent = fileStorageUtil.uploadStream(reportStream, OssPath.HARMONIC_EXCEL_REPORT, FileUtil.generateFileName("json"));

        //入库前判断是否有了，有了就更新
        ExcelRpt excelRpt = new ExcelRpt();
        excelRpt.setName(excelRptTemp.getName());
        excelRpt.setLineId(reportSearchParam.getLineId());
        excelRpt.setDataDate(DateUtil.parse(reportSearchParam.getStartTime()));
        excelRpt.setTempId(excelRptTemp.getId());
        excelRpt.setContent(newContent);
        excelRpt.setType(reportSearchParam.getType());
        excelRpt.setState(DataStateEnum.ENABLE.getCode());

        excelRptMapper.insert(excelRpt);

        return newContent;
    }


    /**
     * 组装influxDB查询sql，查询value并封装endlist
     *
     * @return 结果
     */
    private void assSql(ReportTemplateDTO data, StringBuilder sql, List<ReportTemplateDTO> endList, String method, ReportSearchParam reportSearchParam) {
        //sql拼接示例：select MAX(IHA2) as IHA2 from power_quality_data where Phase = 'A' and LineId='1324564568' and Stat_Method='max' tz('Asia/Shanghai')

        //cp95函数特殊处理 PERCENTILE(field_key, N)
        if (InfluxDbSqlConstant.CP95.equals(method)) {
            sql.append(method)
                    .append(InfluxDbSqlConstant.LBK)
                    .append(data.getTemplateName())
                    .append(InfluxDbSqlConstant.NUM_95)
                    .append(InfluxDbSqlConstant.RBK)
                    .append(InfluxDbSqlConstant.AS_VALUE);
        } else {
            sql.append(method)
                    .append(InfluxDbSqlConstant.LBK)
                    .append(data.getTemplateName())
                    .append(InfluxDbSqlConstant.RBK)
                    .append(InfluxDbSqlConstant.AS_VALUE);
        }
        sql.append(InfluxDbSqlConstant.FROM)
                .append(data.getClassId())
                .append(InfluxDbSqlConstant.WHERE)
                .append(InfluxDBTableConstant.LINE_ID)
                .append(InfluxDbSqlConstant.EQ)
                .append(InfluxDbSqlConstant.QM)
                .append(reportSearchParam.getLineId())
                .append(InfluxDbSqlConstant.QM);
        //相别特殊处理
        if (!InfluxDBTableConstant.NO_PHASE.equals(data.getPhase())) {
            sql.append(InfluxDbSqlConstant.AND)
                    .append(InfluxDBTableConstant.PHASIC_TYPE)
                    .append(InfluxDbSqlConstant.EQ)
                    .append(InfluxDbSqlConstant.QM)
                    .append(data.getPhase())
                    .append(InfluxDbSqlConstant.QM);
        }


        //data_flicker、data_fluc、data_plt 无 value_type
        if (!InfluxDBTableConstant.DATA_FLICKER.equals(data.getClassId()) && !InfluxDBTableConstant.DATA_FLUC.equals(data.getClassId()) && !InfluxDBTableConstant.DATA_PLT.equals(data.getClassId())) {
            sql.append(InfluxDbSqlConstant.AND)
                    .append(InfluxDBTableConstant.VALUE_TYPE)
                    .append(InfluxDbSqlConstant.EQ)
                    .append(InfluxDbSqlConstant.QM)
                    .append(data.getStatMethod())
                    .append(InfluxDbSqlConstant.QM);
        }

        //频率和频率偏差仅统计T相
        if(data.getTemplateName().equals("freq_dev") || data.getTemplateName().equals("freq")){
            sql.append(InfluxDbSqlConstant.AND)
                    .append(InfluxDBTableConstant.PHASIC_TYPE)
                    .append(InfluxDbSqlConstant.EQ)
                    .append(InfluxDBTableConstant.PHASE_TYPE_T);
        }
        //时间范围处理
        sql
                .append(InfluxDbSqlConstant.AND)
                .append(InfluxDbSqlConstant.TIME).append(InfluxDbSqlConstant.GE).append(InfluxDbSqlConstant.QM).append(reportSearchParam.getStartTime()).append(InfluxDbSqlConstant.START_TIME).append(InfluxDbSqlConstant.QM)
                .append(InfluxDbSqlConstant.AND)
                .append(InfluxDbSqlConstant.TIME).append(InfluxDbSqlConstant.LT).append(InfluxDbSqlConstant.QM).append(reportSearchParam.getEndTime()).append(InfluxDbSqlConstant.END_TIME).append(InfluxDbSqlConstant.QM);

        sql.append(InfluxDbSqlConstant.TZ);

        //根据不同的库表赋值
        StatisticalDataDTO statisticalDataDTO =  commonService.selectBySql(sql);
        data.setValue(String.format("%.3f",statisticalDataDTO.getValue()));
        endList.add(data);
    }



}
