package org.jk.job.snailjob;

import cn.dev33.satoken.stp.StpUtil;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.model.dto.ExecuteResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jk.common.core.constant.CacheConstants;
import org.jk.common.core.domain.dto.UserOnlineDTO;
import org.jk.common.core.utils.StringUtils;
import org.jk.common.json.utils.JsonUtils;
import org.jk.common.redis.utils.RedisUtils;
import org.jk.job.entity.BillDto;
import org.jk.rag.domain.bo.SysUserOnlineLogBo;
import org.jk.rag.service.IJkRagService;
import org.jk.rag.service.ISysUserOnlineLogService;
import org.jk.rag.utils.MonthTimeUtils;
import org.jk.system.domain.vo.SysTenantVo;
import org.jk.system.service.ISysLogininforService;
import org.jk.system.service.ISysTenantService;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * DAG工作流任务-模拟支付宝账单任务
 * <a href="https://juejin.cn/post/7487860254114644019"></a>
 *
 * @author 老马
 */
@Slf4j
@Component
@RequiredArgsConstructor
@JobExecutor(name = "onlineUserTask")
public class OnlineUserTask {

    private final ISysUserOnlineLogService service;

    private final ISysLogininforService sysLogininforService;

    public ExecuteResult jobExecute(JobArgs jobArgs) throws InterruptedException {
        // 1. 核心业务逻辑（替换为你的实际代码）
        log.info("===== 每天统计登录人数任务开始执行 =====");
        log.info("当前时间：{}", LocalDateTime.now());
        // 示例：执行业务操作（如数据同步、报表生成、接口调用等）
        int count = doBusinessLogic();
        log.info("===== 每天统计登录人数任务执行完成 =====\n");
        return ExecuteResult.success("执行成功 插入在线人数："+count +"人");
    }

    private int doBusinessLogic() {

        // 1. 获取当前日期 → 减1天得到前一天日期
        Date yesterdayStartDate = MonthTimeUtils.getYesterdayStartAsDate();
        Date yesterdayEndDate = MonthTimeUtils.getYesterdayEndAsDate();
        Integer loginCount = sysLogininforService.queryCountByTime(yesterdayStartDate,yesterdayEndDate);
//        String onlineTokenKey = "*:"+ CacheConstants.ONLINE_TOKEN_KEY;
//        log.info("【定时任务】ONLINE_TOKEN_KEY = {}", onlineTokenKey);
//        String queryPattern = onlineTokenKey + "*";
//        log.info("【定时任务】查询 Redis Key 前缀 = {}", queryPattern);
//        Collection<String> keys = RedisUtils.keys(queryPattern);
//        log.info("【定时任务】RedisUtils 查询 Key 结果：{}，数量：{}", keys, keys == null ? 0 : keys.size());
//        List<UserOnlineDTO> userOnlineDTOList = new ArrayList<>();
//        for (String key : keys) {
//            String token = StringUtils.substringAfterLast(key, ":");
//            // 如果已经过期则跳过
//            if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
//                continue;
//            }
//            userOnlineDTOList.add(RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token));
//        }
        SysUserOnlineLogBo bo = new SysUserOnlineLogBo();
        bo.setOnlineNum(String.valueOf(loginCount));
        bo.setCreateTime(yesterdayStartDate);
        service.insertByBo(bo);
        log.info("插入在线人数..."+loginCount);
        return loginCount;
    }

}
