package cc.mrbird.febs.dapp.utils;
|
|
import cc.mrbird.febs.common.contants.AppContants;
|
import cc.mrbird.febs.common.utils.RedisUtils;
|
import cc.mrbird.febs.common.utils.SpringContextUtil;
|
import cn.hutool.core.collection.CollUtil;
|
import cn.hutool.core.util.RandomUtil;
|
import com.alibaba.fastjson.JSONObject;
|
import lombok.extern.slf4j.Slf4j;
|
|
import java.util.ArrayList;
|
import java.util.Collections;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.concurrent.ConcurrentHashMap;
|
|
/**
|
* @author wzy
|
* @date 2022-07-14
|
**/
|
@Slf4j
|
public class BoxUtil {
|
|
// public static volatile List<Box> boxList = Collections.synchronizedList(new ArrayList<>());
|
|
private static final RedisUtils redisUtils = SpringContextUtil.getBean(RedisUtils.class);
|
public synchronized static Box openBox() {
|
String redisStr = redisUtils.getString(AppContants.IDO_BOX_PRIZE);
|
List<Box> boxList = JSONObject.parseArray(redisStr, Box.class);
|
if (CollUtil.isEmpty(boxList)) {
|
boxList = Collections.synchronizedList(new ArrayList<>());
|
Box box1 = new Box(1, 95);
|
Box box2 = new Box(2, 3);
|
Box box3 = new Box(3, 2);
|
boxList.add(box1);
|
boxList.add(box2);
|
boxList.add(box3);
|
}
|
|
int min = 1;
|
int minIndex = 1;
|
int max = 1;
|
|
for (int i = 0; i < boxList.size(); i++) {
|
Box box = boxList.get(i);
|
if (i != 0) {
|
Box lastBox = (Box) boxList.get(i - 1);
|
minIndex += lastBox.getCount();
|
}
|
max += box.getCount();
|
box.setMin(minIndex);
|
box.setMax(max);
|
}
|
|
int i = RandomUtil.randomInt(min, max);
|
|
Box result = new Box();
|
for (Box box : boxList) {
|
if (box.getMin() <= i && box.getMax() > i) {
|
result = box;
|
int count = box.getCount();
|
count--;
|
|
box.setCount(count);
|
if (count == 0) {
|
boxList.remove(box);
|
}
|
break;
|
}
|
}
|
redisUtils.set(AppContants.IDO_BOX_PRIZE, JSONObject.toJSONString(boxList));
|
return result;
|
}
|
|
public static class Box {
|
private int index;
|
|
private int count;
|
|
public Box() {}
|
|
public Box(int index, int count) {
|
this.index = index;
|
this.count = count;
|
}
|
|
private int min;
|
|
private int max;
|
|
public int getIndex() {
|
return index;
|
}
|
|
public void setIndex(int index) {
|
this.index = index;
|
}
|
|
public int getCount() {
|
return count;
|
}
|
|
public void setCount(int count) {
|
this.count = count;
|
}
|
|
public int getMin() {
|
return min;
|
}
|
|
public void setMin(int min) {
|
this.min = min;
|
}
|
|
public int getMax() {
|
return max;
|
}
|
|
public void setMax(int max) {
|
this.max = max;
|
}
|
}
|
|
}
|