package com.yfd.platform.component.nettyserver;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yfd.platform.component.WebSocketServer;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;

/**
 * 心跳保持器
 */
@Component
public class NettyHeartTimer {

    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

//    @Scheduled(fixedRate = 10000)
    public void timeTask() {

        LocalDateTime startTime = Constant.now;
        LocalDateTime endTime = LocalDateTime.now();
        // 指定时区（这里以系统默认时区为例）
        ZoneId zoneId = ZoneId.systemDefault();

        // 将LocalDateTime转换为ZonedDateTime
        ZonedDateTime startZoned = startTime.atZone(zoneId);
        ZonedDateTime endZoned = endTime.atZone(zoneId);

        // 计算两个ZonedDateTime之间的差异
        Duration duration = Duration.between(startZoned, endZoned);

        // 获取差异的总秒数
        long secondsBetween = duration.getSeconds();

        if (secondsBetween > 60) {
            // 在这里你可以进行清理工作，比如关闭资源
            LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
            String robotIp = "192.168.1.106";
            queryWrapper.eq(SubstationPatroldevice::getIpaddr, robotIp);
            List<SubstationPatroldevice> list = substationPatroldeviceService.list(queryWrapper);
            if (list.size() > 0) {
                SubstationPatroldevice substationPatroldevice = list.get(0);
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                jsonObject.putOpt("patroldevice_name", substationPatroldevice.getPatroldeviceName());
                jsonObject.putOpt("patroldevice_code", substationPatroldevice.getPatroldeviceCode());
                jsonObject.putOpt("time", DateUtil.now());
                jsonObject.putOpt("type", "301");
                jsonObject.putOpt("value", "1");
                jsonObject.putOpt("unit", "");
                jsonObject.putOpt("value_unit", "异常");
                jsonArray.add(jsonObject);
                WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
            }
        }

    }
}
