package com.fdkankan.download.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fdkankan.common.bean.DownLoadTaskBean;
import com.fdkankan.download.bean.CurrentDownloadNumUtil;
import com.fdkankan.download.service.ISceneDownLoadService;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/2/22
 **/
@RefreshScope
@Service
public class SceneDownLoadServiceImpl implements ISceneDownLoadService {

    @Value("${scene.download.threadMax:3}")
    private Integer downloadThreadMax;

    @Autowired
    RedisUtil redisUtil;

//    @Autowired
//    ExecutorCompletionService completionService;

    @Autowired
    SceneDownloadHandlerServiceImpl handlerService;


    @Override
    public void process() throws Exception {

        //统计本节点正在下载任务数量
        int downloadIngCnt = CurrentDownloadNumUtil.cntDownloadingLocal();
        //如果正在下载的场景大于最大线程数，不往下执行
        if(downloadIngCnt >= downloadThreadMax){
            return;
        }

        for(int i = 0; i < downloadThreadMax - downloadIngCnt; i++){
            DownLoadTaskBean downLoadTaskBean = this.getTaskSceneNum();
            //获取任务队列中队头场景码，如果是空，标识没有场景要下载，则退出程序
            if(Objects.isNull(downLoadTaskBean)){
                continue;
            }
            handlerService.download(downLoadTaskBean);
        }

    }

    private DownLoadTaskBean getTaskSceneNum() throws Exception{
        //redis待下载任务出队
        String downloadTask = redisUtil.lLeftPop(RedisKey.SCENE_DOWNLOADS_TASK_V4);
        if(StrUtil.isEmpty(downloadTask)){
            return null;
        }
        DownLoadTaskBean downLoadTaskBean = JSONUtil.toBean(downloadTask, DownLoadTaskBean.class);
        if(downLoadTaskBean == null || StrUtil.isEmpty(downLoadTaskBean.getNum()) || !"local".equals(downLoadTaskBean.getType())){
            throw new Exception("下载任务数据不正确,downloadTask:" +  downloadTask);
        }
        //如果场景正在下载中，就直接丢弃
        String num = downLoadTaskBean.getNum();
        if(CurrentDownloadNumUtil.containSceneNum(num)){
            return null;
        }
        //本地缓存入队
        CurrentDownloadNumUtil.addSceneNum(num);
        //正在下载任务入队
        redisUtil.lLeftPush(RedisKey.SCENE_DOWNLOAD_ING, num);
        return downLoadTaskBean;
    }


}
