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

import com.liquidnet.client.admin.zhengzai.kylin.utils.MongoVoUtils;
import com.liquidnet.common.cache.redis.util.RedisUtil;
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.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class StoneRedisUtils {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoVoUtils mongoVoUtils;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取 积分物品 剩余库存
     *
     * @param itemId ID
     * @return
     */
    public Integer getStoneGeneralSurplus(String itemId) {
        String redisKey = StoneConstant.ITEM.concat(itemId).concat(StoneConstant.SURPLUS_GENERAL);
        Object obj = redisUtil.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 = redisUtil.incr(redisKey, general);
        } else {
            result = redisUtil.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);
        redisUtil.set(redisKey, data);
    }

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

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

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

}
