package com.liquidnet.service.kylin.utils;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.entity.KylinBuyNotice;
import com.liquidnet.service.kylin.mapper.KylinBuyNoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DataUtils {

    @Autowired
    private KylinBuyNoticeMapper buyNoticeMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据 购票须知 id 获取 购票须知文案
     *
     * @param buyNoticeIds 购票须知 数组
     * @return 购票须知 json串
     */
    public String getBuyNoticeJsonString(List<String> buyNoticeIds) {
        List<KylinBuyNotice> data = buyNoticeMapper.selectList(new UpdateWrapper<KylinBuyNotice>().in("buy_notice_id", buyNoticeIds));
        return JsonUtils.toJson(data);
    }

    /**
     * 初始化普通库存
     *
     * @param ticketId     票id
     * @param totalGeneral 普通库存
     */
    public void setSurplusGeneral(String ticketId, int totalGeneral) {
        redisUtil.hset(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId, KylinRedisConst.SURPLUS_GENERAL, totalGeneral);
    }

    /**
     * 获取普通剩余库存
     *
     * @param ticketId 票id
     * @return 普通剩余库存
     */
    public int getSurplusGeneral(String ticketId) {
        return (int) redisUtil.hget(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId, KylinRedisConst.SURPLUS_GENERAL);
    }

    /**
     * 修改普通库存 并 返回修改后的数量
     *
     * @param ticketId       票id
     * @param surplusGeneral 普通库存
     * @return 普通剩余库存
     */
    public int changeSurplusGeneral(String ticketId, int surplusGeneral) {
        return (int) redisUtil.hincr(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId, KylinRedisConst.SURPLUS_GENERAL, surplusGeneral);
    }

    /**
     * 初始化兑换库存
     *
     * @param ticketId      票id
     * @param totalExchange 兑换库存
     */
    public void setSurplusExchange(String ticketId, int totalExchange) {
        redisUtil.hset(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId, KylinRedisConst.SURPLUS_EXCHANGE, totalExchange);
    }

    /**
     * 获取兑换剩余库存
     *
     * @param ticketId 票id
     * @return 兑换剩余库存
     */
    public int getSurplusExchange(String ticketId) {
        return (int) redisUtil.hget(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId, KylinRedisConst.SURPLUS_EXCHANGE);
    }

    /**
     * 变更兑换库存 并 返回 修改后的数量
     *
     * @param ticketId        票id
     * @param surplusExchange 普通库存
     * @return 兑换剩余库存
     */
    public int changeSurplusExchange(String ticketId, int surplusExchange) {
        return (int) redisUtil.hincr(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId, KylinRedisConst.SURPLUS_GENERAL, surplusExchange);
    }

}
