package cn.iocoder.yudao.module.system.job.equipment;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.framework.websocket.core.session.WebSocketSessionManager;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.attendancemachine.DeviceStatusUpdateVO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.AttendanceMachineDO;
import cn.iocoder.yudao.module.system.service.equipment.AttendanceMachineService;
import com.github.yulichang.toolkit.SpringContentUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@EnableScheduling
public class AttendanceMachineJob {

    @Resource
    private AttendanceMachineService attendanceMachineService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(initialDelay = 5000, fixedRate = 30000)
    @TenantJob
    public void updateAttendanceMachineStatus() {

        WebSocketSessionManager webSocketSessionManager = SpringContentUtils.getBean(WebSocketSessionManager.class);

        List<DeviceStatusUpdateVO> statusUpdateVOS = new ArrayList<>();

        // 获得所有在线的设备
        List<AttendanceMachineDO> attendanceMachineDOS = attendanceMachineService.getListByStatus();
        for (AttendanceMachineDO reqDO : attendanceMachineDOS) {

            // redis数据不存在，则为离线状态
            String data = stringRedisTemplate.opsForValue().get(reqDO.getDeviceNo() + "_1");
            if (StrUtil.isEmpty(data)) {

                statusUpdateVOS.add(new DeviceStatusUpdateVO(reqDO.getId(),reqDO.getDeviceNo(), 0, null));
                //同步 删除对应sessionId
                if (webSocketSessionManager.getSessionByDeviceNum(reqDO.getDeviceNo()) != null) {
                    webSocketSessionManager.removeSession(webSocketSessionManager.getSessionByDeviceNum(reqDO.getDeviceNo()));
                }
            } else {
                statusUpdateVOS.add(new DeviceStatusUpdateVO(reqDO.getId(),reqDO.getDeviceNo(),
                        1, LocalDateTime.parse(data, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }
        }

        if (!CollectionUtil.isEmpty(statusUpdateVOS)) {

            attendanceMachineService.updateAttendanceMachineStatus(statusUpdateVOS);
        }
    }
}
