package com.bootdo.datasend.dianxin.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bootdo.datasend.dianxin.cache.DeviceCache;
import com.bootdo.datasend.dianxin.domain.*;
import com.bootdo.datasend.dianxin.domain.dto.*;
import com.bootdo.datasend.dianxin.service.*;
import com.bootdo.util.Base64Util;
import com.bootdo.util.StringKit;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class StandardTask {
    private static final Logger logger = LoggerFactory.getLogger(StandardTask.class);

    private final RabbitTemplate rabbitTemplate;
    private final BaseHighThrowRecordService highThrowRecordService;
    private final BaseElectricCarRecordService electricCarRecordService;
    private final BaseUserRecordService userRecordService;
    private final BaseVehicleRecordService vehicleRecordService;
    private final BaseDoorRecordService doorRecordService;
    private final DeviceInfoRecordService deviceRecordService;
    private final DeviceOrderInfoService deviceOrderInfoService;

    private final DevicePowerInfoService devicePowerInfoService;

    private final RestTemplate restTemplate;

    /**
     * 功能描述: 高抛发送
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendHighThrow() {

        //获取高抛记录
        List<BaseHighThrowRecord> highThrowRecords = highThrowRecordService.list(new QueryWrapper<BaseHighThrowRecord>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (BaseHighThrowRecord h : highThrowRecords) {

            String deviceId = h.getDeviceIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }

            HighThrowDto dto = new HighThrowDto();

            RequestDataDTO dataDTO = new RequestDataDTO();
            dataDTO.setRequestFlag("1");

            RequestDataListDTO requestDataListDTO = new RequestDataListDTO();
            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setWarnType("1001");
            requestDataListDTO.setDeviceType("302");
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            requestDataListDTO.setEventName("高抛报警");
            requestDataListDTO.setWarnTime(StringKit.toString(h.getPassTime()));
            requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getHighThrowImgurl()));
            List<RequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);

            //循环发送mq
            boolean b = sendHighThrowMq(dto);
            if (b) {
                h.setIsSend(1);
                highThrowRecordService.saveOrUpdate(h);
                logger.info("高抛记录发送成功：" + h.getId());
            }
        }
    }

    /**
     * 功能描述: 发送电瓶车预警
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendElectricCar() {

        //获取高抛记录
        List<BaseElectricCarRecord> lists = electricCarRecordService.list(new QueryWrapper<BaseElectricCarRecord>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (BaseElectricCarRecord h : lists) {

            String deviceId = h.getDeviceIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }

            ElectricCarDto dto = new ElectricCarDto();

            RequestDataDTO dataDTO = new RequestDataDTO();
            dataDTO.setRequestFlag("1");

            RequestDataListDTO requestDataListDTO = new RequestDataListDTO();
            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setWarnType("1002");
            requestDataListDTO.setDeviceType("302");
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            requestDataListDTO.setEventName("电动车入侵");
            requestDataListDTO.setWarnTime(StringKit.toString(h.getPassTime()));
            requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getHighThrowImgurl()));
            List<RequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);

            //循环发送mq
            boolean b = sendElectricCarMq(dto);
            if (b) {
                h.setIsSend(1);
                electricCarRecordService.saveOrUpdate(h);
                logger.info("电动车入侵记录发送成功：" + h.getId());
            }
        }
    }

    /**
     * 功能描述: 发送人脸记录
     */
//    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendUserRecord() {

        List<BaseUserRecord> lists = userRecordService.list(new QueryWrapper<BaseUserRecord>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (BaseUserRecord h : lists) {

            String deviceId = h.getDeviceIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }

            UserRecordDto dto = new UserRecordDto();

            UserRequestDataDTO dataDTO = new UserRequestDataDTO();
            dataDTO.setRequestFlag("1");

            UserRequestDataListDTO requestDataListDTO = new UserRequestDataListDTO();


            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setPassTime(StringKit.toString(h.getPassTime()));
            requestDataListDTO.setPersonPicBase64(Base64Util.getBase64ByUrl(h.getPersonPic()));
            requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getGlobalPic()));
            requestDataListDTO.setPassDirection(StringKit.toString(deviceInfo.getDirection()));
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            List<UserRequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
            String requestBody = JSON.toJSONString(dto);

            // 比如队列名称是 instruction||{gatewaySN} ，需替换成实际的 gatewaySN 值
            String gatewaySN = deviceInfo != null ? deviceInfo.getGeminiSn() : "";
            String queueName = "instruction||" + gatewaySN;
            String url = "http://cyy.csxdtx.com:10010/api/zdyq-equipment/dwBoxRecord/accept";

            try {
                // 发送 POST 请求，这里假设接口返回类型为 String ，可根据实际调整
//                消息队列发送
//                rabbitTemplate.convertAndSend(queueName, JSON.toJSONString(dto));
//                调接口
                String result = restTemplate.postForObject(url, requestBody, String.class);
                logger.info("调用接口返回结果：{}", result);

                // 若返回码符合成功逻辑（需看接口文档定义），更新发送状态
                h.setIsSend(1);
                userRecordService.saveOrUpdate(h);
                logger.info("人脸抓拍记录发送成功：" + h.getId());
            } catch (Exception e) {
                logger.error("调用接口发送数据失败，记录 ID：{}，异常：{}", h.getId(), e.getMessage());
            }
            //循环发送mq
            boolean b = sendUserMq(dto);
            if (b) {
                h.setIsSend(1);
                userRecordService.saveOrUpdate(h);
                logger.info("人脸抓拍记录发送成功：" + h.getId());
            }
        }
    }

    /**
     * 功能描述: 发送车辆记录
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendVehicleRecord() {

        List<BaseVehicleRecord> lists = vehicleRecordService.list(new QueryWrapper<BaseVehicleRecord>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (BaseVehicleRecord h : lists) {


            String deviceId = h.getDeviceIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            String passDirection = "";
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }


            VehicleRecordDto dto = new VehicleRecordDto();

            VehicleRequestDataDTO dataDTO = new VehicleRequestDataDTO();
            dataDTO.setRequestFlag("1");

            VehicleRequestDataListDTO requestDataListDTO = new VehicleRequestDataListDTO();
            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setPassTime(StringKit.toString(h.getPassTime()));
            if (h.getPlatePic()!=null){
                requestDataListDTO.setPlatePicBase64(Base64Util.getBase64ByUrl(h.getPlatePic()));
            }
            if (h.getGlobalPic()!=null){
                requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getGlobalPic()));
            }
            requestDataListDTO.setPlateNo(h.getPlateNo());
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            requestDataListDTO.setGlobalPic(h.getGlobalPic());
            requestDataListDTO.setUserName(h.getOwnerName());
            requestDataListDTO.setPassDirection(StringKit.toString(deviceInfo.getDirection()));
            List<VehicleRequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
//            String requestBody = JSON.toJSONString(dto);
            String requestBody = JSON.toJSONString(dto, SerializerFeature.BrowserCompatible);
            // 比如队列名称是 instruction||{gatewaySN} ，需替换成实际的 gatewaySN 值
            String gatewaySN = deviceInfo != null ? deviceInfo.getGeminiSn() : "";
            String queueName = "instruction||" + gatewaySN;
            String url = "https://cyy.csxdtx.com:10010/api/zdyq-equipment/dwBoxRecord/acceptDwCarRecord";

            try {
                // 发送 POST 请求，这里假设接口返回类型为 String ，可根据实际调整
//                消息队列发送
//                rabbitTemplate.convertAndSend(queueName, JSON.toJSONString(dto));
//                调接口
                String result = restTemplate.postForObject(url, requestBody, String.class);
                logger.info("调用接口返回结果：{}", result);

                // 若返回码符合成功逻辑（需看接口文档定义），更新发送状态
                h.setIsSend(1);
                vehicleRecordService.saveOrUpdate(h);
                logger.info("车辆记录发送成功：" + h.getId());
            } catch (Exception e) {
                logger.error("调用接口发送数据失败，记录 ID：{}，异常：{}", h.getId(), e.getMessage());
            }

        }
    }


    /**
     * 人脸门禁
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void doorRecord() {

        List<BaseDoorRecord> lists = doorRecordService.list(new QueryWrapper<BaseDoorRecord>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (BaseDoorRecord h : lists) {


            String deviceId = h.getCameraIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            String passDirection = "";
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }


            DoorRecordDTO dto = new DoorRecordDTO();

            DoorRequestDataDTO dataDTO = new DoorRequestDataDTO();
            dataDTO.setRequestFlag("1");

            DoorRequestDataListDTO requestDataListDTO = new DoorRequestDataListDTO();
            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            requestDataListDTO.setValidType(Integer.valueOf(h.getDirection()));
            requestDataListDTO.setPassTime(StringKit.toString(h.getPassTime()));
            if (h.getPersonPic()!=null){
                requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getPersonPic()));
            }
            requestDataListDTO.setPersonPic(h.getPersonPic());
            requestDataListDTO.setGlobalPic(h.getPersonPic());
            requestDataListDTO.setCardNo(h.getCardno());
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            if (h.getOpenResult().contains("成功")){
                requestDataListDTO.setValidResult((short) 1);
            }else {
                requestDataListDTO.setValidResult((short) 0);
            }
            requestDataListDTO.setUserName(h.getUserName());
            requestDataListDTO.setPassDirection(h.getDirection());
            List<DoorRequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
//            String requestBody = JSON.toJSONString(dto);
            String requestBody = JSON.toJSONString(dto, SerializerFeature.BrowserCompatible);
            // 比如队列名称是 instruction||{gatewaySN} ，需替换成实际的 gatewaySN 值
            String gatewaySN = deviceInfo != null ? deviceInfo.getGeminiSn() : "";
            String queueName = "instruction||" + gatewaySN;
            String url = "https://cyy.csxdtx.com:10010/api/zdyq-equipment/dwBoxRecord/acceptDwUserRecord";

            try {
                // 发送 POST 请求，这里假设接口返回类型为 String ，可根据实际调整
//                消息队列发送
//                rabbitTemplate.convertAndSend(queueName, JSON.toJSONString(dto));
//                调接口
                String result = restTemplate.postForObject(url, requestBody, String.class);
                logger.info("调用接口返回结果：{}", result);

                // 若返回码符合成功逻辑（需看接口文档定义），更新发送状态
                h.setIsSend(1);
                doorRecordService.saveOrUpdate(h);
                logger.info("人脸抓拍记录发送成功：" + h.getId());
            } catch (Exception e) {
                logger.error("调用接口发送数据失败，记录 ID：{}，异常：{}", h.getId(), e.getMessage());
            }

        }
    }


//    @Scheduled(cron = "0/5 * * * * ? ")
//    public void sendDoorRecord() {
//
//        List<BaseDoorRecord> lists = doorRecordService.list(new QueryWrapper<BaseDoorRecord>()
//                .eq("is_send", "0")
//                .last("limit 100")
//        );
//
//        for (BaseDoorRecord h : lists) {
//
//            String deviceId = h.getCameraIp();
//            String deviceCacheStr = DeviceCache.get(deviceId);
//            DevopsDeviceInfo deviceInfo = null;
//            if ("".equals(StringKit.toString(deviceCacheStr))) {
//                logger.info("当前设备缓存中不存在:" + deviceId);
//            } else {
//                logger.info("当前设备获取到缓存:" + deviceId);
//                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
//            }
//
//            UserRecordDto dto = new UserRecordDto();
//
//            UserRequestDataDTO dataDTO = new UserRequestDataDTO();
//            dataDTO.setRequestFlag("1");
//
//            UserRequestDataListDTO requestDataListDTO = new UserRequestDataListDTO();
//
//            if (deviceInfo != null) {
//                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
//            }
//            requestDataListDTO.setPassTime(StringKit.toString(h.getPassTime()));
//            requestDataListDTO.setPersonPicBase64(Base64Util.getBase64ByUrl(h.getPersonPic()));
//            requestDataListDTO.setPassDirection(StringKit.toString(deviceInfo.getDirection()));
//
//            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
//            //门禁验证方式
//            requestDataListDTO.setValidType(h.getGbsChannelNo());
//            requestDataListDTO.setCardNo(h.getCardno());
//
//            List<UserRequestDataListDTO> list = new ArrayList<>();
//            list.add(requestDataListDTO);
//            dataDTO.setRequestDataList(list);
//            dto.setRequestData(dataDTO);
//
//            //循环发送mq
//            boolean b = sendUserMq(dto);
//            if (b) {
//                h.setIsSend(1);
//                doorRecordService.saveOrUpdate(h);
//                logger.info("门禁抓拍记录发送成功：" + h.getId());
//            }
//        }
//    }



    public boolean sendHighThrowMq(HighThrowDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.warnrecord", JSON.toJSONString(bean));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean sendElectricCarMq(ElectricCarDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.warnrecord", JSON.toJSONString(bean));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean sendUserMq(UserRecordDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.userrecord", JSON.toJSONString(bean));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean sendVehicleMq(VehicleRecordDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.vehiclerecord", JSON.toJSONString(bean));
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 电表设备信息
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void DeviceInfoRecord() {

        List<DeviceInfoRecord> lists = deviceRecordService.list(new QueryWrapper<DeviceInfoRecord>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (DeviceInfoRecord h : lists) {
            DeviceInfoDTO dto = new DeviceInfoDTO();

            DeviceInfoDataDTO dataDTO = new DeviceInfoDataDTO();
            dataDTO.setRequestFlag("single");
            DeviceInfoDataListDTO dataListDTO = new DeviceInfoDataListDTO();
            dataListDTO.setGatewaySN(h.getGatewaySN());
            dataListDTO.setDeviceType(h.getDeviceType());
            dataListDTO.setDeviceSN(h.getDeviceSN());
            dataListDTO.setHeartbeatTime(h.getHeartbeatTime());
            if (h.getIsOnline() == null){
                dataListDTO.setIsOnline(0);
            }else {
                dataListDTO.setIsOnline(h.getIsOnline());
            }
            dataListDTO.setIsOpenAccount(h.getIsOpenAccount());
            dataListDTO.setIsOweMoney(h.getIsOweMoney());
            dataListDTO.setTotalMoney(h.getTotalMoney());
            dataListDTO.setBuyTimes(h.getBuyTimes());
            dataListDTO.setBalance(h.getBalance());
            dataListDTO.setRoomNo(h.getRoomNo());
            dataListDTO.setProjectName(h.getProjectName());
            List<DeviceInfoDataListDTO> list = new ArrayList<>();
            list.add(dataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
            String requestBody = JSON.toJSONString(dto, SerializerFeature.BrowserCompatible);

            String url = "https://cyy.csxdtx.com:10010/api/zdyq-equipment/dwBoxRecord/acceptDwDeviceInfo";

            try {
                // 发送 POST 请求，这里假设接口返回类型为 String ，可根据实际调整
//                消息队列发送
//                rabbitTemplate.convertAndSend(queueName, JSON.toJSONString(dto));
//                调接口
                String result = restTemplate.postForObject(url, requestBody, String.class);
                logger.info("调用接口返回结果：{}", result);

                // 若返回码符合成功逻辑（需看接口文档定义），更新发送状态
                h.setIsSend(1);
                deviceRecordService.saveOrUpdate(h);
                logger.info("电表数据发送成功：" + h.getId());
            } catch (Exception e) {
                logger.error("调用接口发送数据失败，记录 ID：{}，异常：{}", h.getId(), e.getMessage());
            }

        }
    }


    /**
     * 推送设备订单信息
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void DeviceOrderInfoRecord() {

        List<DeviceOrderInfo> lists = deviceOrderInfoService.list(new QueryWrapper<DeviceOrderInfo>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (DeviceOrderInfo h : lists) {
            DeviceOrderInfoDTO dto = new DeviceOrderInfoDTO();
            DeviceOrderInfoDataDTO dataDTO = new DeviceOrderInfoDataDTO();
            dataDTO.setRequestFlag("single");
            DeviceOrderInfoDataListDTO dataListDTO = new DeviceOrderInfoDataListDTO();
            dataListDTO.setDeviceSN(h.getDeviceSN());
            dataListDTO.setSaleType(h.getSaleType());
            dataListDTO.setBuyTypeName(h.getBuyTypeName());
            dataListDTO.setMoney(h.getMoney());
            dataListDTO.setSaleDate(h.getSaleDate());
            dataListDTO.setOwnerName(h.getOwnerName());
            dataListDTO.setRoomNo(h.getRoomNo());
            List<DeviceOrderInfoDataListDTO> list = new ArrayList<>();
            list.add(dataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
            String requestBody = JSON.toJSONString(dto, SerializerFeature.BrowserCompatible);

            String url = "https://cyy.csxdtx.com:10010/api/zdyq-equipment/dwBoxRecord/acceptDwDeviceOrder";

            try {
                // 发送 POST 请求，这里假设接口返回类型为 String ，可根据实际调整
//                消息队列发送
//                rabbitTemplate.convertAndSend(queueName, JSON.toJSONString(dto));
//                调接口
                String result = restTemplate.postForObject(url, requestBody, String.class);
                logger.info("调用接口返回结果：{}", result);

                // 若返回码符合成功逻辑（需看接口文档定义），更新发送状态
                h.setIsSend(1);
                deviceOrderInfoService.saveOrUpdate(h);
                logger.info("电表设备订单信息发送成功：" + h.getId());
            } catch (Exception e) {
                logger.error("调用接口发送数据失败，记录 ID：{}，异常：{}", h.getId(), e.getMessage());
            }

        }
    }




    /**
     * 推送电表设备用电信息
     */
//    @Scheduled(cron = "0/5 * * * * ? ")
    @Scheduled(cron = "0 30 2 * * ?")
    public void DevicePowerInfoRecord() {

        List<DevicePowerInfo> lists = devicePowerInfoService.list(new QueryWrapper<DevicePowerInfo>()
                .eq("is_send", "0")
                .last("limit 100")
        );

        for (DevicePowerInfo h : lists) {
            DevicePowerInfoDTO dto = new DevicePowerInfoDTO();
            DevicePowerInfoDataDTO dataDTO = new DevicePowerInfoDataDTO();
            dataDTO.setRequestFlag("single");
            DevicePowerInfoDataListDTO dataListDTO = new DevicePowerInfoDataListDTO();
            dataListDTO.setDeviceSN(h.getDeviceSN());

            dataListDTO.setPowerEnd(h.getPowerEnd());
            dataListDTO.setPowerStart(h.getPowerStart());
            dataListDTO.setPowerUse(h.getPowerUse());
            dataListDTO.setRoomNo(h.getRoomNo());
            dataListDTO.setUseDate(h.getUseDate());
            dataListDTO.setUserName(h.getUserName());
            List<DevicePowerInfoDataListDTO> list = new ArrayList<>();
            list.add(dataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
            String requestBody = JSON.toJSONString(dto, SerializerFeature.BrowserCompatible);

            String url = "https://cyy.csxdtx.com:10010/api/zdyq-equipment/dwBoxRecord/acceptDwDeviceUsage";

            try {
                // 发送 POST 请求，这里假设接口返回类型为 String ，可根据实际调整
//                消息队列发送
//                rabbitTemplate.convertAndSend(queueName, JSON.toJSONString(dto));
//                调接口
                String result = restTemplate.postForObject(url, requestBody, String.class);
                logger.info("调用接口返回结果：{}", result);

                // 若返回码符合成功逻辑（需看接口文档定义），更新发送状态
                h.setIsSend(1);
                devicePowerInfoService.saveOrUpdate(h);
                logger.info("电表设备用电信息发送成功：" + h.getId());
            } catch (Exception e) {
                logger.error("调用接口发送数据失败，记录 ID：{}，异常：{}", h.getId(), e.getMessage());
            }

        }
    }
}
