package com.fs.app.controller.live;

import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.common.core.redis.RedisCache;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.live.domain.LiveGift;
import com.fs.live.domain.LiveUserGift;
import com.fs.live.service.ILiveGiftService;
import com.fs.live.service.ILiveUserGiftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/app/live/liveUserGift")
public class LiveUserGiftController extends AppBaseController {

    @Autowired
    private ILiveUserGiftService liveUserGiftService;

    @Autowired
    private ILiveGiftService liveGiftService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IFsUserService fsUserService;

    /**
     *给直播间送礼物
     */
    @Login
    @PostMapping("/send")
    @Transactional
    public String send(@RequestBody LiveUserGift liveUserGift) {
        liveUserGift.setUserId(Long.parseLong(getUserId()));
        long giftValue;
        List<LiveGift> liveGifts = redisCache.getCacheList("liveGift");
        LiveGift liveGift = liveGifts.stream().filter(gift ->
                gift.getGiftId().equals(liveUserGift.getGiftId()))
                .findFirst().orElse(null);
        if (liveGift == null) {
            return "礼物信息不存在";
        }else{
            giftValue = liveGift.getPrice().longValue() * liveUserGift.getCn();
        }
        FsUser user=fsUserService.selectFsUserByUserId(liveUserGift.getUserId());
        if (user.getIntegral().longValue() < giftValue) {
            return "账户余额不足";
        }
        user.setIntegral(user.getIntegral() - giftValue);
        fsUserService.updateFsUser(user);
        return liveUserGiftService.save(liveUserGift)?"赠送礼物成功":"赠送礼物失败";
    }

}
