package com.ruoyi.cai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.*;
import com.ruoyi.cai.dto.admin.vo.AccountAdminVo;
import com.ruoyi.cai.enums.ConsumeLogType;
import com.ruoyi.cai.mapper.AccountMapper;
import com.ruoyi.cai.service.*;
import com.ruoyi.cai.util.NumCaUtil;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户账户Service业务层处理
 *
 * @author 77
 * @date 2023-12-23
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private ConsumeLogService consumeLogService;


    @Override
    public Account getByUserId(Long userId) {
        return this.getOne(Wrappers.lambdaQuery(Account.class).eq(Account::getUserId,userId).last("limit 1"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CaiConsumeLog decr(CaiConsumeLog consumeLog) {
        log.info("开始扣费 consumeLog={}", JSON.toJSONString(consumeLog));
        Long userId = consumeLog.getSourceUserId();
        Long amount = consumeLog.getAmount();

        Account account = this.getByUserId(userId);
        long totalCoin = account.getIncomeCoin() + account.getCoin();
        if(totalCoin < amount){
            throw new ServiceException("余额不足");
        }
        boolean flag = false;
        long diff = account.getCoin() - amount;
        // 充值币够用
        if(diff > 0){
            long l = baseMapper.decrCoin(userId, amount);
            flag = l > 0;
        } else { // 充值币不够用
            long decrCoin = baseMapper.decrCoin(userId, account.getCoin());
            long decrIncomeCoin = baseMapper.decrIncomeCoin(userId, -diff);
            if(decrCoin > 0 && decrIncomeCoin > 0){
                flag = true;
            }
        }
        // 扣费不成功
        if(!flag){
            throw new ServiceException("扣费失败，请重新购买");
        }
        // 开始处理 接收方的费用
        Long targetUserId = consumeLog.getTargetUserId();
        if(targetUserId != null){
            Long anchorAmount = NumCaUtil.coin(amount,consumeLog.getTargetRate());
            consumeLog.setAnchorAmount(anchorAmount);
            baseMapper.incsCoin(targetUserId,anchorAmount);
        }
        // 获取分销的比例和用户
        fenxiao(consumeLog);
        consumeLogService.save(consumeLog);
        return consumeLog;
    }
    @Autowired
    private UserInviteService userInviteService;
    @Autowired
    private UserService userService;
    @Autowired
    private UnionUserService unionUserService;
    @Autowired
    private UnionService unionService;


    private void fenxiao(CaiConsumeLog consumeLog){
        if(ConsumeLogType.PAY.getCode().equals(consumeLog.getType())){
            Long sourceUserId = consumeLog.getSourceUserId();
            UserInvite userInvite = userInviteService.getByUserId(sourceUserId);
            if(userInvite != null){
                User oneUser = userService.getById(userInvite.getInviteId());
                if(oneUser != null && oneUser.getStatus() == 0){
                    consumeLog.setOneRate(userInvite.getPayIncomeRate());
                    consumeLog.setOneUserId(userInvite.getInviteId());
                    consumeLog.setOneUsercode(oneUser.getUsercode());
                    consumeLog.setOnePhone(oneUser.getMobile());
                    consumeLog.setOneJoin(userInvite.getEnableRate());
                    consumeLog.setOneIsUnion(oneUser.getIsUnion());
                }
            }
            return;
        }
        Long targetUserId = consumeLog.getTargetUserId();
        if(targetUserId != null){
            // 获取一级分销
            UserInvite userInvite = userInviteService.getByUserId(targetUserId);
            if(userInvite != null){
                User oneUser = userService.getById(userInvite.getInviteId());
                if(oneUser != null && oneUser.getStatus() == 0){
                    if(ConsumeLogType.GUARD.getCode().equals(consumeLog.getType())){
                        consumeLog.setOneRate(userInvite.getGuardIncomeRate());
                    }else if(ConsumeLogType.GIFT.getCode().equals(consumeLog.getType())){
                        consumeLog.setOneRate(userInvite.getGiftIncomeRate());
                    }else if(ConsumeLogType.VIDEO.getCode().equals(consumeLog.getType())){
                        consumeLog.setOneRate(userInvite.getVideoIncomeRate());
                    }
                    consumeLog.setOneUserId(userInvite.getInviteId());
                    consumeLog.setOneUsercode(oneUser.getUsercode());
                    consumeLog.setOnePhone(oneUser.getMobile());
                    consumeLog.setOneJoin(userInvite.getEnableRate());
                    consumeLog.setOneIsUnion(oneUser.getIsUnion());
                }
            }
            // 工会分销 只有通话和礼物才有
            if(ConsumeLogType.GIFT.getCode().equals(consumeLog.getType())
                    || ConsumeLogType.VIDEO.getCode().equals(consumeLog.getType())){
                UnionUser unionUser = unionUserService.getByUserId(targetUserId);
                if(unionUser != null){
                    User user = userService.getById(unionUser.getId());
                    if(user != null && user.getIsUnion() == 1 && user.getStatus() == 0){
                        Union union = unionService.getById(unionUser.getUnionId());
                        if(union != null){
                            consumeLog.setUnionUsercode(user.getUsercode());
                            consumeLog.setUnionPhone(user.getMobile());
                            consumeLog.setUnionUserId(user.getId());
                            consumeLog.setUnionJoin(false);
                            if(unionUser.getEnableRate() && union.getEnableRate()){
                                consumeLog.setUnionJoin(true);
                            }
                            if(ConsumeLogType.GIFT.getCode().equals(consumeLog.getType())){
                                consumeLog.setUnionRate(unionUser.getGiftDivide());
                            }else if(ConsumeLogType.VIDEO.getCode().equals(consumeLog.getType())){
                                consumeLog.setUnionRate(unionUser.getVideoDivide());
                            }
                        }
                    }
                }
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void withdraw(Long userId, Long incomeCoin){
        Account account = this.getByUserId(userId);
        if(account == null){
            throw new ServiceException("无效账号");
        }
        if(account.getIncomeCoin() < incomeCoin){
            throw new ServiceException("需"+incomeCoin+"紫贝才可提现");
        }
        long incs = baseMapper.decrIncomeCoin(userId, incomeCoin);
        if(incs <= 0){
            throw new ServiceException("需"+incomeCoin+"紫贝才可提现");
        }
    }

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