package com.ruoyi.cai.service.impl;

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.AccountBankcard;
import com.ruoyi.cai.domain.AccountCash;
import com.ruoyi.cai.domain.WithdrawExchange;
import com.ruoyi.cai.dto.admin.vo.AccountCashAdminVo;
import com.ruoyi.cai.dto.app.query.WithdrawReq;
import com.ruoyi.cai.mapper.AccountCashMapper;
import com.ruoyi.cai.service.AccountCashService;
import com.ruoyi.cai.service.AccountBankcardService;
import com.ruoyi.cai.service.AccountService;
import com.ruoyi.cai.service.WithdrawExchangeService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class AccountCashServiceImpl extends ServiceImpl<AccountCashMapper, AccountCash> implements AccountCashService {
    @Autowired
    private AccountBankcardService accountBankcardService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private WithdrawExchangeService withdrawExchangeService;
    @Override
    public void withdraw(WithdrawReq res) {
        AccountBankcard one = accountBankcardService.getOne(Wrappers.lambdaQuery(AccountBankcard.class)
                .eq(AccountBankcard::getUserId, res.getUserId()).last("limit 1"));
        if(one == null){
            throw new ServiceException("请先配置支付宝提现账号");
        }
        WithdrawExchange withdrawExchange = withdrawExchangeService.getById(res.getWithdrawSettingId());
        if(withdrawExchange == null){
            throw new ServiceException("参数不正确");
        }
        Long coinNum = withdrawExchange.getCoinNum();
        accountService.withdraw(res.getUserId(), coinNum);
        AccountCash cash = new AccountCash();
        cash.setUserId(res.getUserId());
        cash.setOrderNo("orderNo");
        cash.setWithdrawCoin(coinNum);
        cash.setCashMoney(BigDecimal.valueOf(withdrawExchange.getMoney()));
        cash.setRealCashMoney(BigDecimal.valueOf(withdrawExchange.getMoney()));
        cash.setCashFees(BigDecimal.ZERO);
        cash.setBank(one.getBank());
        cash.setCardName(one.getCardName());
        cash.setCardAccount(one.getCardAccount());
        this.save(cash);
    }

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