package com.njcn.device.pq.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.njcn.dataProcess.api.PqsCommunicateFeignClient;
import com.njcn.dataProcess.pojo.dto.PqsCommunicateDto;
import com.njcn.device.device.service.DeviceProcessService;
import com.njcn.device.device.service.IDeviceService;
import com.njcn.device.node.mapper.NodeMapper;
import com.njcn.device.pq.pojo.po.Device;
import com.njcn.device.pq.pojo.po.DeviceProcess;
import com.njcn.device.pq.pojo.po.Node;
import com.njcn.message.constant.RedisKeyPrefix;
import com.njcn.redis.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2025/07/31  下午 4:23【需求编号】
 *定时根据前置心跳设置设备状态
 * @author clam
 * @version V1.0.0
 */
@Component
@EnableScheduling
@RequiredArgsConstructor
@ConditionalOnProperty(name = "business.task-enabled", havingValue = "true", matchIfMissing = true)
public class DeviceComflagTasks {
    private  final NodeMapper nodeMapper;
    private final IDeviceService iDeviceService;
    private final DeviceProcessService deviceProcessService;
    private final PqsCommunicateFeignClient pqsCommunicateFeignClient;
    private  final RedisUtil redisUtil;
    private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());

    @Scheduled(fixedRate = 1000*60*3) // 每3钟执行一次
    public void updateDeviceComflag() {
        List<Node> nodeList = nodeMapper.selectList(null);
        for (Node node : nodeList) {
            for (int i = 1; i <= node.getMaxProcessNum(); i++) {

                //h获取redis里心跳如果收不到心跳

                String heartByKey = redisUtil.getStringByKey(node.getId().concat(":").concat(i + ""));
                if(StringUtils.isBlank(heartByKey)){
                    List<Device> list = iDeviceService.lambdaQuery().eq(Device::getNodeId, node.getId()).list();
                    if(!CollectionUtils.isEmpty(list)){
                        List<String> collect = list.stream().map(Device::getId).collect(Collectors.toList());
                        List<DeviceProcess> deviceProcess = deviceProcessService.lambdaQuery().in(DeviceProcess::getId, collect).eq(DeviceProcess::getProcessNo, i).list();

                        List<String> collect2 = deviceProcess.stream().map(DeviceProcess::getId).collect(Collectors.toList());
                        if(!CollectionUtils.isEmpty(list)){
                            collect2.forEach(temp->{
                                PqsCommunicateDto pqsCommunicateDto = new PqsCommunicateDto();
                                pqsCommunicateDto.setTime(LocalDateTimeUtil.now().format(DatePattern.NORM_DATETIME_FORMATTER));
                                pqsCommunicateDto.setDevId(temp);
                                pqsCommunicateDto.setType(0);
                                //获取之前设备状态
                                String devFalg =redisUtil.getStringByKey(RedisKeyPrefix.DEVICE_RUN_FLAG.concat(temp));

                                if(StringUtils.isBlank(devFalg)||(!Objects.equals(Integer.valueOf(devFalg),pqsCommunicateDto.getType()))){
                                    //状态翻转
                                    redisUtil.saveByKey(RedisKeyPrefix.DEVICE_RUN_FLAG.concat(temp),pqsCommunicateDto.getType()+"");
                                    pqsCommunicateFeignClient.insertion(pqsCommunicateDto) ;


                                }

                            });

                        }

                    }
                }
            }
        }

    }
}
