
package com.tmerclub.cloud.product.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.product.vo.SkuStockVO;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.product.manager.StockManager;
import com.tmerclub.cloud.product.model.Giveaway;
import com.tmerclub.cloud.product.service.*;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 商品定时任务
 *
 * @author tmerclub
 */
@Component
public class ProductTask {
    private static final Logger log = LoggerFactory.getLogger(ProductTask.class);
    @Autowired
    private SpuService spuService;
    @Autowired
    private GiveawayService giveawayService;
    @Autowired
    private StockManager stockManager;
    @Autowired
    private SkuStockService skuStockService;
    @Autowired
    private StockBillLogService stockBillLogService;
    @Autowired
    private SkuStockLockService skuStockLockService;
    @Autowired
    private WarehouseService warehouseService;

    /**
     * 校验商品数量是否完整
     * 商品数据是否为最新的：根据商品更新时间判断
     */
    @XxlJob("verifySpuData")
    public void verifySpuData() {
        spuService.verifySpuData();
    }

    /**
     * 结束赠品活动
     */
    @XxlJob("activityFinishAndProdChange")
    public void activityFinishAndProdChange() {
        XxlJobHelper.log("赠品活动结束，主商品恢复为普通商品。。。");
        // -1：已删除 0：关闭 1:开启 2：未开启
        // 获取活动结束，需要改变商品类型的列表
        List<Giveaway> giveawayActivityList = giveawayService.listUnEndButNeedEndActivity();

        if (CollUtil.isEmpty(giveawayActivityList)) {
            return;
        }
        giveawayService.changeSpuTypeByGiveawayActivityIdList(giveawayActivityList);
    }

    /**
     * 启用赠品活动
     */
    @XxlJob("activityStartAndProdChange")
    public void activityStartAndProdChange() {
        XxlJobHelper.log("赠品活动开启");
        giveawayService.startGiveawayActivity();
    }


    @XxlJob("offlineExpireVirtualProd")
    public void offlineExpireVirtualProd() {
        XxlJobHelper.log("过了核销时间的虚拟商品，进行下架操作。");
        // 获取30分钟之前未支付的订单
        List<SpuVO> spuVOList = spuService.handleExpireVirtualProd();
        if (CollectionUtils.isEmpty(spuVOList)) {
            return;
        }
        for (SpuVO spuVO : spuVOList) {
            //清除缓存
            spuService.removeSpuCacheBySpuId(spuVO.getSpuId());
        }
    }

    /**
     * 处理sku库存的变化
     *
     * sku库存发生变化时，将最新的sku库存、销量求和，写入es的商品库存、销量中
     * 以及变更sku的库存预警
     */
    @XxlJob("handleSkuStockChange")
    public void handleSkuStockChange() {
        try {
            skuStockService.handleSkuStockChange();
        } catch (Exception e) {
            log.error("处理sku库存变化失败", e);
        }
    }

    @XxlJob("intiStock")
    public void intiStock() {

        // ===================== 初始化商品库存 =====================
        try{
            skuStockService.initSkuStock();
        } catch (Exception e) {
            log.error("初始化商品库存失败", e);
        }
        // ===================== 初始化商品库存记录 =====================
        // 缺少库存项的库存记录，都更新一遍，补全数据
        stockBillLogService.initStockBillLog();
    }

    @XxlJob("intiPointStock")
    public void intiPointStock() {
        // ===================== 初始化商品库存 =====================
        try{
            warehouseService.intiWarehouse();
            spuService.intiStockPointSKu();
            skuStockService.initPointStock();
        } catch (Exception e) {
            log.error("初始化商品库存失败", e);
        }
    }


    /**
     * 订单解锁sku库存
     *
     */
    @XxlJob("unLockOrderSkuStock")
    public void unLockOrderSkuStock() {
        // 获取所有锁定库存的订单记录
        List<SkuStockVO> skuStockList = stockManager.scanLockStockOrderLog();
        // 批量处理订单解锁库存
        try {
            skuStockLockService.unlockStockByException(skuStockList);
        } catch (Exception e) {
            log.error("订单解锁库存失败", e);
        }
    }
}
