package com.ruoyi.cai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.*;
import com.ruoyi.cai.dto.app.query.GiveGiftRes;
import com.ruoyi.cai.dto.app.vo.index.UserGiftIndexVo;
import com.ruoyi.cai.enums.ConsumeLogType;
import com.ruoyi.cai.mapper.UserGiftMapper;
import com.ruoyi.cai.service.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 礼物记录Service业务层处理
 *
 * @author 77
 * @date 2023-12-23
 */
@RequiredArgsConstructor
@Service
public class UserGiftServiceImpl extends ServiceImpl<UserGiftMapper, UserGift> implements UserGiftService {

    @Autowired
    private GiftService giftService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserService userService;
    @Autowired
    private AnchorService anchorService;


    @Override
    public List<UserGiftIndexVo> selectGiftList(Long userId) {
        return baseMapper.selectGiftList(userId);
    }

    @Override
    public boolean giveGift(GiveGiftRes query) {
        Long fromUserId = LoginHelper.getUserId();
        Gift gift = giftService.getById(query.getGiftId());
        if(gift == null){
            throw new ServiceException("礼物不存在");
        }
        User fromUser = userService.getById(fromUserId);
        User toUser = userService.getById(query.getToUserId());
        Anchor anchor = anchorService.getByUserId(query.getToUserId());
        Long price = gift.getPrice();
        Long giftAmount = query.getGiftCount() * price;
        CaiConsumeLog consumeLog = new CaiConsumeLog();
        consumeLog.init(fromUser,toUser);
        consumeLog.setType(ConsumeLogType.GIFT.getCode());
        consumeLog.setAmount(giftAmount);
        consumeLog.setTargetRate(anchor.getGiftRate());
        consumeLog = accountService.decr(consumeLog);
        UserGift userGift = new UserGift();
        userGift.setType(query.getType());
        userGift.setFromUid(fromUserId);
        userGift.setFromMobile(fromUser.getMobile());
        userGift.setFromUsercode(fromUser.getUsercode());
        userGift.setToUid(query.getToUserId());
        userGift.setToMobile(toUser.getMobile());
        userGift.setToUsercode(toUser.getUsercode());
        userGift.setGiftId(query.getGiftId());
        userGift.setGiftName(gift.getName());
        userGift.setGiftImg(gift.getImg());
        userGift.setGiftPrice(gift.getPrice());
        userGift.setGiftCount(query.getGiftCount());
        userGift.setGiftAmount(giftAmount);
        userGift.setConsumerLogId(consumeLog.getId());
        this.save(userGift);
        return true;
    }
}
