package com.zd.base.job.task;

import com.zd.common.core.domain.R;
import com.zd.common.redis.service.RedisService;
import com.zd.system.api.exam.RemoteExamService;
import com.zd.system.api.exam.domain.ElResources;
import com.zd.system.api.kkFile.RemoteKkFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 文件预览
 */
@Component("fileViewTask")
public class FileViewTask {

    private static Logger logger = LoggerFactory.getLogger(FileViewTask.class);

    /** 固定的线程池（当前线程池大小为30） */
    private static final ExecutorService executor = Executors.newFixedThreadPool(30);

    @Autowired
    private RemoteKkFileService remoteKkFileService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteExamService remoteExamService;

    private URI url;
    {
        try {
            url = new URI("http://127.0.0.1:8012");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     *  两个要点：
     *  1.用Executors实现固定大小的线程池，从而达到控制硬件资源消耗的目的。
     *  2.用CountDownLatch（闭锁），来确保循环内的多线程都执行完成后，再执行后续代码
     */
    public void cacheKkFile() throws InterruptedException {
        logger.info("***********文件分片任务开始***********");
        R resourcesR = remoteExamService.listAll();
        if (resourcesR.getCode() != 200) {
            return;
        }
        List<ElResources> resourcesList = (List<ElResources>) resourcesR.getData();
        for(ElResources resources:resourcesList){
            resources.setPath("http://192.168.251.2/labSystem/"+resources.getPath());
        }
        if(null!=resourcesList && resourcesList.size()>0){
            logger.info("resourcesList.size()***********"+resourcesList.size()+"***********");
        }
        // 初始化计时器
        CountDownLatch cdl = new CountDownLatch(resourcesList.size());
        for (ElResources resources : resourcesList) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        logger.info("ThreadName"+Thread.currentThread().getName()+"resourcesId:"+resources.getId());
                        getKkFileAsync(resources.getPath());
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.info("error msg:"+e.getMessage());
                    }
                    // 闭锁-1
                    cdl.countDown();
                }
            });
        }
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //关闭线程池
        executor.awaitTermination(5, TimeUnit.SECONDS);
        logger.info("***********文件分片任务完成***********");
    }

    public String getKkFileAsync(String resource) {
        String resultStr = remoteKkFileService.getKkFilePath(url, URLEncoder.encode(Base64.getEncoder().encodeToString(resource.getBytes())));
        if ("image".equals(resultStr)) {
            logger.info("***********远程分片操作成功***********");
        }
        return resultStr;
    }
}
