package com.fdkankan.download.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.constant.RedisLockKey;
import com.fdkankan.redis.util.RedisLockUtil;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.common.bean.DownLoadTaskBean;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 应用启动校验是否有下载任务正在进行，如有过就重新入队头，从新下载
 * </p>
 *
 * @author dengsixing
 * @since 2022/2/22
 **/
@Component
public class CheckProgressRunnerImpl implements CommandLineRunner {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisLockUtil redisLockUtil;

    @Override
    public void run(String... args) throws Exception {

        //这里考虑到如果是集群部署，可能多个节点启动时，只需要一个节点进来就行了，所以加一个分布式锁
        String lockKey = String.format(RedisLockKey.LOCK_SCENE_DOWNLOAD_ING);
        boolean lock = redisLockUtil.lock(lockKey, RedisKey.EXPIRE_TIME_1_MINUTE);
        if(!lock){
            return;
        }
        try {
            //查询还没下载完毕的场景
            List<String> downLoadList = redisUtil.lGet(RedisKey.SCENE_DOWNLOAD_ING, 0, -1);
            if(CollUtil.isEmpty(downLoadList)){
                return;
            }
            //删除还没执行完毕的场景缓存
            redisUtil.del(RedisKey.SCENE_DOWNLOAD_ING);

            List<String> taskList = downLoadList.stream().map(num -> {
                return JSON.toJSONString(DownLoadTaskBean.builder().num(num).type("local").build());
            }).collect(Collectors.toList());

            //从新入队
            redisUtil.lLeftPushAll(RedisKey.SCENE_DOWNLOADS_TASK_V4, taskList);

        }finally {
            redisLockUtil.unlockLua(lockKey);
        }
    }
}
