package com.ruoyi.cai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.*;
import com.ruoyi.cai.mapper.UserCallMapper;
import com.ruoyi.cai.service.AccountService;
import com.ruoyi.cai.service.UnionUserService;
import com.ruoyi.cai.service.UserCallService;
import com.ruoyi.cai.service.UserInviteService;
import com.ruoyi.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 通话记录Service业务层处理
 *
 * @author 77
 * @date 2023-12-27
 */
@RequiredArgsConstructor
@Service
public class UserCallServiceImpl extends ServiceImpl<UserCallMapper, UserCall> implements UserCallService {

    @Autowired
    private AccountService accountService;
    @Autowired
    private UserInviteService inviteService;
    @Autowired
    private UnionUserService unionUserService;
    @Override
    public UserCall createCall(User fromUser, User toUser, Anchor anchor) {
        Long fromUid = fromUser.getId();
        // 特殊用户不允许拨打电话
        if(fromUid.equals(toUser.getId())){
            throw new ServiceException("不能给自己拨打哦!");
        }
        if(anchor == null){
            throw new ServiceException("主播技能不存在");
        }
        if(anchor.getOpenVideoStatus() == 0){
            throw new ServiceException("对方未开启视频接听!");
        }
        Account account = accountService.getByUserId(fromUid);
        if(account.getIncomeCoin() + account.getCoin() < anchor.getPrice() * 2){
            throw new ServiceException("你的紫贝不足!");
        }
        UserCall userCall = new UserCall();
        userCall.setFromUid(fromUid);
        userCall.setToUid(toUser.getId());
        userCall.setCallPrice(anchor.getPrice());
        userCall.setReceiverVideoDivide(anchor.getVideoRate());
        UnionUser unionUser = unionUserService.getByUserId(toUser.getId());
        if(unionUser != null && unionUser.getEnableRate()){
            userCall.setReceiverUnionUserId(unionUser.getUserId());
            userCall.setReceiverUnionVideoDivide(unionUser.getVideoDivide());
        }
        UserInvite invite = inviteService.getByUserId(toUser.getId());
        if(invite != null){
            userCall.setReceiverInviteUserId(invite.getInviteId());
            userCall.setReceiverIncomeDivide(invite.getVideoIncomeRate());
        }
        boolean save = this.save(userCall);
        if(!save){
            throw new ServiceException("添加通话失败!");
        }
        return userCall;
    }
}
