package cn.com.qmth.stmms.ms.commons.utils;

import cn.com.qmth.stmms.ms.commons.threadPool.MyThreadPool;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Description: 随机数生成工具类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2019/10/24
 */
@Component
public class RandomUtil {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RandomUtil.class);
    private final int minSize = 1000000;
    private final int maxSize = 1000001;
    private final int randomSize = 2000000;
    private int randomNum = 0;
    private Map<Long, List<Long>> randomMap = new HashMap<>();
//    public static List<Long> randomList = new ArrayList<>();

    @Autowired
    MyThreadPool myThreadPool;

    /**
     * 根据workId随机生成百万随机数
     *
     * @param workId
     * @param againRandom
     */
    public void getRandom(Long workId, boolean againRandom) {
        List list = randomMap.get(workId);
        if (Objects.isNull(list)) {
//            randomMap.clear();
            list = new ArrayList(randomSize);
        }
        if (list.size() == 0 || againRandom) {
            long start = System.currentTimeMillis();
            if (againRandom) {
//                randomMap.clear();
                list = new ArrayList(randomSize);
                randomNum++;
            }
            Long randomReq = workId % 10;
            randomReq = randomReq + randomNum;
            if (randomReq > 9) {
                randomReq = randomReq % 10;
            }
            randomReq = randomReq == 0L ? (long) (Math.random() * 9 + 1) : randomReq;
            LOGGER.info("workId:{},开始生成随机数:{},randomReq:{}", workId, start, randomReq);
            Long finalRandomReq = randomReq;
            List finalList = list;

            myThreadPool.arbitratePoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    Set<Long> set = new HashSet<>(randomSize);
                    for (int i = 0; i < randomSize; i++) {
                        long id = (long) (Math.random() * minSize + maxSize * finalRandomReq);
                        set.add(id);
                    }
                    finalList.addAll(set);
                    set.clear();
                    randomMap.put(workId, finalList);
                    long end = System.currentTimeMillis();
                    LOGGER.info("workId:{},生成随机数耗时：{},数据长度为:{}", workId, (end - start) / 1000 + "s", finalList.size());
                }
            });
        }
    }

    public Map<Long, List<Long>> getRandomMap() {
        return randomMap;
    }

    public void setRandomMap(Map<Long, List<Long>> randomMap) {
        this.randomMap = randomMap;
    }
}
