package com.itheima.quartz;

import com.itheima.arithmetic.ReducePriceUtils;
import com.itheima.dao.MoneyPackageDao;
import com.itheima.domain.MoneyPackage;
import com.itheima.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/*****
 * @Author: http://www.itheima.com
 * @Description: com.itheima.quartz.MoneyPushTask
 ****/
@Component
public class MoneyPushTask {

    @Autowired
    private MoneyPackageDao moneyPackageDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /****
     * 每30秒加载一次红包信息到队列中
     */
    @Scheduled(cron = "0/30 * * * * ?") //定时任务Quartz
    public void pushMoney(){
        //1）查询1条记录，更新状态为3
        MoneyPackage one = moneyPackageDao.findOne();

        if(one!=null){
            //改状态
            moneyPackageDao.modify(one.getId());

            //2）计算红包个数  10  随机算
            List<Double> doubles = ReducePriceUtils.splitReducePrice(one.getMoney(), one.getCount());

            Double[] moneys = new Double[doubles.size()];
            doubles.toArray(moneys);

            //3）将红包信息存入到队列中
            redisTemplate.boundListOps(Constant.MONEY_QUEUE_NAME).leftPushAll(moneys);
        }
    }
}
