package com.liquidnet.service.sweet.service.impl;

import com.liquidnet.commons.lang.util.RandomUtil;
import com.liquidnet.service.sweet.entity.SweetQrCode;
import com.liquidnet.service.sweet.service.ISweetActiveTypeService;
import com.liquidnet.service.sweet.utils.RedisDataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SweetActiveQrCodeServiceImpl implements ISweetActiveTypeService {

    @Autowired
    private RedisDataUtils redisDataUtils;

    @Override
    public String getRandomQrCode(int type) {
        List<SweetQrCode> sweetQrCodeList = redisDataUtils.getQrCodeTypeNum(type);//SweetQrCodeList
        SweetQrCode bean = judgeRandom(type, sweetQrCodeList);
        if (bean == null) {
            return "";
        } else {
            redisDataUtils.incrQrCodeShowNum(type, bean.getQrCodeId());//访问数量
            return bean.getUrl();
        }
    }


    //获取 可使用的随机数
    private SweetQrCode judgeRandom(int type, List<SweetQrCode> sweetQrCodeList) {
        int randomSwat = RandomUtil.getRandomInt(0, sweetQrCodeList.size());//随机到第几个
        int showNum = redisDataUtils.getQrCodeShowNum(type, sweetQrCodeList.get(randomSwat).getQrCodeId());//访问数量
        int maxNum = redisDataUtils.getQrCodeMaxNum(type);
        if (showNum >= maxNum) {//超过阈值
            sweetQrCodeList.remove(randomSwat);
            if (sweetQrCodeList.size() == 0) {
                return null;
            }
            return judgeRandom(type, sweetQrCodeList);
        } else {
            redisDataUtils.setQrCodeDetails(type, sweetQrCodeList);
            return sweetQrCodeList.get(randomSwat);
        }
    }
}
