
package com.tmerclub.cloud.discount.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.discount.mapper.DiscountMapper;
import com.tmerclub.cloud.discount.service.DiscountService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author tmerclub
 */
@Component
public class DiscountTask {

    @Autowired
    private DiscountService discountService;
    @Autowired
    private DiscountMapper discountMapper;

    public static final Logger log = LoggerFactory.getLogger(DiscountTask.class);

    /**
     * 关闭已经结束的满减折活动
     */
    @XxlJob("closeDiscount")
    public void closeDiscount() {
        log.info("关闭已经结束的满减折活动");
        try {
            // 休眠10秒，保证准确关闭到期活动
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        discountService.closeDiscountBySetStatus();
    }

    /**
     * 满减活动开启，删除商家活动缓存
     * 0 0 0/1 * * ?
     */
    @XxlJob("startDiscount")
    public void startDiscount() {
        // 如果有活动在这个整点开始才去清除缓存
        List<Long> shopIds = discountMapper.listShopIdsWhichStart(DateUtil.beginOfHour(new Date()));
        if (CollUtil.isNotEmpty(shopIds)) {
            // 清除缓存
            List<String> keys = new ArrayList<>(Constant.INITIAL_CAPACITY);
            for (Long shopId : shopIds) {
                keys.add(CacheNames.DISCOUNT_BY_SHOPID + CacheNames.UNION + shopId);
            }
            RedisUtil.deleteBatch(keys);
        }
    }
}
