package com.ruoyi.xq.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserExtend;
import com.ruoyi.xq.dto.admin.user.UserExtendAdminVo;
import com.ruoyi.xq.dto.admin.user.req.UpdateIncomeCoinReq;
import com.ruoyi.xq.mapper.UserExtendMapper;
import com.ruoyi.xq.service.UserExtendService;
import com.ruoyi.xq.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 用户邀请Service业务层处理
 *
 * @author 77
 * @date 2024-03-04
 */
@RequiredArgsConstructor
@Service
public class UserExtendServiceImpl extends ServiceImpl<UserExtendMapper,UserExtend> implements UserExtendService {
    @Autowired
    private UserService userService;

    @Override
    public boolean withdraw(Long userId, BigDecimal withdrawPrice){
        boolean success = baseMapper.decrIncome(userId, withdrawPrice);
        if(success){
            // TODO 记录金额流水
        }
        return success;
    }

    @Override
    public void resetWithdraw(Long userId, BigDecimal withdrawMoney, String traceId) {
        boolean success = baseMapper.incrIncome(userId, withdrawMoney);
        if(success){
            // TODO 记录金额流水
        }
    }

    /**
     * 新增提现统计
     * @param userId
     * @param withdrawMonty
     */
    @Override
    public boolean incsWithdrawCount(Long userId, BigDecimal withdrawMonty){
        return baseMapper.incsWithdrawCount(userId,withdrawMonty);
    }


    @Override
    public Page<UserExtendAdminVo> pageAdmin(PageQuery pageQuery, UserExtendAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(), bo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateIncomeCoin(UpdateIncomeCoinReq bo) {
        User user = userService.getByUsercode(bo.getUsercode());
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        boolean income = baseMapper.incrIncome(user.getId(), bo.getRechargeCoin());
        if(!income){
            throw new ServiceException("调整失败，请保证调整后金额不为负数");
        }
    }

}
