package com.fs.qw.config;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.redis.RedisCache;
import com.fs.qw.domain.QwContactReturn;
import com.fs.qw.domain.QwInnerContactReturn;
import com.fs.qw.domain.QwOnline;
import com.fs.qw.domain.QwUser;
import com.fs.qw.service.IQwLoginService;
import com.fs.qw.service.IQwUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.fs.qw.utils.QwAllUtil.contactList;
import static com.fs.qw.utils.QwAllUtil.innerContactList;
import static com.fs.qw.utils.QwUtil.toJson;

@Component
public class QwSeqUpdate {

    private final RedisCache redisCache;
    private final IQwLoginService qwLoginService;
    private final IQwUserService qwUserService;

    public QwSeqUpdate(RedisCache redisCache, IQwLoginService qwLoginService, IQwUserService qwUserService) {
        this.redisCache = redisCache;
        this.qwLoginService = qwLoginService;
        this.qwUserService = qwUserService;
    }

    Logger logger= LoggerFactory.getLogger(getClass());

//    @Scheduled(cron = "0 0 0 * * ?")
// 在每天的午夜执行任务
    @Scheduled(cron = "0 */5 * * * ?")
    public void updateQwSeq() {
        //在redis取全部的qw_seq的key
        Set<String> keys = redisCache.getKeysWithPrefix("qw_seq:");
        for (String key : keys) {
            //获取key的数据
            QwUser qwUser = JSONObject.parseObject(redisCache.getCacheObject(key), QwUser.class);
            QwOnline qwOnline = qwLoginService.getCheck(qwUser.getDeviceId());
            //判断账号是否在线
            if (qwOnline.getOnline()) {
                //在线时获取最新的seq
                QwContactReturn qwContactReturn = contactList(qwUser.getSeq(), qwUser.getDeviceId());
                QwInnerContactReturn innerContactReturn = innerContactList(qwUser.getInnerSeq(), qwUser.getDeviceId());
                qwUser.setSeq(qwContactReturn.getSeq());
                qwUser.setInnerSeq(innerContactReturn.getSeq());
                //更新user表
                qwUserService.updateQwUser(qwUser);
                //更新redis
                redisCache.setCacheObject("qw_seq:" + qwUser.getDeviceId(), toJson(qwUser), 15, TimeUnit.DAYS);
                logger.info("更新seq成功：{}" ,qwUser);
            }
        }
    }
}
