
package com.tmerclub.cloud.coupon.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.api.product.vo.SkuStockVO;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.constant.LockCacheNames;
import com.tmerclub.cloud.common.cache.manager.MultiRedisStockManager;
import com.tmerclub.cloud.common.cache.util.CacheManagerUtil;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.coupon.manager.CouponStockManager;
import com.tmerclub.cloud.coupon.mapper.CouponMapper;
import com.tmerclub.cloud.coupon.service.CouponService;
import com.tmerclub.cloud.coupon.service.CouponUserService;
import com.tmerclub.cloud.coupon.vo.CouponUserVO;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.collections.CollectionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
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;

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

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

    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CouponStockManager couponStockManager;

    /**
     * 删除用户失效180天以上的优惠券
     */
    @XxlJob("deleteCouponUser")
    public void deleteCouponUser() {
        log.info("删除用户失效180天以上的优惠券");
        // 删除用户失效半年以上的优惠券 参考京东
        couponUserService.deleteUnValidTimeCoupons(DateUtil.offsetDay(new Date(), -180));
    }

    /**
     * 改变用户优惠券的状态(设为失效状态)
     */
    @XxlJob("changeCouponUser")
    public void changeCouponUser() {
        log.info("设置用户的过期优惠券为失效状态");
        // 设置用户的过期优惠券为失效状态
        couponUserService.updateStatusByTime();
    }

    /**
     * 改变店铺优惠券的状态(设为过期状态)
     */
    @XxlJob("changeCoupon")
    public void changeCoupon() {
        log.info("设置店铺的过期优惠券为过期状态");
        // 查询需要更新的店铺id列表
        List<Long> shopIds = couponMapper.listOverdueStatusShopIds();
        // 取消投放
        couponService.cancelPut();
        //清除缓存
        if (CollectionUtils.isNotEmpty(shopIds)) {
            List<String> keys = new ArrayList<>(Constant.INITIAL_CAPACITY);
            for (Long shopId : shopIds) {
                keys.add(CacheNames.COUPON_LIST_BY_SHOP_KEY + CacheNames.UNION + shopId);
            }
            RedisUtil.deleteBatch(keys);
        }
    }

    /**
     * 投放优惠券
     */
    @XxlJob("putOnCoupon")
    public void putOnCoupon() {
        log.info("投放优惠券");
        // 投放优惠券
        couponService.putonCoupon();
    }

    /**
     * 初始化原有数据库记录至mongodb
     * 该定时任务成功执行一次即可!!!!!，成功执行完后将任务置为STOP状态或删除
     */
    @XxlJob("initCouponUserToMongodb")
    public void initCouponUserToMongodb() {
        log.info("初始化领券记录");
        couponUserService.initCouponUserToMongodb();
    }

    /**
     * 解锁优惠券
     */
    @XxlJob("unLockCouponStock")
    public void unLockCouponStock() {
        log.info("解锁优惠券记录");
        List<CouponUserVO> couponUserIds = couponStockManager.scanLockStockCouponLog(null);
        if (CollUtil.isEmpty(couponUserIds)) {
            return;
        }
        // 批量处理订单解锁库存
        try {
            couponStockManager.unlockStockByException(couponUserIds);
        } catch (Exception e) {
            log.error("优惠券解锁库存失败", e);
        }
    }
}
