package com.hdkj.lt.si.service.measurement.impl;


import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.core.bizms.modle.dto.StateEstimation;
import com.hdkj.lt.core.bizms.modle.request.StateEstimationEquipRequest;
import com.hdkj.lt.core.bizms.mp.ArgTableNameHandler;
import com.hdkj.lt.core.sys.dao.FhzgOrganSuffixMapper;
import com.hdkj.lt.modle.dto.measurement.ContainDeviceMeasurementDTO;
import com.hdkj.lt.modle.dto.measurement.DistributionTransformerDTO;
import com.hdkj.lt.modle.dto.measurement.DistributionTransformerGetDTO;
import com.hdkj.lt.modle.dto.measurement.MeasurementTokenDTO;
import com.hdkj.lt.modle.dto.simulation.RecordsDTO;
import com.hdkj.lt.modle.vo.measurement.*;
import com.hdkj.lt.si.dao.FhzgDeviceTypeMapper;
import com.hdkj.lt.si.service.measurement.IMeasurementApiService;
import com.hdkj.hussar.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author rj
 * @date 2025/5/24 下午3:28
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MeasurementApiService implements IMeasurementApiService {

    @Autowired
    @Qualifier("simpleRestTemplate")
    private RestTemplate restTemplate;

    private final FhzgDeviceTypeMapper fhzgDeviceTypeMapper;

    private final FhzgOrganSuffixMapper fhzgOrganSuffixMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private final String BASE_URL = "http://25.55.39.199:30002";

    private MeasurementTokenDTO getMeasurementTokenDTO() {
        MeasurementTokenDTO dto = new MeasurementTokenDTO();
        dto.setClientId("HBfd939c1a43524e778544fe58d966c6");
        dto.setClientSecret("/vTxYuVsHgTv1cuoIpdO+2K974fAGtxwbOOsnKpoNYwWSadcX0we2wffjyTUYGsK");
        dto.setGrantType("client_credentials");
        return dto;
    }

    @Override
    public MeasurementTokenVO getAccessToken(MeasurementTokenDTO measurementTokenDTO) {
        String url = BASE_URL + "/baseCenter/oauth2/accessToken";
        Map<String, String> map = new HashMap<>();
        map.put("password", measurementTokenDTO.getPassword());
        map.put("grant_type", measurementTokenDTO.getGrantType());
        map.put("client_id", measurementTokenDTO.getClientId());
        map.put("client_secret", measurementTokenDTO.getClientSecret());
        map.put("user_name", measurementTokenDTO.getUserName());
        return restTemplate.postForObject(url, measurementTokenDTO, MeasurementTokenVO.class);
    }

    @Override
    public ContainDeviceMeasurementVO getTelesignalCommonQuery(ContainDeviceMeasurementDTO containDeviceMeasurementDTO) {
        String url = BASE_URL + "/realMeasCenter/measurement/commonQuery";
        HttpHeaders headers = new HttpHeaders();
        headers.add("x-token", getAccessToken(getMeasurementTokenDTO()).getAccess_token());
        HttpEntity<ContainDeviceMeasurementDTO> entity = new HttpEntity<>(containDeviceMeasurementDTO, headers);
        return restTemplate.postForObject(url, entity, ContainDeviceMeasurementVO.class);
    }

    /**
     * 获取设备曲线信息
     *
     * @param distributionTransformerDTO
     * @return
     */
    @Override
    public DistributionTransformerVO getTelemetryCommonQuery(DistributionTransformerDTO distributionTransformerDTO) {
        DistributionTransformerGetDTO distributionTransformerGetDTO = new DistributionTransformerGetDTO();
        List<DistributionTransformerGetDTO.FiltersDTO> filtersDTOS = new ArrayList<>();
        DistributionTransformerGetDTO.FiltersDTO filtersDTO = new DistributionTransformerGetDTO.FiltersDTO();
        distributionTransformerGetDTO.setPage(1);
        distributionTransformerGetDTO.setPerPage(2000);
        distributionTransformerGetDTO.setEndTime(distributionTransformerDTO.getEndTime());
        distributionTransformerGetDTO.setStartTime(distributionTransformerDTO.getStartTime());
        List<String> telemetryTypes = new ArrayList<>(Arrays.asList("TotW", "TotVar", "A_phsA", "A_phsB", "A_phsC", "PhV_phsA", "PhV_phsB", "PhV_phsC", "PPV_phsBC"
                , "PPV_phsAB", "PPV_phsCA"));
        //校验入参类型为0：配电变压器、断路器、隔离开关等  1：光伏用户 2:线路id 3：成片电压越限
        List<String> psrIds = new ArrayList<>();
        Map<String, String> lineToPsrIdMap = new HashMap<>();
        Map<String, String> lineToOpp = new HashMap<>();
        if (Objects.equals(distributionTransformerDTO.getPsrType(), "3") && !distributionTransformerDTO.getPsrIds().isEmpty()) {
            distributionTransformerDTO.getPsrIds().forEach(e -> {
                        List<String> ids = fhzgDeviceTypeMapper.getPsrIdByFeederSe(e);
                        psrIds.addAll(ids);
                        lineToPsrIdMap.put(e, ids.get(0));
                        if (e.equals(distributionTransformerDTO.getPsrIds().get(0))) {
                            lineToOpp.put(e, "0");
                        } else {
                            lineToOpp.put(e, "1");
                        }

                    }
            );
        }
        distributionTransformerDTO.getPsrIds().forEach(e -> {
            if (Objects.equals(distributionTransformerDTO.getPsrType(), "0")) {
                //动态切换表名
                //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(e, null));
                filtersDTO.setPsrType(fhzgDeviceTypeMapper.getPsrType(e));
                filtersDTO.setPsrIds(distributionTransformerDTO.getPsrIds());
            } else if (Objects.equals(distributionTransformerDTO.getPsrType(), "1")) {
                filtersDTO.setConsType("3");
                filtersDTO.setConsNos(distributionTransformerDTO.getPsrIds());
            } else if (Objects.equals(distributionTransformerDTO.getPsrType(), "2")) {
                //动态切换表名
                //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, e));
                filtersDTO.setPsrType(fhzgDeviceTypeMapper.getPsrTypeByFeeder(e));
                //动态切换表名
                //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, e));
                filtersDTO.setPsrIds(fhzgDeviceTypeMapper.getPsrIdByFeeder(e));
            } else if (Objects.equals(distributionTransformerDTO.getPsrType(), "3")) {
                //动态切换表名
                //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, e));
                filtersDTO.setPsrIds(psrIds);
                //动态切换表名
                //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, e));
                filtersDTO.setPsrType(fhzgDeviceTypeMapper.getPsrTypeByFeederSe(e));
            }
            filtersDTO.setTelemetryTypes(telemetryTypes);
        });
        filtersDTOS.add(filtersDTO);
        distributionTransformerGetDTO.setFilters(filtersDTOS);
        String url = BASE_URL + "/realMeasCenter/telemetry/commonQuery";
        HttpHeaders headers = new HttpHeaders();
        DistributionReceiveVO receiveVO = new DistributionReceiveVO();
        //优先缓存读取(标识为设备id 开始时间 结束时间 curve 字符串拼接)
        try {
            String key = filtersDTO.getPsrIds().get(0)
                    + distributionTransformerDTO.getStartTime()
                    + distributionTransformerDTO.getEndTime()
                    + "curve";
            if (distributionTransformerDTO.getPsrIds().size() > 1) {
                key = filtersDTO.getPsrIds().get(0) + filtersDTO.getPsrIds().get(1)
                        + distributionTransformerDTO.getStartTime()
                        + distributionTransformerDTO.getEndTime()
                        + "curve";
            }
            receiveVO = JSON.parseObject(JSON
                    .toJSONString(redisTemplate.opsForValue()
                            .get(key)), DistributionReceiveVO.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (receiveVO == null) {
            try {
                headers.add("x-token", getAccessToken(getMeasurementTokenDTO()).getAccess_token());
            } catch (Exception e) {
                e.printStackTrace();
            }
            HttpEntity<DistributionTransformerGetDTO> entity = new HttpEntity<>(distributionTransformerGetDTO, headers);
            log.info("请求参数: {}", JSON.toJSONString(distributionTransformerGetDTO));
            try {
                receiveVO = restTemplate.postForObject(url, entity, DistributionReceiveVO.class);
                if (receiveVO != null) {
                    String key = filtersDTO.getPsrIds().get(0)
                            + distributionTransformerDTO.getStartTime()
                            + distributionTransformerDTO.getEndTime()
                            + "curve";
                    if (distributionTransformerDTO.getPsrIds().size() > 1) {
                        key = filtersDTO.getPsrIds().get(0) + filtersDTO.getPsrIds().get(1)
                                + distributionTransformerDTO.getStartTime()
                                + distributionTransformerDTO.getEndTime()
                                + "curve";
                    }
                    //缓存曲线
                    SaveCommonQueryLocal(receiveVO, distributionTransformerDTO.getStartTime(), distributionTransformerDTO.getEndTime(), key);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        DistributionTransformerVO distributionTransformerVO = new DistributionTransformerVO();
        //电流
        List<RecordsDTO> recordsDTOSSeis = new ArrayList<>();
        //功率
        List<RecordsDTO> recordsDTOSseps = new ArrayList<>();
        //电压
        List<RecordsDTO> recordsDTOSseus = new ArrayList<>();
        //线电压
        List<RecordsDTO> recordsDTOSsepvs = new ArrayList<>();
        if (receiveVO == null) {
            throw new BusinessException("量测接口调用失败");
        }
        if (receiveVO.getResult() == null) {
            throw new BusinessException("未获取到曲线数据");
        }
        Map<String, String> volType = new HashMap<>();
        volType.put("PhV_phsA", "A相");
        volType.put("PhV_phsB", "B相");
        volType.put("PhV_phsC", "C相");
        List<String> nameList = new ArrayList<>();
        receiveVO.getResult().getRecords().forEach(r -> {
            RecordsDTO recordsDTO = new RecordsDTO();
            //电流
            if (r.getMeasTypeCode().equals("A_phsA") || r.getMeasTypeCode().equals("A_phsB") || r.getMeasTypeCode().equals("A_phsC")) {
                recordsDTO.setMeasTypeName(r.getMeasTypeName());
                //根据变比计算期望单位数据
                if (r.getCt() != null) {
                    r.getTelemetryValue().forEach(t -> {
                        t.setMeasValue(String.format("%.2f", (Double.parseDouble(t.getMeasValue()) * Double.parseDouble((String) r.getCt()))));
                    });
                }
                recordsDTO.setTelemetryValue(r.getTelemetryValue());
                recordsDTO.setMeasTypeCode(r.getMeasTypeCode());
                if (!nameList.contains(recordsDTO.getMeasTypeName()) && r.getTelemetryValue() != null) {
                    recordsDTOSSeis.add(recordsDTO);
                    nameList.add(r.getMeasTypeName());
                }
            }
            //电压
            if (distributionTransformerDTO.getPsrIds().size() < 2) {
                if (r.getMeasTypeCode().equals("PhV_phsA") || r.getMeasTypeCode().equals("PhV_phsB") || r.getMeasTypeCode().equals("PhV_phsC")) {
                    //根据变比计算期望单位数据
                    if (r.getPt() != null) {
                        r.getTelemetryValue().forEach(t -> {
                            t.setMeasValue(String.format("%.2f", (Double.parseDouble(t.getMeasValue()) * Double.parseDouble((String) r.getPt()))));
                        });
                    }
                    recordsDTO.setMeasTypeName(volType.get(r.getMeasTypeCode()));
                    recordsDTO.setTelemetryValue(r.getTelemetryValue());
                    recordsDTO.setMeasTypeCode(r.getMeasTypeCode());
//                recordsDTOSseus.add(recordsDTO);
                    if (!recordsDTOSseus.contains(recordsDTO)) {
                        recordsDTOSseus.add(recordsDTO);
                    }
                }
            }
            //功率
            if (r.getMeasTypeCode().equals("TotVar") || r.getMeasTypeCode().equals("TotW")) {
                //根据变比计算期望单位数据
                if (r.getTFactor() != null) {
                    r.getTelemetryValue().forEach(t -> {
                        t.setMeasValue(String.format("%.2f", (Double.parseDouble(t.getMeasValue()) * Double.parseDouble(r.getTFactor()))));
                    });
                }
                recordsDTO.setMeasTypeName(r.getMeasTypeName());
                recordsDTO.setTelemetryValue(r.getTelemetryValue());
                recordsDTO.setMeasTypeCode(r.getMeasTypeCode());
//                recordsDTOSseps.add(recordsDTO);
                if (!nameList.contains(recordsDTO.getMeasTypeName()) && r.getTelemetryValue() != null) {
                    recordsDTOSseps.add(recordsDTO);
                    nameList.add(r.getMeasTypeName());
                }
            }
            if (distributionTransformerDTO.getPsrIds().size() > 1) {
                if (r.getMeasTypeCode().equals("PPV_phsAB")) {
                    // || r.getMeasTypeCode().equals("PPV_phsBC") || r.getMeasTypeCode().equals("PPV_phsCA")
                    recordsDTO.setMeasTypeName(r.getMeasTypeName());
                    recordsDTO.setTelemetryValue(r.getTelemetryValue());
                    lineToPsrIdMap.forEach((key, value) -> {
                        if (value.equals(r.getPsrId())) {
                            recordsDTO.setLineId(key);
                            recordsDTO.setMeasTypeCode(lineToOpp.get(key));
                        }
                    });
                    // recordsDTO.setMeasTypeCode(r.getMeasTypeCode());
//                  recordsDTOSsepvs.add(recordsDTO);
                    if (!recordsDTOSsepvs.contains(recordsDTO)) {
                        recordsDTOSsepvs.add(recordsDTO);
                    }
                }
            }
        });
        distributionTransformerVO.setSeis(recordsDTOSSeis);
        distributionTransformerVO.setSeps(recordsDTOSseps);
        distributionTransformerVO.setSeus(recordsDTOSseus);
        distributionTransformerVO.setSepvs(recordsDTOSsepvs);
        return distributionTransformerVO;
    }

    /**
     * 按日期获配变曲线
     *
     * @param dto
     * @return
     */
    public RecordsVO queryCommonQueryByDay(DistributionTransformerDTO dto) {
        DistributionTransformerVO distributionTransformerVO = new DistributionTransformerVO();
        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            distributionTransformerVO = getTelemetryCommonQuery(dto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RecordsVO recordsVO = new RecordsVO();
        List<String> telemetryTypesA = new ArrayList<>(Arrays.asList("A_phsA", "A_phsB", "A_phsC"));
        List<String> telemetryTypesP = new ArrayList<>(Arrays.asList("PhV_phsA", "PhV_phsB", "PhV_phsC"));
        List<String> telemetryTypesT = new ArrayList<>(Arrays.asList("TotW", "TotVar"));
        List<RecordsDTO> list = new ArrayList<>();
        //判断查询种类
        if (distributionTransformerVO != null) {
            if (telemetryTypesA.contains(dto.getType())) {
                list = distributionTransformerVO.getSeis();
            } else if (telemetryTypesP.contains(dto.getType())) {
                list = distributionTransformerVO.getSeus();
            } else if (telemetryTypesT.contains(dto.getType())) {
                list = distributionTransformerVO.getSeps();
            }
        }
        if (list != null && !list.isEmpty()) {
            list.forEach(e -> {
                if (e.getMeasTypeCode().equals(dto.getType())) {
                    recordsVO.setMeasTypeName(e.getMeasTypeName());
                    //按日期重新聚合
                    Map<LocalDate, List<DistributionReceiveVO.ResultDTO.RecordsDTO.TelemetryValueDTO>> groupByDateMap
                            = e.getTelemetryValue().stream().collect(Collectors.groupingBy(b ->
                            LocalDateTime.parse(b.getDataTime(), dateTimeFormat).toLocalDate()
                    ));
                    List<TelemetryValueListDTO> listDTOS = new ArrayList<>();
                    List<List<DistributionReceiveVO.ResultDTO.RecordsDTO.TelemetryValueDTO>> dtoList = new ArrayList<>(groupByDateMap.values());
                    dtoList.forEach(d -> {
                        TelemetryValueListDTO dto1 = new TelemetryValueListDTO();
                        dto1.setValueDTOList(d);
                        listDTOS.add(dto1);
                    });
                    recordsVO.setTelemetryValue(listDTOS);
                }
            });
        }
        return recordsVO;
    }


    /**
     * 获取对侧线路七天最大电流
     *
     * @return
     */
    @Override
    public Map<String, BigDecimal> queryPeriodByCommonQuery(StateEstimationEquipRequest request) {
        Map<String, BigDecimal> rs = new HashMap<>();
        request.getPsrIds().forEach(e -> {
            DistributionTransformerGetDTO distributionTransformerGetDTO = new DistributionTransformerGetDTO();
            distributionTransformerGetDTO.setPage(1);
            distributionTransformerGetDTO.setPerPage(1000);
            distributionTransformerGetDTO.setEndTime(convertTimeFormat(request.getEndTime()));
            distributionTransformerGetDTO.setStartTime(convertTimeFormat(request.getStartTime()));
            List<String> telemetryTypes = new ArrayList<>(Arrays.asList("A_phsA", "A_phsB", "A_phsC"));
            List<DistributionTransformerGetDTO.FiltersDTO> filtersDTOS = new ArrayList<>();
            DistributionTransformerGetDTO.FiltersDTO filtersDTO = new DistributionTransformerGetDTO.FiltersDTO();
            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, e));
            String psrTypeByFeeder = fhzgDeviceTypeMapper.getPsrTypeByFeeder(e);
            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, e));
            List<String> psrIdByFeeder = fhzgDeviceTypeMapper.getPsrIdByFeeder(e);
            filtersDTO.setPsrType(psrTypeByFeeder);
            filtersDTO.setPsrIds(psrIdByFeeder);
            filtersDTO.setTelemetryTypes(telemetryTypes);
            filtersDTOS.add(filtersDTO);
            distributionTransformerGetDTO.setFilters(filtersDTOS);
            String url = BASE_URL + "/realMeasCenter/telemetry/commonQuery";
            HttpHeaders headers = new HttpHeaders();
            headers.add("x-token", getAccessToken(getMeasurementTokenDTO()).getAccess_token());
            HttpEntity<DistributionTransformerGetDTO> entity = new HttpEntity<>(distributionTransformerGetDTO, headers);
            log.info("请求参数: {}", entity);
            DistributionReceiveVO receiveVO = restTemplate.postForObject(url, entity, DistributionReceiveVO.class);
            if (receiveVO.getResult() == null) {
                throw new BusinessException("未获取到量测数据");
            }
            log.info("返回参数: {}", "receiveVO.getResult()");
            //将返回值根据lineId获取每条线路下电流的最大值
            Map<String, BigDecimal> collect = receiveVO.getResult().getRecords().stream().filter(o -> !CollectionUtils.sizeIsEmpty(o.getTelemetryValue()))
                    .flatMap(a -> a.getTelemetryValue().stream()
                            .filter(b -> b.getMeasValue() != null && !b.getMeasValue().isEmpty()) // 过滤无效值
                            .map(b -> new AbstractMap.SimpleEntry<>(a.getPsrId(), b.getMeasValue()))
                    )
                    .collect(Collectors.groupingBy(
                            AbstractMap.SimpleEntry::getKey,
                            Collectors.mapping(
                                    entry -> new BigDecimal(entry.getValue()),
                                    Collectors.reducing(BigDecimal.ZERO, BigDecimal::max)
                            )
                    ));

            rs.put(e, collect.get(psrIdByFeeder.get(0)));
        });
        return rs;
    }

    /**
     * 获取线路量测数据
     *
     * @param request
     * @return
     */
    @Override
    public ApiResponse<StateEstimation> queryByFeederSaveCommonQuery(StateEstimationEquipRequest request) {
        DistributionTransformerGetDTO distributionTransformerGetDTO = new DistributionTransformerGetDTO();
        distributionTransformerGetDTO.setPage(1);
        distributionTransformerGetDTO.setPerPage(1000);
        distributionTransformerGetDTO.setEndTime(convertTimeFormat(request.getEndTime()));
        distributionTransformerGetDTO.setStartTime(convertTimeFormat(request.getStartTime()));
        List<String> telemetryTypes = new ArrayList<>(Arrays
                .asList("TotW", "TotVar", "A_phsA", "A_phsB", "A_phsC", "Phv_phsA", "Phv_phsB", "Phv_phsC"));
        List<DistributionTransformerGetDTO.FiltersDTO> filtersDTOS = new ArrayList<>();
        DistributionTransformerGetDTO.FiltersDTO filtersDTO = new DistributionTransformerGetDTO.FiltersDTO();
        request.getPsrIds().forEach(e -> {
            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(e, null));
            filtersDTO.setPsrType(fhzgDeviceTypeMapper.getPsrTypeByFeeder(e));
            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(e, null));
            filtersDTO.setPsrIds(fhzgDeviceTypeMapper.getPsrIdByFeeder(e));
            filtersDTO.setTelemetryTypes(telemetryTypes);
        });
        filtersDTOS.add(filtersDTO);
        distributionTransformerGetDTO.setFilters(filtersDTOS);
        String url = BASE_URL + "/realMeasCenter/telemetry/commonQuery";
        HttpHeaders headers = new HttpHeaders();
        headers.add("x-token", getAccessToken(getMeasurementTokenDTO()).getAccess_token());
        HttpEntity<DistributionTransformerGetDTO> entity = new HttpEntity<>(distributionTransformerGetDTO, headers);
        log.info("请求参数: {}", entity);
        DistributionReceiveVO receiveVO = restTemplate.postForObject(url, entity, DistributionReceiveVO.class);
        if (receiveVO.getResult() == null) {
            throw new BusinessException("未获取到量测数据");
        }
        log.info("返回参数: {}", receiveVO.getResult());
        return null;
    }


    //缓存量测数据本地调用
    public void SaveCommonQueryLocal(DistributionReceiveVO request, String startTime, String endTime, String key) {
        // String psrId = request.getResult().getRecords().get(0).getPsrId();
        redisTemplate.opsForValue().set(key, request, 60, TimeUnit.MINUTES);
    }

    @Override
    //缓存量测数据接口
    public void SaveCommonQuery(DistributionReceiveVO request) {
        String psrId = request.getResult().getRecords().get(0).getPsrId();
        List<String> psrIds = new ArrayList<>();
        request.getResult().getRecords().forEach(e -> {
            if (!psrIds.contains(e.getPsrId())) {
                psrIds.add(e.getPsrId());
            }
        });
        String start = "2025-12-15 00:00:00";
        String end = "2025-12-15 23:45:00";
        String key = psrId + start + end + "curve";
        if (psrIds.size() > 1) {
            key = psrIds.get(0) + psrIds.get(1) + start + end + "curve";
        }
        redisTemplate.opsForValue().set(key, request, 1000, TimeUnit.MINUTES);
    }

    private String convertTimeFormat(String original) {
        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(original, dateTimeFormat);
        return dateTime.format(dateTimeFormatter);
    }


}
