package com.njcn.product.event.transientes.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.product.event.dataTransmit.DataSynchronization;
import com.njcn.product.event.devcie.config.PqlineCache;
import com.njcn.product.event.devcie.job.LineCacheJob;
import com.njcn.product.event.devcie.mapper.PqLineMapper;
import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO;
import com.njcn.product.event.devcie.pojo.po.PqLine;
import com.njcn.product.event.devcie.pojo.po.PqsDeptsline;
import com.njcn.product.event.devcie.service.PqsDeptslineService;
import com.njcn.product.event.transientes.mapper.PqUserLedgerMapper;
import com.njcn.product.event.transientes.mapper.PqUserLineAssMapper;
import com.njcn.product.event.transientes.mapper.PqsEventdetailMapper;
import com.njcn.product.event.transientes.pojo.dto.MessaeDTO;
import com.njcn.product.event.transientes.pojo.dto.SmsResponseDTO;
import com.njcn.product.event.transientes.pojo.dto.SmsSendDTO;
import com.njcn.product.event.transientes.pojo.dto.UpLoadEvent;
import com.njcn.product.event.transientes.pojo.param.MonitorTerminalParam;
import com.njcn.product.event.transientes.pojo.po.*;
import com.njcn.product.event.transientes.pojo.vo.EventDetailVO;
import com.njcn.product.event.transientes.service.*;
import com.njcn.product.event.transientes.utils.SmsUtils;
import com.njcn.product.event.transientes.websocket.WebSocketServer;
import com.njcn.product.event.config.RedisUtil;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.njcn.product.event.transientes.pojo.constant.RedisConstant.REDIS_DEPT_INDEX;

/**
 * @Author: cdf
 * @CreateTime: 2025-06-23
 * @Description:
 */
@Api(tags = "暂降接收")
@RequestMapping("accept")
@RestController
@RequiredArgsConstructor
@Slf4j
public class EventGateController extends BaseController {
    private final PqUserLineAssMapper pqUserLineAssMapper;
    private final PqUserLedgerMapper pqUserLedgerMapper;
    private final PqsEventdetailMapper pqsEventdetailMapper;
    @Value("${SYS_TYPE_ZT}")
    private String sysTypeZt;

    @Value("${business.RealTimeSMSSwitch:false}")
    private boolean realTimeSMSSwitch;

    private final WebSocketServer webSocketServer;

    private final PqsDeptslineService pqsDeptslineService;

    private final PqsDeptsService pqsDeptsService;

    private final PqsUserService pqsUserService;

    private final PqsUsersetService pqsUsersetService;

    private final PqLineMapper pqLineMapper;

    private final EventGateService eventGateService;

    private final MsgEventConfigService msgEventConfigService;

    private final MsgEventInfoService msgEventInfoService;

    private final RedisUtil redisUtil;

    private final SmsUtils smsUtils;

    private final ThreadPoolTaskExecutor smsTaskExecutor;
    private final PqlineCache pqlineCache;

    private final SendMessageService messageService;
    private final CleanEventService cleanEventService;
    private final DataSynchronization dataSynchronization;
    @GetMapping("/testSendMessage")
    @ApiOperation("接收远程推送的暂态事件")
    public HttpResult<Object> SendMessage(@RequestParam("startTime") String startTime,@RequestParam("endtTime")  String endtTime) {
        String methodDescribe = getMethodDescribe("SendMessage");
        messageService.sendMessage(LocalDateTimeUtil.parse(startTime,DatePattern.NORM_DATETIME_PATTERN),LocalDateTimeUtil.parse(endtTime,DatePattern.NORM_DATETIME_PATTERN));
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);

    }
    @GetMapping("/testClean")
    @ApiOperation("接收远程推送的暂态事件")
    public HttpResult<Object> testClean() {
        String methodDescribe = getMethodDescribe("testClean");
        dataSynchronization.syncFail();
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);

    }

    @OperateInfo
    @GetMapping("/eventMsg")
    @ApiOperation("接收远程推送的暂态事件")
    @ApiImplicitParam(name = "eventMsg", value = "暂态事件json字符", required = true)
    public HttpResult<Object> eventMsg(@RequestParam("msg") String msg) {
        String methodDescribe = getMethodDescribe("eventMsg");
        log.info("收到前置推送暂降事件,事件详情：" + msg);

        JSONObject jsonObject;
        try {
            //下面一行代码正式环境需要放开
            jsonObject = new JSONObject(msg);
            //下面一行代码正式环境需要放开
            //jsonObject = test();

            if (msgEventConfigService.getEventType().contains(jsonObject.get("wavetype").toString())
                    && Float.parseFloat(jsonObject.get("eventvalue").toString()) <= msgEventConfigService.getEventValue()
                    && (Float.parseFloat(jsonObject.get("persisttime").toString()) * 1000) >= msgEventConfigService.getEventDuration()) {
                //过滤重要暂降事件
                //F47过滤
                float eventvalue = Float.parseFloat(jsonObject.get("eventvalue").toString())*100;
                float persisttime = Float.parseFloat(jsonObject.get("persisttime").toString()) * 1000;
                if(shouldSendSMS(eventvalue,persisttime)){
                    Integer lineId = Integer.valueOf(jsonObject.get("lineid").toString());
                    List<PqUserLineAssPO> assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper<PqUserLineAssPO>().eq(PqUserLineAssPO::getLineIndex, lineId));

                    String str ;
                    if (CollUtil.isNotEmpty(assList)) {
                        List<String> userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
                        List<PqUserLedgerPO> poList = pqUserLedgerMapper.selectList(new LambdaQueryWrapper<PqUserLedgerPO>().select(PqUserLedgerPO::getId, PqUserLedgerPO::getCustomerName,PqUserLedgerPO::getIsShow).in(PqUserLedgerPO::getId, userIds));
                        List<PqUserLedgerPO> isShowUser = poList.stream().filter(temp -> temp.getIsShow() == 1).collect(Collectors.toList());
                        List<PqUserLedgerPO> noShowUser = poList.stream().filter(temp -> temp.getIsShow() != 1).collect(Collectors.toList());
                        String strUser="" ;

                        if(CollectionUtil.isEmpty(isShowUser)){
                            strUser =strUser+"影响集成电路敏感用户:无;";
                        }else {
                            String sensitiveUser = isShowUser.stream().map(PqUserLedgerPO::getCustomerName).collect(Collectors.joining(";"));
                            strUser =strUser+"影响集成电路敏感用户:"+sensitiveUser+";";
                        }
                        if(CollectionUtil.isEmpty(noShowUser)){
                            strUser =strUser+"影响其他用户:无;";
                        }else {
                            String sensitiveUser = noShowUser.stream().map(PqUserLedgerPO::getCustomerName).collect(Collectors.joining(";"));
                            strUser =strUser+"影响其他用户:"+sensitiveUser+";";
                        }
                        str = strUser;
                    } else {
                        str = "/";
                    }

                    List<PqsDepts> deptsList = (List<PqsDepts>) redisUtil.getObjectByKey(REDIS_DEPT_INDEX + StrUtil.DASHED + "AllDept");
                    Map<String, PqsDepts> deptsMap = deptsList.stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex, dept -> dept));

                    List<PqsDeptsline> deptslineList = pqsDeptslineService.lambdaQuery().eq(PqsDeptsline::getLineIndex, lineId).list();
                    List<String> deptIds = deptslineList.stream().map(PqsDeptsline::getDeptsIndex).collect(Collectors.toList());
                    Set<String> set = getAllParentIdsWithChildrenBatch(deptIds, deptsMap);
                    jsonObject.putOpt("objName", str);
                    jsonObject.putOpt("dept", String.join(StrUtil.COMMA, set));

//                    webSocketServer.sendMessageToAll(jsonObject.toString());

                    //针对前置推送的暂降事件进行短信发送功能
                    //开启实时短信功能默认关闭走批量
                    if(realTimeSMSSwitch){
                        smsTaskExecutor.execute(() -> {
                            sendMessage(jsonObject, str);
                        });
                    }


                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("暂降json格式异常!{}", e.getMessage());
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }

    private boolean shouldSendSMS( Float value , Float time ) {


        // 条件1: 电压降至50%以下，持续时间超过20ms
        if (value < 50 && time >= 20) {
            return true;
        }

        // 条件2: 电压降至50%—70%，持续时间超过200ms
        if (value >= 50 && value < 70 && time >= 200) {
            return true;
        }

        // 条件3: 电压降至70%—80%，持续时间超过500ms
        if (value >= 70 && value < 80 && time >= 500) {
            return true;
        }

        return false;
    }

    public Set<String> getAllParentIdsRecursive(String deptId, Map<String, PqsDepts> deptMap, Set<String> result) {
        if (deptId == null || result.contains(deptId)) {
            return result;
        }

        result.add(deptId); // 添加当前ID
        PqsDepts dept = deptMap.get(deptId);
        if (dept != null && dept.getParentnodeid() != null) {
            getAllParentIdsRecursive(dept.getParentnodeid(), deptMap, result); // 递归处理父节点
        }
        return result;
    }

    // 批量处理入口方法
    public Set<String> getAllParentIdsWithChildrenBatch(Collection<String> deptIds, Map<String, PqsDepts> deptMap) {
        Set<String> result = new HashSet<>();
        for (String deptId : deptIds) {
            getAllParentIdsRecursive(deptId, deptMap, result);
        }
        return result;
    }

    @OperateInfo
    @GetMapping("/testEvent")
    @ApiOperation("接收远程推送的暂态事件")
    public HttpResult<Object> testEvent() {
        String methodDescribe = getMethodDescribe("testEvent");
        log.info("模拟测试发送暂降事件-------------------------");

        JSONObject jsonObject;
        try {
            //下面一行代码正式环境需要放开
            jsonObject = test();
            List<PqsDepts> deptsList = (List<PqsDepts>) redisUtil.getObjectByKey(REDIS_DEPT_INDEX + StrUtil.DASHED + "AllDept");
            List<String> deptIds = deptsList.stream().map(PqsDepts::getDeptsIndex).distinct().collect(Collectors.toList());
            jsonObject.putOpt("dept", String.join(StrUtil.COMMA,deptIds));

            if (msgEventConfigService.getEventType().contains(jsonObject.get("wavetype").toString()) && Float.parseFloat(jsonObject.get("eventvalue").toString()) <= msgEventConfigService.getEventValue()) {
               log.info("122345678788999999----------测试发送数据成功: {}",jsonObject);
                webSocketServer.sendMessageToAll(jsonObject.toString());

                //开始发送短信
                try {
                    sendMessage(jsonObject, "/");
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("短信组装发送失败!失败原因{}", e.getMessage());
                }

            }

        } catch (Exception e) {
            log.error("暂降json格式异常!{}", e.getMessage());
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }

    private static final int MAX_RETRY_COUNT = 3; // 最大重试次数


    //测试模拟，正式环境删除
    private PqsEventdetail createEvent(JSONObject jsonObject, LocalDateTime now) {
        PqsEventdetail pqsEventdetail = new PqsEventdetail();
        pqsEventdetail.setEventdetailIndex(jsonObject.get("eventdetail_index").toString());
        pqsEventdetail.setLineid(Integer.valueOf(jsonObject.get("lineid").toString()));
        pqsEventdetail.setTimeid(now);
        pqsEventdetail.setMs(new BigDecimal(jsonObject.get("ms").toString()));
        pqsEventdetail.setWavetype(Integer.valueOf(jsonObject.get("wavetype").toString()));
        pqsEventdetail.setPersisttime(Double.valueOf(jsonObject.get("persisttime").toString()));
        pqsEventdetail.setEventvalue(Double.valueOf(jsonObject.get("eventvalue").toString()));
        pqsEventdetail.setEventreason(jsonObject.get("eventreason").toString());
        pqsEventdetail.setEventtype(jsonObject.get("eventtype").toString());

        return pqsEventdetail;
    }

    //测试模拟，正式环境删除
    private JSONObject test() {
        /*----------------------------------------------------------------------------------------*/
        //以下部分为测试数据后续删除
        List<PqLine> pqLineList = pqLineMapper.selectList(new LambdaQueryWrapper<>());
        List<Integer> lineList = pqLineList.stream().map(PqLine::getLineIndex).collect(Collectors.toList());

        List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = new ArrayList<>();
        if(lineList.size()>1000){
            List<List<Integer>> listIds = CollUtil.split(lineList,1000);
            for(List<Integer> itemIds : listIds){
                List<LedgerBaseInfoDTO> temp =pqLineMapper.getBaseLineInfo(itemIds);
                ledgerBaseInfoDTOS.addAll(temp);
            }
        }else {
            List<LedgerBaseInfoDTO> temp =pqLineMapper.getBaseLineInfo(lineList);
            ledgerBaseInfoDTOS.addAll(temp);
        }
        Map<Integer, LedgerBaseInfoDTO> map = ledgerBaseInfoDTOS.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        Random random = new Random();
        Integer lineId = lineList.get(random.nextInt(lineList.size()));
        LedgerBaseInfoDTO dto = map.get(lineId);

        LocalDateTime now = LocalDateTime.now();
        String timeStr = DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN);
        Long ms = (long) random.nextInt(999);

        Integer[] temArr = new Integer[]{1, 3};
        Integer wave = random.nextInt(2);


        Double per = (double) random.nextInt(5000);

        double minV = 0.1;
        double maxV = 0.9;
        Double eventValue = minV + (maxV - minV) * Math.random();

        String id = IdUtil.simpleUUID();

        JSONObject tem = new JSONObject();
        tem.set("eventdetail_index", id);
        tem.set("lineid", lineId.toString());
        tem.set("timeid", timeStr);
        tem.set("ms", ms.toString());
        tem.set("wavetype", temArr[wave]);
        tem.set("persisttime", per.toString());
        tem.set("eventvalue", eventValue);
        tem.set("eventreason", "97a56e0f-b546-4c1e-b27c-52463fc1d82f");
        tem.set("eventtype", "676683a0-7f80-43e6-8df8-bea8ed235d67");
        tem.set("gdname", "测试供电公司");
        tem.set("bdname", dto.getStationName());
        tem.set("pointname", dto.getLineName());

     /*   PqsEventdetail pqsEventdetail = createEvent(tem, now);
        if (msgEventConfigService.getEventType().contains(tem.get("wavetype").toString())) {
            webSocketServer.sendMessageToAll(tem.toString());
        }
        pqsEventdetailService.save(pqsEventdetail);*/
        /*----------------------------------------------------------------------------------------*/

        return tem;
    }


    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/getTransientAnalyseWave")
    @ApiOperation("暂态事件波形分析")
    public HttpResult<WaveDataDTO> getTransientAnalyseWave(@RequestBody MonitorTerminalParam param) {
        String methodDescribe = getMethodDescribe("getTransientAnalyseWave");
        WaveDataDTO wave = eventGateService.getTransientAnalyseWave(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, wave, methodDescribe);
    }


    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/phoneSend")
    @ApiOperation("模拟发送短信")
    public HttpResult<String> simulationSend(@RequestParam("id") String id) {

        String methodDescribe = getMethodDescribe("simulationSend");

        PqsEventdetail pqsEventdetail = pqsEventdetailMapper.selectOne(new LambdaQueryWrapper<PqsEventdetail>().eq(PqsEventdetail::getEventdetailIndex, id));
        UpLoadEvent upLoadEvent = new UpLoadEvent();
        upLoadEvent.setEventdetail_index(pqsEventdetail.getEventdetailIndex());
        upLoadEvent.setMs(pqsEventdetail.getMs());
        upLoadEvent.setBdname("测试电站");
        upLoadEvent.setLineid(pqsEventdetail.getLineid());
        upLoadEvent.setTimeid(LocalDateTimeUtil.format(pqsEventdetail.getTimeid(), DatePattern.NORM_DATETIME_PATTERN));
        upLoadEvent.setWavetype(pqsEventdetail.getWavetype());
        upLoadEvent.setPersisttime(pqsEventdetail.getPersisttime());
        upLoadEvent.setEventvalue(pqsEventdetail.getEventvalue());
        upLoadEvent.setEventreason("");
        upLoadEvent.setEventtype(pqsEventdetail.getEventtype());
        upLoadEvent.setPointname("测试监测点");
        upLoadEvent.setGdname("测试供电公司");
        JSONObject jsonObject = new JSONObject(upLoadEvent);

        sendMessage(jsonObject, "/");
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/simpleTest")
    @ApiOperation("模拟发送简单测试短信")
    public HttpResult<Object> simpleTest() {
        String methodDescribe = getMethodDescribe("simulationSend");
        List<SmsSendDTO.ItemInner> msgDTOList = new ArrayList<>();
        SmsSendDTO.ItemInner msgDTO = new SmsSendDTO.ItemInner();
        msgDTO.setCustomMsgID(IdUtil.simpleUUID());
        msgDTO.setContent("test");
        msgDTO.setTo("18815508963");
        msgDTOList.add(msgDTO);
        List<SmsResponseDTO.SmsItem> result = smsUtils.sendSmSToUser(msgDTOList);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo
    @PostMapping("/messageGenerate")
    @ApiOperation("暂降事件短信内容生成")
    public HttpResult<MessaeDTO> messageGenerate(@RequestParam String eventId) {
        String methodDescribe = getMethodDescribe("messageGenerate");
        MessaeDTO result = eventGateService.messageGenerate(eventId);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }


    @OperateInfo
    @PostMapping("/messageGenerateByIds")
    @ApiOperation("暂降事件短信内容生成")
    public HttpResult<MessaeDTO> messageGenerateByIds(@RequestParam List<String> eventIds) {
        String methodDescribe = getMethodDescribe("messageGenerateByIds");
        MessaeDTO result = eventGateService.messageGenerateByIds(eventIds);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }
    @OperateInfo
    @PostMapping("/msgGenerateByMsg")
    @ApiOperation("根据故障短信内容生成暂降短信")
    public HttpResult<MessaeDTO> msgGenerateByMsg(@RequestParam String msg) {
        String methodDescribe = getMethodDescribe("msgGenerateByMsg");
        MessaeDTO result = eventGateService.msgGenerateByMsg(msg);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }
    @OperateInfo
    @PostMapping("/messageSend")
    @ApiOperation("短信发送")
    public HttpResult<List<MsgEventInfo>> messageSend(@RequestBody MessaeDTO messaeDTO) {
        String methodDescribe = getMethodDescribe("messageGenerate");
        List<MsgEventInfo> resultList = new ArrayList<>();
        List<SmsSendDTO.ItemInner> msgDTOList = new ArrayList<>();
        List<PqsUser> allUsers = messaeDTO.getPqsUsers().values()           // Collection<List<PqsUserSet>>
                .stream()                                       // 转为流
                .filter(list -> list != null)                  // 过滤掉null的List（可选）
                .flatMap(List::stream)                         // 将每个List拆开，合并成一个流
                .collect(Collectors.toList());
        for (PqsUser user : allUsers) {
            String msgId = IdUtil.simpleUUID();

            SmsSendDTO.ItemInner dto = new SmsSendDTO.ItemInner();
            dto.setContent(messaeDTO.getMessage());
            dto.setTo(user.getPhone());
            dto.setCustomMsgID(msgId);
            msgDTOList.add(dto);
            for (String eventId :messaeDTO.getEventIds()){
                MsgEventInfo msgEventInfo = new MsgEventInfo();
                msgEventInfo.setMsgIndex(msgId);
                msgEventInfo.setMsgContent(messaeDTO.getMessage());
                msgEventInfo.setPhone(user.getPhone());
                msgEventInfo.setUserId(user.getUserIndex());
                msgEventInfo.setUserName(user.getName());
                msgEventInfo.setIsHandle(0);
                msgEventInfo.setSendResult(0);
                msgEventInfo.setSendTime(LocalDateTime.now());
                msgEventInfo.setEventIndex(eventId);
                resultList.add(msgEventInfo);
            }

        }

        List<SmsResponseDTO.SmsItem> result = smsUtils.sendSmSToUser(msgDTOList);
        Map<String, SmsResponseDTO.SmsItem> stringSmsItemMap = result.stream().collect(Collectors.toMap(SmsResponseDTO.SmsItem::getCustomMsgID, Function.identity()));

        resultList.forEach(item -> {
            if (stringSmsItemMap.containsKey(item.getMsgIndex())) {
                SmsResponseDTO.SmsItem smsItem = stringSmsItemMap.get(item.getMsgIndex());
                item.setSendResult(Objects.equals(smsItem.getCode(), "0") ? 1 : 0);
                item.setIsHandle(1);

            }
        });
        msgEventInfoService.saveBatch(resultList);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, resultList, methodDescribe);
    }



    private void sendMessage(JSONObject jsonObject, String objStr) {
        try {
            if (!"/".equals(objStr)) {
                log.info("-------------------------开始执行短信发送逻辑{}", System.currentTimeMillis());
                TimeInterval timeInterval = new TimeInterval();
                Integer lineId = Integer.valueOf(jsonObject.get("lineid").toString());
                List<PqsDeptsline> pqLineDept = pqsDeptslineService.lambdaQuery().eq(PqsDeptsline::getLineIndex, lineId).eq(PqsDeptsline::getSystype, sysTypeZt).list();
                Set<String> deptIds = pqLineDept.stream().map(PqsDeptsline::getDeptsIndex).collect(Collectors.toSet());
                Set<String> resultIds = getAllParentDeptIds(deptIds);

                List<PqsUserSet> pqsUserSetList = pqsUsersetService.lambdaQuery().eq(PqsUserSet::getIsNotice, 1).in(PqsUserSet::getDeptsIndex, resultIds).list();
                if (CollUtil.isEmpty(pqsUserSetList)) {
                    //当前事件未找到用户信息，判断为不需要发送短信用户
                    return;
                }
                List<PqsUser> pqsUserList = pqsUserService.lambdaQuery().select(PqsUser::getUserIndex, PqsUser::getPhone, PqsUser::getName).in(PqsUser::getUserIndex, pqsUserSetList.stream().map(PqsUserSet::getUserIndex).collect(Collectors.toList())).list();
                List<String> userIds = pqsUserList.stream().map(PqsUser::getUserIndex).collect(Collectors.toList());
                List<PqsUserSet> poList = pqsUserSetList.stream().filter(it -> userIds.contains(it.getUserIndex())).collect(Collectors.toList());

                if (CollUtil.isNotEmpty(poList)) {
                    StringBuilder stringBuilder = new StringBuilder(jsonObject.get("timeid").toString());
                    String busName = jsonObject.containsKey("busname")? "_"+jsonObject.get("busname").toString():"";
                    BigDecimal bigDecimal = new BigDecimal(jsonObject.get("eventvalue").toString()).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                    stringBuilder.append(".").append(jsonObject.get("ms").toString()).append(",").append(jsonObject.get("bdname").toString()).append(busName)
//                            .append("_").append(jsonObject.get("pointname").toString())
                            .append("发生电压暂降事件,事件残余电压").append(bigDecimal).append("%,持续时间:").append(String.format("%.3f", Double.parseDouble(jsonObject.get("persisttime").toString()))).append("S;");
                    stringBuilder.append(objStr);

                    String message;
                    if (stringBuilder.length() > 500) {
                        message = stringBuilder.substring(0, 490).concat(";详情请登录电压暂降监测平台查看。");
                    } else {
                        message = stringBuilder.toString();
                    }

                    List<MsgEventInfo> resultList = new ArrayList<>();
                    List<SmsSendDTO.ItemInner> msgDTOList = new ArrayList<>();
                    for (PqsUser user : pqsUserList) {
                        String msgId = IdUtil.simpleUUID();

                        SmsSendDTO.ItemInner dto = new SmsSendDTO.ItemInner();
                        dto.setContent(message);
                        dto.setTo(user.getPhone());
                        dto.setCustomMsgID(msgId);
                        msgDTOList.add(dto);

                        MsgEventInfo msgEventInfo = new MsgEventInfo();
                        msgEventInfo.setMsgIndex(msgId);
                        msgEventInfo.setMsgContent(message);
                        msgEventInfo.setPhone(user.getPhone());
                        msgEventInfo.setUserId(user.getUserIndex());
                        msgEventInfo.setUserName(user.getName());
                        msgEventInfo.setIsHandle(0);
                        msgEventInfo.setSendResult(0);
                        msgEventInfo.setSendTime(LocalDateTime.now());
                        msgEventInfo.setEventIndex(jsonObject.get("eventdetail_index").toString());
                        resultList.add(msgEventInfo);
                    }

                    List<SmsResponseDTO.SmsItem> result = smsUtils.sendSmSToUser(msgDTOList);
                    Map<String, SmsResponseDTO.SmsItem> stringSmsItemMap = result.stream().collect(Collectors.toMap(SmsResponseDTO.SmsItem::getCustomMsgID, Function.identity()));

                    resultList.forEach(item -> {
                        if (stringSmsItemMap.containsKey(item.getMsgIndex())) {
                            SmsResponseDTO.SmsItem smsItem = stringSmsItemMap.get(item.getMsgIndex());
                            item.setSendResult(Objects.equals(smsItem.getCode(), "0") ? 1 : 0);
                        }
                    });
                    msgEventInfoService.saveBatch(resultList);
                }
                log.info("{}-------------短信发送执行结束，执行时长{}s", System.currentTimeMillis(), timeInterval.intervalSecond());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("---------短信发送异常，异常信息", e);
        }
    }

    /**
     * 获取远程短信平台token
     */
    private String apiToken() {

        return "token";
    }

    private boolean apiSend() {


        return false;
    }


    public Set<String> getAllParentDeptIds(Set<String> deptIds) {
        // 首次获取直接父级
        List<PqsDepts> allDeptList = pqsDeptsService.lambdaQuery().list();
        // 递归获取所有父级
        Set<String> result = recursivelyGetParentIds(deptIds, allDeptList);
        return result;
    }

    /**
     * 递归获取所有父级ID
     *
     * @param currentParentIds 当前层级的父级ID集合
     * @return 所有层级的父级ID集合
     */
    private Set<String> recursivelyGetParentIds(Set<String> currentParentIds, List<PqsDepts> allDeptList) {
        Set<String> result = new HashSet<>(currentParentIds);
        Set<String> nextLevelParentIds = new HashSet<>();
        List<PqsDepts> parentDeptList = allDeptList.stream().filter(it -> currentParentIds.contains(it.getDeptsIndex())).collect(Collectors.toList());
        for (PqsDepts pqsDepts : parentDeptList) {
            if (!pqsDepts.getParentnodeid().equals("0")) {
                nextLevelParentIds.add(pqsDepts.getParentnodeid());
            }
        }
        // 如果有更高层级的父级，继续递归
        if (!nextLevelParentIds.isEmpty()) {
            Set<String> deeperParentIds = recursivelyGetParentIds(nextLevelParentIds, allDeptList);
            result.addAll(deeperParentIds);
        }
        return result;
    }
    @GetMapping("/refreshIdCache")
    @ApiOperation("刷新缓存")
    public Boolean refreshIdCache() {
        pqlineCache.init();
        return true;// HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, "数据同步");
    }

}
