package org.springblade.gateway.goods_gateway.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.ObjectUtils;
import org.springblade.common.utils.SpringContextHolder;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.gateway.goods_gateway.constant.HelpGoodsConstant;
import org.springblade.sing.goods.entity.HelpGoods;
import org.springblade.sing.goods.service.IHelpGoodsService;

import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Silent
 * @Description 助力道具工具
 * @Date: Created in 10:02 2021/11/25
 * @Modified By:
 */
public class HelpGoodsUtil {
	private static final IHelpGoodsService helpGoodsService = SpringContextHolder.getBean(IHelpGoodsService.class);
	private static final BladeRedis bladeRedis = SpringContextHolder.getBean(BladeRedis.class);

	/**
	 * 获取助力道具列表
	 * @param activeId
	 * @return
	 */
	public static List<HelpGoods> getHelpGoodsList(@NotNull Long activeId){
		List<HelpGoods> list = JSONArray.parseArray(bladeRedis.hGet(HelpGoodsConstant.HELP_GOODS_CACHE, activeId),HelpGoods.class);
		if(ObjectUtils.isEmpty(list)){
			list = helpGoodsService.list(Wrappers.<HelpGoods>lambdaQuery()
				.eq(HelpGoods::getStatus,1)
				.eq(HelpGoods::getActiveId, activeId));
			//设置缓存
			setHelpGoodsListCache(activeId,list);
		}
		return list;
	}

	/**
	 * 设置助力道具缓存
	 * @param activeId
	 * @param helpGoodsList
	 */
	public static void setHelpGoodsListCache(@NotNull Long activeId,@NotNull List<HelpGoods> helpGoodsList){
		if(ObjectUtils.isNotEmpty(helpGoodsList) && ObjectUtils.isNotEmpty(activeId) && helpGoodsList.size()!=0){
			bladeRedis.hSet(HelpGoodsConstant.HELP_GOODS_CACHE,activeId, JSONObject.toJSONString(helpGoodsList));
		}
	}

	/**
	 * 删除助力道具缓存
	 * @param activeId
	 * @return
	 */
	public static Long removeHelpGoodsListCache(@NotNull Long activeId){
		return bladeRedis.hDel(HelpGoodsConstant.HELP_GOODS_CACHE,activeId);
	}

	/**
	 * 删除集合
	 * @param activeIds
	 * @return
	 */
	public static Long removeHelpGoodsListCache(Collection<Long> activeIds){
		return bladeRedis.hDel(HelpGoodsConstant.HELP_GOODS_CACHE,activeIds.stream().map(Object::toString).collect(Collectors.toList()));
	}
}
