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.admin.vo.account.ExportBatchAuditVo;
import com.ruoyi.cai.dto.app.query.WithdrawReq;
import com.ruoyi.cai.enums.AccountCashStatusEnum;
import com.ruoyi.cai.enums.AuditStatusEnum;
import com.ruoyi.cai.manager.IdManager;
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 com.ruoyi.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@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 traceId = IdManager.nextId();
        Long coinNum = withdrawExchange.getCoinNum();
        accountService.withdraw(res.getUserId(), coinNum,traceId);
        AccountCash cash = new AccountCash();
        cash.setUserId(res.getUserId());
        cash.setTraceId(traceId);
        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);
    }

    @Override
    public void fail(Long id) {
        AccountCash accountCash = this.getById(id);
        if(accountCash == null){
            return;
        }
        boolean update = this.update(Wrappers.lambdaUpdate(AccountCash.class)
                .set(AccountCash::getVerifyTime, LocalDateTime.now())
                .set(AccountCash::getOperateIp, ServletUtils.getClientIP())
                .set(AccountCash::getStatus, AccountCashStatusEnum.FAIL.getCode())
                .eq(AccountCash::getStatus, AccountCashStatusEnum.READY.getCode())
                .eq(AccountCash::getId, id));
        if(!update){
            return;
        }
        accountService.withdrawFail(accountCash.getUserId(),accountCash.getWithdrawCoin(),accountCash.getTraceId());

    }

    @Override
    public ExportBatchAuditVo batchAudit(List<AccountCashAdminVo> result) {
        ExportBatchAuditVo res = new ExportBatchAuditVo();
        Integer allNum = result.size();
        Integer successNum = 0;
        Integer ignoreNum = 0;
        Integer failNum = 0;
        for (AccountCashAdminVo vo : result) {
            try {
                AccountCash cash = this.getById(vo.getId());
                if(!AuditStatusEnum.AUDITING.getCode().equals(cash.getStatus())){
                    ignoreNum++;
                    continue;
                }
                boolean update = this.update(Wrappers.lambdaUpdate(AccountCash.class)
                        .eq(AccountCash::getId, vo.getId())
                        .eq(AccountCash::getStatus, AuditStatusEnum.AUDITING.getCode())
                        .set(AccountCash::getVerifyTime, LocalDateTime.now())
                        .set(AccountCash::getOperateIp, ServletUtils.getClientIP())
                        .set(AccountCash::getStatus, AccountCashStatusEnum.SUCCESS.getCode()));
                if(update){
                    successNum++;
                }else{
                    ignoreNum++;
                }
            }catch (Exception e){
                failNum++;
                log.error("提现申请审核失败");
            }
        }
        res.setSuccessNum(successNum);
        res.setIgnoreNum(ignoreNum);
        res.setAllNum(allNum);
        res.setFailNum(failNum);
        return res;
    }


}
