package com.ruoyi.system.service.impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.EchartsDataUtils;
import com.ruoyi.common.core.utils.SpeedUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.EpsInitialTrafficData;
import com.ruoyi.system.domain.EpsNodeBandwidth;
import com.ruoyi.system.domain.EpsTaskStatistics;
import com.ruoyi.system.domain.InitialSwitchInfoDetails;
import com.ruoyi.system.mapper.EpsNodeBandwidthMapper;
import com.ruoyi.system.mapper.EpsTaskStatisticsMapper;
import com.ruoyi.system.mapper.InitialSwitchInfoDetailsMapper;
import com.ruoyi.system.service.EpsInitialTrafficDataService;
import com.ruoyi.system.service.IEpsTaskStatisticsService;
import com.ruoyi.system.service.IInitialSwitchInfoDetailsService;
import com.ruoyi.system.util.CalculateUtil;
import com.ruoyi.system.util.DateUtil;
import com.ruoyi.system.util.PaginationUtil;
import com.ruoyi.system.util.TrafficRedisHashUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 业务95值计算任务Service业务层处理
 *
 * @author gyt
 * @date 2025-10-29
 */
@Service
public class EpsTaskStatisticsServiceImpl implements IEpsTaskStatisticsService
{
    @Autowired
    private EpsTaskStatisticsMapper epsTaskStatisticsMapper;
    @Autowired
    private EpsInitialTrafficDataService epsInitialTrafficDataService;
    @Autowired
    private EpsNodeBandwidthMapper epsNodeBandwidthMapper;
    @Autowired
    private IInitialSwitchInfoDetailsService initialSwitchInfoDetailsService;
    @Autowired
    private InitialSwitchInfoDetailsMapper initialSwitchInfoDetailsMapper;
    @Autowired
    private TrafficRedisHashUtil trafficRedisHashUtil;

    /**
     * 查询业务95值计算任务
     *
     * @param id 业务95值计算任务主键
     * @return 业务95值计算任务
     */
    @Override
    public EpsTaskStatistics selectEpsTaskStatisticsById(Long id)
    {
        return epsTaskStatisticsMapper.selectEpsTaskStatisticsById(id);
    }

    /**
     * 查询业务95值计算任务列表
     *
     * @param epsTaskStatistics 业务95值计算任务
     * @return 业务95值计算任务
     */
    @Override
    public List<EpsTaskStatistics> selectEpsTaskStatisticsList(EpsTaskStatistics epsTaskStatistics)
    {
        List<EpsTaskStatistics> epsTaskStatisticsList = epsTaskStatisticsMapper.selectEpsTaskStatisticsList(epsTaskStatistics);
        for (EpsTaskStatistics taskStatistics : epsTaskStatisticsList) {
            String startTime = taskStatistics.getStartTime();
            String endTime = taskStatistics.getEndTime();
            String timeRange = "";
            if(endTime == null){
                timeRange = startTime;
            }else{
                timeRange = startTime + "~" + endTime;
            }
            taskStatistics.setTimeRange(timeRange);
        }
        return epsTaskStatisticsList;
    }

    /**
     * 新增业务95值计算任务
     *
     * @param epsTaskStatistics 业务95值计算任务
     * @return 结果
     */
    @Override
    public int insertEpsTaskStatistics(EpsTaskStatistics epsTaskStatistics)
    {
        epsTaskStatistics.setCreateTime(DateUtils.getNowDate());
        epsTaskStatisticsMapper.insertEpsTaskStatistics(epsTaskStatistics);
        // 开始计算
        if(StringUtils.equals(epsTaskStatistics.getResourceType(), "1")){
            if(StringUtils.equals(epsTaskStatistics.getCalculationType(), "1")){
                EpsInitialTrafficData queryParam = new EpsInitialTrafficData();
                queryParam.setStartTime(epsTaskStatistics.getStartTime());
                queryParam.setEndTime(epsTaskStatistics.getEndTime());
                queryParam.setBusinessId(epsTaskStatistics.getBusinessCode());
                queryParam.setClientIds(epsTaskStatistics.getIncludedResources());
                List<EpsInitialTrafficData> dataList = epsInitialTrafficDataService.getTrafficListByClientIds(queryParam);
                if(!dataList.isEmpty()){
                    // 存储数据到redis缓存
                    trafficRedisHashUtil.saveListToHash(epsTaskStatistics.getId().toString(), dataList);
                    // 计算95数据
                    processServer95Data(dataList, epsTaskStatistics);
                }else{
                    EpsTaskStatistics updataData = new EpsTaskStatistics();
                    updataData.setId(epsTaskStatistics.getId());
                    updataData.setTaskStatus("2");
                    updataData.setPercentile95(BigDecimal.ZERO);
                    epsTaskStatisticsMapper.updateEpsTaskStatistics(updataData);
                }
            }else{
                // 查询当月的流量 存到redis缓存
                // 处理时间
                DateUtil.TimeRange timeRange = DateUtil.getTimeRange(DateUtils.parseDate(epsTaskStatistics.getStartTime()), "2");
                EpsInitialTrafficData queryParam = new EpsInitialTrafficData();
                queryParam.setStartTime(timeRange.getStart());
                queryParam.setEndTime(timeRange.getEnd());
                queryParam.setBusinessId(epsTaskStatistics.getBusinessCode());
                queryParam.setClientIds(epsTaskStatistics.getIncludedResources());
                List<EpsInitialTrafficData> dataList = epsInitialTrafficDataService.getTrafficListByClientIds(queryParam);
                if(!dataList.isEmpty()){
                    trafficRedisHashUtil.saveListToHash(epsTaskStatistics.getId().toString(), dataList);
                }
                processAvg95Data(epsTaskStatistics);
            }
        }else{
            String resources = epsTaskStatistics.getIncludedResources();
            String clientIds = Arrays.stream(resources.split(","))
                    .map(msg -> msg.split(";"))
                    .filter(resource -> resource.length >= 3)
                    .map(resource -> resource[1])
                    .collect(Collectors.joining(","));
            String interfaceNames = Arrays.stream(resources.split(","))
                    .map(msg -> msg.split(";"))
                    .filter(resource -> resource.length >= 3)
                    .map(resource -> resource[2])
                    .collect(Collectors.joining(","));
            if(StringUtils.equals(epsTaskStatistics.getCalculationType(), "1")){
                InitialSwitchInfoDetails queryParam = new InitialSwitchInfoDetails();
                queryParam.setStartTime(epsTaskStatistics.getStartTime());
                queryParam.setEndTime(epsTaskStatistics.getEndTime());
                queryParam.setBusinessCode(epsTaskStatistics.getBusinessCode());
                queryParam.setClientIds(clientIds);
                queryParam.setInterfaceNames(interfaceNames);
                List<InitialSwitchInfoDetails> dataList = initialSwitchInfoDetailsMapper
                        .sumSwitchTrafficByclientIds(queryParam);
                if(!dataList.isEmpty()){
                    trafficRedisHashUtil.saveListToHash(epsTaskStatistics.getId().toString(), dataList);
                    processSwitch95Data(dataList, epsTaskStatistics);
                }else{
                    // 保存计算结果
                    EpsTaskStatistics updateData = new EpsTaskStatistics();
                    updateData.setId(epsTaskStatistics.getId());
                    updateData.setTaskStatus("2");
                    updateData.setPercentile95(BigDecimal.ZERO);
                    updateData.setUpdateTime(DateUtils.getNowDate());
                    epsTaskStatisticsMapper.updateEpsTaskStatistics(updateData);
                }
            }else{
                // 查询当月的流量 存到redis缓存
                // 处理时间
                DateUtil.TimeRange timeRange = DateUtil.getTimeRange(DateUtils.parseDate(epsTaskStatistics.getStartTime()), "2");
                InitialSwitchInfoDetails queryParam = new InitialSwitchInfoDetails();
                queryParam.setStartTime(timeRange.getStart());
                queryParam.setEndTime(timeRange.getEnd());
                queryParam.setBusinessCode(epsTaskStatistics.getBusinessCode());
                queryParam.setClientIds(clientIds);
                queryParam.setInterfaceNames(interfaceNames);
                List<InitialSwitchInfoDetails> dataList = initialSwitchInfoDetailsMapper
                        .sumSwitchTrafficByclientIds(queryParam);
                if(!dataList.isEmpty()){
                    trafficRedisHashUtil.saveListToHash(epsTaskStatistics.getId().toString(), dataList);
                }
                processAvg95Data(epsTaskStatistics);
            }
        }
        return 1;
    }

    public void processServer95Data(List<EpsInitialTrafficData> dataList, EpsTaskStatistics epsTaskStatistics){
        if(!dataList.isEmpty()){
            // 1. 提取并转换带宽值
            List<BigDecimal> speedsInMbps = dataList.stream()
                    .map(data -> CalculateUtil.parseSpeedToMbps(data.getOutSpeed(), epsTaskStatistics.getCalculationMode()))
                    .sorted()
                    .collect(Collectors.toList());
            // 计算95百分位
            BigDecimal percentile95 = CalculateUtil.calculatePercentile(speedsInMbps, 0.95);

            // 保存计算结果
            EpsTaskStatistics updateData = new EpsTaskStatistics();
            updateData.setId(epsTaskStatistics.getId());
            updateData.setTaskStatus("2");
            updateData.setPercentile95(percentile95.setScale(0, RoundingMode.HALF_UP));
            updateData.setUpdateTime(DateUtils.getNowDate());
            epsTaskStatisticsMapper.updateEpsTaskStatistics(updateData);
        }
    }
    public void processSwitch95Data(List<InitialSwitchInfoDetails> dataList, EpsTaskStatistics epsTaskStatistics){
        if(!dataList.isEmpty()){
            // 1. 提取并转换带宽值
            List<BigDecimal> speedsInMbps = dataList.stream()
                    .map(data -> {
                        // 根据 interfaceDeviceType 选择 inSpeed 或 outSpeed
                        String speed = data.getMaxSpeed() != null ? data.getMaxSpeed().toString() : BigDecimal.ZERO.toString();
                        // 如果 speed 是纯数字，补充单位 "B/S"（Bytes/s）
                        if (speed.matches("^\\d+(\\.\\d+)?$")) {
                            speed += " B/S";
                        }
                        return CalculateUtil.parseSpeedToMbps(speed, epsTaskStatistics.getCalculationMode());
                    })
                    .sorted()
                    .collect(Collectors.toList());

            // 2. 计算95百分位
            BigDecimal percentile95 = CalculateUtil.calculatePercentile(speedsInMbps, 0.95);

            // 保存计算结果
            EpsTaskStatistics updateData = new EpsTaskStatistics();
            updateData.setId(epsTaskStatistics.getId());
            updateData.setTaskStatus("2");
            updateData.setPercentile95(percentile95.setScale(0, RoundingMode.HALF_UP));
            updateData.setUpdateTime(DateUtils.getNowDate());
            epsTaskStatisticsMapper.updateEpsTaskStatistics(updateData);
        }
    }

    public void processAvg95Data(EpsTaskStatistics epsTaskStatistics) {
        EpsNodeBandwidth epsNodeBandwidth = new EpsNodeBandwidth();
        epsNodeBandwidth.setMonthTime(epsTaskStatistics.getStartTime());
        epsNodeBandwidth.setBusinessId(epsTaskStatistics.getBusinessCode());
        EpsNodeBandwidth calculatedData = epsNodeBandwidthMapper.calculateAvg(epsNodeBandwidth);
        if (calculatedData != null) {
            BigDecimal sum95Daily = Optional.ofNullable(calculatedData.getBandwidth95Daily()).orElse(BigDecimal.ZERO);
            LocalDate monthTime = null;
            try {
                String monthStr = epsNodeBandwidth.getMonthTime() == null
                        ? epsNodeBandwidth.getStartTime().substring(0, 7)
                        : epsNodeBandwidth.getMonthTime();

                YearMonth yearMonth = YearMonth.parse(monthStr);
                monthTime = yearMonth.atDay(1); // 转换为当月第一天
            } catch (Exception e) {
                System.err.println("月份格式错误：" + e.getMessage());
            }
            int daysInMonth = YearMonth.from(monthTime).lengthOfMonth();
            if (daysInMonth == 0) {
                System.err.println("当月天数为0，月份: " + epsNodeBandwidth.getMonthTime() == null
                        ? epsNodeBandwidth.getStartTime() : epsNodeBandwidth.getMonthTime());
            }
            // 月均日95值
            BigDecimal avgMonthly = sum95Daily.divide(BigDecimal.valueOf(daysInMonth), 0, RoundingMode.HALF_UP);
            // 保存计算结果
            EpsTaskStatistics updateData = new EpsTaskStatistics();
            updateData.setId(epsTaskStatistics.getId());
            updateData.setTaskStatus("2");
            updateData.setMonthlyAvgPercentile95(avgMonthly);
            updateData.setUpdateTime(DateUtils.getNowDate());
            epsTaskStatisticsMapper.updateEpsTaskStatistics(updateData);
        }else{
            EpsTaskStatistics updataData = new EpsTaskStatistics();
            updataData.setId(epsTaskStatistics.getId());
            updataData.setTaskStatus("2");
            updataData.setMonthlyAvgPercentile95(BigDecimal.ZERO);
            updataData.setUpdateTime(DateUtils.getNowDate());
            epsTaskStatisticsMapper.updateEpsTaskStatistics(updataData);
        }
    }
    /**
     * 修改业务95值计算任务
     *
     * @param epsTaskStatistics 业务95值计算任务
     * @return 结果
     */
    @Override
    public int updateEpsTaskStatistics(EpsTaskStatistics epsTaskStatistics)
    {
        epsTaskStatistics.setUpdateTime(DateUtils.getNowDate());
        return epsTaskStatisticsMapper.updateEpsTaskStatistics(epsTaskStatistics);
    }

    /**
     * 批量删除业务95值计算任务
     *
     * @param ids 需要删除的业务95值计算任务主键
     * @return 结果
     */
    @Override
    public int deleteEpsTaskStatisticsByIds(Long[] ids)
    {
        return epsTaskStatisticsMapper.deleteEpsTaskStatisticsByIds(ids);
    }

    /**
     * 删除业务95值计算任务信息
     *
     * @param id 业务95值计算任务主键
     * @return 结果
     */
    @Override
    public int deleteEpsTaskStatisticsById(Long id)
    {
        return epsTaskStatisticsMapper.deleteEpsTaskStatisticsById(id);
    }

    @Override
    public PageInfo<?> getRelateData(EpsTaskStatistics epsTaskStatistics) {
        // 分页参数
        Integer pageNum = epsTaskStatistics.getPageNum();
        Integer pageSize = epsTaskStatistics.getPageSize();
        // 查询任务详情
        Long taskId = epsTaskStatistics.getId();
        EpsTaskStatistics taskMsg = epsTaskStatisticsMapper.selectEpsTaskStatisticsById(taskId);
        if(StringUtils.equals("1", taskMsg.getResourceType())){
            List<EpsInitialTrafficData> list = trafficRedisHashUtil.getListFromHash(taskId.toString(), EpsInitialTrafficData.class);
            if(!list.isEmpty()){
                if(StringUtils.equals("1", taskMsg.getCalculationType())){
                    int index = CalculateUtil.calculate95Index(list, 0.05);
                    list.get(index).setFlag95(true);
                    List<EpsInitialTrafficData> pageList = list.stream()
                            .skip((long) (pageNum - 1) * pageSize)
                            .limit(pageSize)
                            .collect(Collectors.toList());
                    for (EpsInitialTrafficData epsInitialTrafficData : pageList) {
                        epsInitialTrafficData.setBusinessId(taskMsg.getBusinessCode());
                        epsInitialTrafficData.setClientId(taskMsg.getIncludedResources());
                    }
                    PageInfo<EpsInitialTrafficData> pageInfo = new PageInfo<>();
                    pageInfo.setPageNum(pageNum);
                    pageInfo.setPageSize(pageSize);
                    pageInfo.setTotal(list.size());
                    pageInfo.setList(pageList);
                    return pageInfo;
                }else{
                    // 2. 按天分组
                    Map<String, List<EpsInitialTrafficData>> groupedData = list.stream()
                            .collect(Collectors.groupingBy(data -> {
                                // 使用 SimpleDateFormat 格式化日期部分
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                return sdf.format(data.getCreateTime());
                            }));
                    // 获取指定日期的数据
                    List<EpsInitialTrafficData> dailyData = groupedData.getOrDefault(epsTaskStatistics.getAvgTime(), new ArrayList<>());
                    int index = CalculateUtil.calculate95Index(dailyData, 0.05);
                    dailyData.get(index).setFlag95(true);
                    PageInfo<EpsInitialTrafficData> resultData = PaginationUtil.paginate(dailyData, pageNum, pageSize);
                    return resultData;
                }
            }
        }else{
            String resources = taskMsg.getIncludedResources();
            String result = Arrays.stream(resources.split(","))
                    .map(msg -> msg.split(";"))
                    .filter(resource -> resource.length >= 4)
                    .map(resource -> "[" + resource[3] + "].[" + resource[2] + "]")
                    .collect(Collectors.joining(";"));
            List<InitialSwitchInfoDetails> list = trafficRedisHashUtil.getListFromHash(taskId.toString(), InitialSwitchInfoDetails.class);
            if(!list.isEmpty()){
                if(StringUtils.equals("1", taskMsg.getCalculationType())){

                    int index = CalculateUtil.calculate95Index(list, 0.05);
                    list.get(index).setFlag95(true);
                    List<InitialSwitchInfoDetails> pageList = list.stream()
                            .skip((long) (pageNum - 1) * pageSize)
                            .limit(pageSize)
                            .collect(Collectors.toList());
                    for (InitialSwitchInfoDetails initialSwitchInfoDetails : pageList) {
                        initialSwitchInfoDetails.setName(result);
                    }
                    PageInfo<InitialSwitchInfoDetails> pageInfo = new PageInfo<>();
                    pageInfo.setPageNum(pageNum);
                    pageInfo.setPageSize(pageSize);
                    pageInfo.setTotal(list.size());
                    pageInfo.setList(pageList);
                    return pageInfo;
                }else{
                    // 2. 按天分组
                    Map<String, List<InitialSwitchInfoDetails>> groupedData = list.stream()
                            .collect(Collectors.groupingBy(data -> {
                                // 使用 SimpleDateFormat 格式化日期部分
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                return sdf.format(data.getCreateTime());
                            }));
                    // 获取指定日期的数据
                    List<InitialSwitchInfoDetails> dailyData = groupedData.getOrDefault(epsTaskStatistics.getAvgTime(), new ArrayList<>());
                    int index = CalculateUtil.calculate95Index(dailyData, 0.05);
                    dailyData.get(index).setFlag95(true);
                    PageInfo<InitialSwitchInfoDetails> resultData = PaginationUtil.paginate(dailyData, pageNum, pageSize);
                    return resultData;
                }
            }
        }
        return new PageInfo<>();
    }

    /**
     * 获取月均日数据的日期
     * @param epsTaskStatistics
     * @return
     */
    public List<String> getAvgTimeList(EpsTaskStatistics epsTaskStatistics){
        List<String> resultList = new ArrayList<>();
        Long taskId = epsTaskStatistics.getId();
        EpsTaskStatistics taskMsg = epsTaskStatisticsMapper.selectEpsTaskStatisticsById(taskId);

        if(StringUtils.equals(taskMsg.getCalculationType(), "2")){
            List<EpsInitialTrafficData> list = trafficRedisHashUtil.getListFromHash(taskId.toString(), EpsInitialTrafficData.class);
            if(!list.isEmpty()){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                resultList = list.stream()
                        .map(data -> sdf.format(data.getCreateTime()))
                        .distinct()
                        .sorted()
                        .collect(Collectors.toList());
            }
        }
        return resultList;
    }

    @Override
    public int updateRelateData(EpsTaskStatistics epsTaskStatistics) {
        // 查询任务详情
        Long taskId = epsTaskStatistics.getId();
        EpsTaskStatistics taskMsg = epsTaskStatisticsMapper.selectEpsTaskStatisticsById(taskId);
        if(StringUtils.equals("1", taskMsg.getResourceType())){
            EpsInitialTrafficData epsInitialTrafficData = new EpsInitialTrafficData();
            epsInitialTrafficData.setOutSpeed(epsTaskStatistics.getNeedSpeed().toString());
            epsInitialTrafficData.setCreateTime(DateUtils.parseDate(epsTaskStatistics.getNeedTime()));
            trafficRedisHashUtil.updateItemInHash(taskId.toString(), epsInitialTrafficData, epsTaskStatistics.getNeedTime());
        }else{
            InitialSwitchInfoDetails initialSwitchInfoDetails = new InitialSwitchInfoDetails();
            initialSwitchInfoDetails.setMaxSpeed(epsTaskStatistics.getNeedSpeed());
            initialSwitchInfoDetails.setCreateTime(DateUtils.parseDate(epsTaskStatistics.getNeedTime()));
            trafficRedisHashUtil.updateItemInHash(taskId.toString(), initialSwitchInfoDetails, epsTaskStatistics.getNeedTime());
        }
        return 1;
    }

    @Override
    public int recaculate(EpsTaskStatistics epsTaskStatistics) {
        // 查询任务详情
        Long taskId = epsTaskStatistics.getId();
        EpsTaskStatistics taskMsg = epsTaskStatisticsMapper.selectEpsTaskStatisticsById(taskId);
        // 任务状态改为计算中
        EpsTaskStatistics updateParam = new EpsTaskStatistics();
        updateParam.setId(taskId);
        updateParam.setTaskStatus("1");
        epsTaskStatisticsMapper.updateEpsTaskStatistics(updateParam);
        // 开始计算
        if(StringUtils.equals("1", taskMsg.getResourceType())){
            List<EpsInitialTrafficData> dataList = trafficRedisHashUtil.getListFromHash(taskId.toString(), EpsInitialTrafficData.class);
            if(StringUtils.equals(taskMsg.getCalculationType(), "1")){
                processServer95Data(dataList, taskMsg);
            }else{
                processAvg95Data(taskMsg);
            }
        }else{
            List<InitialSwitchInfoDetails> dataList = trafficRedisHashUtil.getListFromHash(taskId.toString(), InitialSwitchInfoDetails.class);
            if(StringUtils.equals(taskMsg.getCalculationType(), "1")){
                processSwitch95Data(dataList, taskMsg);
            }else{
                processAvg95Data(taskMsg);
            }
        }
        return 1;
    }

    @Override
    public Map getRraphicalMsg(EpsTaskStatistics epsTaskStatistics) {
        // 查询任务详情
        Long taskId = epsTaskStatistics.getId();
        EpsTaskStatistics taskMsg = epsTaskStatisticsMapper.selectEpsTaskStatisticsById(taskId);
        String startTime = taskMsg.getStartTime();
        String endTime = taskMsg.getEndTime();
        String timeRange = "";
        if(endTime == null){
            timeRange = startTime;
        }else{
            timeRange = startTime + "~" + endTime;
        }
        if(StringUtils.equals("1", taskMsg.getResourceType())){
            List<EpsInitialTrafficData> list = trafficRedisHashUtil.getListFromHash(taskId.toString(), EpsInitialTrafficData.class);
            if(!list.isEmpty()){
                try{
                    BigDecimal percentile95 = "1".equals(taskMsg.getCalculationType())
                            ? taskMsg.getPercentile95()
                            : taskMsg.getMonthlyAvgPercentile95();
                    list.forEach(data -> data.setPercentile95(SpeedUtils.mbitToBit(percentile95)));
                    SpeedUtils.SpeedResult result = SpeedUtils.calculateWithStringTraffic(list, "inSpeed", "outSpeed");
                    BigDecimal divisor = SpeedUtils.getDivisor(result.getRecommendedUnit());
                    Map<String, Function<EpsInitialTrafficData, ?>> extractors = new LinkedHashMap<>();

                    extractors.put("netOutSpeedData", info ->
                            info != null && info.getOutSpeed() != null ?
                                    new BigDecimal(info.getOutSpeed()).divide(divisor, 0, RoundingMode.HALF_UP) :
                                    0);
                    extractors.put("percentile95", info ->
                            info != null && info.getPercentile95() != null ?
                                    info.getPercentile95().divide(divisor, 2, RoundingMode.HALF_UP) :
                                    0);
                    Map<String, Object> resultMap = EchartsDataUtils.buildEchartsData(list, EpsInitialTrafficData::getCreateTime, extractors);
                    resultMap.put("other", result);
                    resultMap.put("percentile95", percentile95);
                    resultMap.put("timeRange", timeRange);
                    return resultMap;
                }catch (Exception e){
                    System.err.println(e.getMessage());
                }
            }
        }else{
            List<InitialSwitchInfoDetails> list = trafficRedisHashUtil.getListFromHash(taskId.toString(), InitialSwitchInfoDetails.class);
            if(!list.isEmpty()){
                try{
                    BigDecimal percentile95 = "1".equals(taskMsg.getCalculationType())
                            ? taskMsg.getPercentile95()
                            : taskMsg.getMonthlyAvgPercentile95();
                    list.forEach(data -> data.setPercentile95(SpeedUtils.mbitToBit(percentile95)));
                    SpeedUtils.SpeedResult result = SpeedUtils.calculateWithAverageBasedUnit(list, "inSpeed", "outSpeed");
                    BigDecimal divisor = SpeedUtils.getDivisor(result.getRecommendedUnit());
                    Map<String, Function<InitialSwitchInfoDetails, ?>> extractors = new LinkedHashMap<>();
                    extractors.put("netInSpeedData", info ->
                            info != null && info.getInSpeed() != null ?
                                    info.getInSpeed().divide(divisor, 0, RoundingMode.HALF_UP) :
                                    0);

                    extractors.put("netOutSpeedData", info ->
                            info != null && info.getOutSpeed() != null ?
                                    info.getOutSpeed().divide(divisor, 0, RoundingMode.HALF_UP) :
                                    0);
                    extractors.put("percentile95", info ->
                            info != null && info.getPercentile95() != null ?
                                    info.getPercentile95().divide(divisor, 2, RoundingMode.HALF_UP) :
                                    0);
                    Map<String, Object> resultMap = EchartsDataUtils.buildEchartsData(list, InitialSwitchInfoDetails::getCreateTime, extractors);
                    resultMap.put("other", result);
                    if(StringUtils.equals("1", taskMsg.getCalculationType())){
                        resultMap.put("percentile95", taskMsg.getPercentile95());
                    }else{
                        resultMap.put("percentile95", taskMsg.getMonthlyAvgPercentile95());
                    }
                    resultMap.put("timeRange", timeRange);
                    return resultMap;
                }catch (Exception e){
                    System.err.println(e.getMessage());
                }
            }
        }
        return new HashMap();
    }
}
