package com.duiba.tuia.youtui.web.service.impl;

import cn.com.duiba.wolf.utils.DateUtils;
import com.duiba.tuia.youtui.web.constant.CacheKey;
import com.duiba.tuia.youtui.web.model.rsp.BigAndSmallRsp;
import com.duiba.tuia.youtui.web.service.CustomizedService;
import com.duiba.tuia.youtui.web.tool.CachedKeyUtils;
import com.duiba.tuia.youtui.web.tool.DataUtil;
import com.duiba.tuia.youtui.web.tool.RequestLocal;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 定制的需求的service接口
 *
 * @author lichao 2018/4/2
 */
@Service
public class CustomizedServiceImpl implements CustomizedService {

    /**
     * redisClient
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取猜大小需求的金额
     */
    @Override
    public BigAndSmallRsp bigSmallMoney(Long activityId) {

        return getBigAndSmallRsp(activityId, 18, 1900);
    }

    public BigAndSmallRsp getBigAndSmallRsp(Long activityId, int totalSize, int totalMoney) {
        //先获取redis key
        Date date = new Date();
        String redisKey = CachedKeyUtils.getRedisKey(CacheKey.Customized_BIG_SMALL, activityId,
                RequestLocal.get().getCid()
                , DateUtils.getDayStr(date));
        //1.首先获取当前的金钱
        String money = stringRedisTemplate.opsForValue().get(redisKey);
        int remainSize = totalSize;
        int remainMoney = totalMoney;
        int oldTotalMoney = 0;
        if (StringUtils.isBlank(money)) {
            money = "";
        } else {
            //计算剩余的个数和金钱
            List<Integer> list = Stream.of(money.split(";")).map(s -> Integer.parseInt(s.trim()))
                    .collect(Collectors.toList());
            oldTotalMoney = list.stream().reduce(0, (item1, item2) -> item1 + item2);
            if (oldTotalMoney >= totalMoney || list.size() >= totalSize) {
                return new BigAndSmallRsp(DataUtil.calculateFenToYuan((long) oldTotalMoney), 0.00);
            }
            remainSize -= list.size();
            remainMoney -= oldTotalMoney;
        }
        int newMoney = getRandomMoney(remainSize, remainMoney);

        // 2. 保存当前的所得的所有money
        money += newMoney + ";";
        // 2.1 获取当前时间
        Calendar curDate = Calendar.getInstance();
        curDate.setTime(date);
        // 2.2 获取明天时间
        Calendar tommorowDate = new GregorianCalendar(curDate
                .get(Calendar.YEAR), curDate.get(Calendar.MONTH), curDate
                .get(Calendar.DATE) + 1, 1, 0, 0);
        int times = (int) (tommorowDate.getTimeInMillis() - curDate.getTimeInMillis()) / 1000;
        //2.3 保存到redis
        stringRedisTemplate.opsForValue().set(redisKey, money, times, TimeUnit.SECONDS);
        //返回总数和这次抢的
        oldTotalMoney += newMoney;
        return new BigAndSmallRsp(DataUtil.calculateFenToYuan((long) oldTotalMoney),
                DataUtil.calculateFenToYuan((long) newMoney));
    }

    /**
     * 获取某一次的金额
     *
     * @param remainSize  剩余的红包数量
     * @param remainMoney 剩余的钱
     * @return
     */
    private int getRandomMoney(int remainSize, int remainMoney) {
        Random r = new Random();
        if (remainSize == 1) {
            // 若需要到达最大值，则 return remainMoney
            return r.nextInt(remainMoney + 1);
        }
        int min = 1; //
        int max = remainMoney / remainSize * 2;
        int money = r.nextInt(1000) * max / 1000;
        money = money <= min ? 1 : money;
        return money;
    }


}
