package com.liquidnet.client.admin.zhengzai.stone.service.utils;

import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.service.stone.constant.StoneConstant;
import com.liquidnet.service.stone.entity.StoneScoreItems;
import com.liquidnet.service.stone.vo.StoneUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class StoneRedisUtils {

    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;
    @Autowired
    private StoneMongoUtils mongoUtils;

    /**
     * 获取 积分物品 剩余库存
     *
     * @param itemId ID
     * @return
     */
    public Integer getStoneGeneralSurplus(String itemId) {
        String redisKey = StoneConstant.ITEM.concat(itemId).concat(StoneConstant.SURPLUS_GENERAL);
        Object obj = redisDataSourceUtil.getRedisStoneUtil().get(redisKey);
        if (obj == null) {
            return 0;
        } else {
            return (Integer) obj;
        }
    }

    /**
     * 修改 积分物品 库存
     *
     * @param itemId  ID
     * @param general 改变量
     * @return
     */
    public Integer changeStoneGeneralSurplus(String itemId, Integer general) {
        String redisKey = StoneConstant.ITEM.concat(itemId).concat(StoneConstant.SURPLUS_GENERAL);
        long result;
        if (general > 0) {
            result = redisDataSourceUtil.getRedisStoneUtil().incr(redisKey, general);
        } else {
            result = redisDataSourceUtil.getRedisStoneUtil().decr(redisKey, Math.abs(general));
        }
        return (int) result;
    }

    /**
     * 设置 积分物品 缓存
     *
     * @param itemId
     * @param data
     */
    public void setItemData(String itemId, StoneScoreItems data) {
        String redisKey = StoneConstant.ITEM.concat(itemId);
        redisDataSourceUtil.getRedisStoneUtil().set(redisKey, data);
    }

    /**
     * 获取 积分物品 缓存
     *
     * @param itemId
     */
    public StoneScoreItems getItemData(String itemId) {
        String redisKey = StoneConstant.ITEM.concat(itemId);
        Object obj = redisDataSourceUtil.getRedisStoneUtil().get(redisKey);
        if (obj == null) {
            return mongoUtils.itemGet(itemId);
        } else {
            return (StoneScoreItems) obj;
        }
    }

    /**
     * 设置 用户积分 缓存
     *
     * @param uid
     * @param data
     */
    public void setUserData(String uid, StoneUserVo data) {
        String redisKey = StoneConstant.USER.concat(uid);
        redisDataSourceUtil.getRedisStoneUtil().set(redisKey, data);
    }

    /**
     * 获取 用户积分 缓存
     *
     * @param uid
     */
    public StoneUserVo getUserData(String uid) {
        String redisKey = StoneConstant.USER.concat(uid);
        Object obj = redisDataSourceUtil.getRedisStoneUtil().get(redisKey);
        if (obj == null) {
            return null;
        } else {
            return (StoneUserVo) obj;
        }
    }

}
