package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.SysUserContractRecordDao;
import com.yonge.cooleshow.biz.dal.dto.req.AuthOperaReq;
import com.yonge.cooleshow.biz.dal.entity.UserWithdrawalCallback;
import com.yonge.cooleshow.biz.dal.enums.*;
import com.yonge.cooleshow.biz.dal.sdk.WithdrawSdk;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.UserAccountRecordVo;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.payment.util.DistributedLock;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.biz.dal.dao.UserBankCardDao;
import com.yonge.cooleshow.biz.dal.dto.UserAccountRecordDto;
import com.yonge.cooleshow.biz.dal.dto.req.WithdrawalReq;
import com.yonge.cooleshow.biz.dal.entity.UserAccountRecord;
import com.yonge.cooleshow.biz.dal.vo.UserAccountVo;
import com.yonge.cooleshow.biz.dal.vo.UserBankCardVo;
import com.yonge.cooleshow.biz.dal.vo.res.WithdrawalInfoRes;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.CacheNameEnum;
import com.yonge.cooleshow.common.service.IdGeneratorService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.string.StringPool;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.payment.base.enums.TradeStatusEnum;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import com.yonge.toolset.utils.string.ValueUtil;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yonge.cooleshow.biz.dal.entity.UserWithdrawal;
import com.yonge.cooleshow.biz.dal.vo.UserWithdrawalVo;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherWithdrawalSearch;
import com.yonge.cooleshow.biz.dal.dao.UserWithdrawalDao;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


@Service
public class UserWithdrawalServiceImpl extends ServiceImpl<UserWithdrawalDao, UserWithdrawal> implements UserWithdrawalService {
    private final static Logger log = LoggerFactory.getLogger(UserWithdrawalServiceImpl.class);

    @Autowired
    private UserBankCardDao bankCardDao;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private WithdrawSdk withdrawSdk;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private SysUserContractRecordDao userContractRecordDao;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private UserAccountRecordService accountRecordService;

    @Override
    public UserWithdrawalVo detail(Long id) {
        UserWithdrawalVo detail = baseMapper.detail(id);
        return detail;
    }

    @Override
    public UserWithdrawalVo detailByTransNo(String transNo) {
        UserWithdrawalVo detail = baseMapper.detailByTransNo(transNo);
        return detail;
    }

    @Override
    public IPage<UserWithdrawalVo> selectPage(IPage<UserWithdrawalVo> page, TeacherWithdrawalSearch query) {
        List<UserWithdrawalVo> withdrawalVoList = baseMapper.selectPage(page, query);
        withdrawalVoList.forEach(o -> {
            if (AuthStatusEnum.DOING.equals(o.getAuthStatus()) || TradeStatusEnum.pending.equals(o.getTradeStatus())) {
                o.setWithdrawStatus("DOING");
            } else if (TradeStatusEnum.succeeded.equals(o.getTradeStatus())) {
                o.setWithdrawStatus("SUCCESS");
            } else {
                o.setWithdrawStatus("FAILED");
            }
            o.setBankCard(ValueUtil.fuzzyBankCard(o.getBankCard()));
        });
        return page.setRecords(withdrawalVoList);
    }

    @Override
    public List<UserWithdrawalVo> selectList(TeacherWithdrawalSearch query) {
        return baseMapper.selectAllList(query);
    }

    @Override
    public HttpResponseResult<WithdrawalInfoRes> getWithdrawalInfo(Long userId) {
        WithdrawalInfoRes withdrawalInfoRes = new WithdrawalInfoRes();
        UserBankCardVo defaultBank = bankCardDao.getDefaultBankByUserId(userId);
        if (null != defaultBank) {
            defaultBank.setPhone(ValueUtil.fuzzyMobile(defaultBank.getPhone()));
            defaultBank.setBankCard(ValueUtil.fuzzyBankCard(defaultBank.getBankCard()));
            withdrawalInfoRes.setUserBankCard(defaultBank);
        }
        //获取平台结算手续费
        BigDecimal withdrawalServiceFee = getWithdrawalServiceFee();
        withdrawalInfoRes.setWithdrawalServiceFee(withdrawalServiceFee);
        //获取用户可用于结算余额
        withdrawalInfoRes.setAmountWithdrawal(getAmountUsable(userId));
        return HttpResponseResult.succeed(withdrawalInfoRes);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<Boolean> withdrawal(SysUser user, WithdrawalReq withdrawalReq) {
        if (StringUtil.isEmpty(user.getIdCardNo())) {
            return HttpResponseResult.failed("用户未实名认证");
        }
        //校验--结算开关
        String withdrawalSwitch = sysConfigService.findConfigValue(SysConfigConstant.WITHDRAWAL_SWITCH);
        if (!YesOrNoEnum.YES.getCode().toString().equals(withdrawalSwitch)) {
            return HttpResponseResult.failed("当前不允许结算");
        }
        //校验--判断今天结算次数
        String withdrawalMaxCount = sysConfigService.findConfigValue(SysConfigConstant.WITHDRAWAL_MAX_COUNT);
        Integer count = getNowDayWithdrawalCount(user.getId());
        if (count >= Integer.parseInt(withdrawalMaxCount)) {
            return HttpResponseResult.failed("达到当天结算最大次数");
        }
        //校验--校验金额(金额不能小于手续费，手续费从结算金额里面扣除)
        BigDecimal withdrawalServiceFee = getWithdrawalServiceFee();
        BigDecimal actualAmount = withdrawalReq.getAmountWithdrawal().subtract(withdrawalServiceFee);
        if (actualAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return HttpResponseResult.failed("结算金额过小");
        }
        //获取用户可结算金额
        BigDecimal amountWithdrawal = getAmountUsable(user.getId());
        if (amountWithdrawal.compareTo(withdrawalReq.getAmountWithdrawal()) < 0) {
            return HttpResponseResult.failed("账户余额不足");
        }
        //获取结算银行卡
        UserBankCardVo bankCardVo = bankCardDao.getBankByUserIdAndCardId(user.getId(), withdrawalReq.getBankCardId());
        if (null == bankCardVo) {
            return HttpResponseResult.failed("未找到用户绑卡信息");
        }
        //结算审核开关
        String withdrawalAuthSwitch = sysConfigService.findConfigValue(SysConfigConstant.WITHDRAWAL_AUTH_SWITCH);
        //结算审核额度(小于该额度免审核结算)
        String withdrawalAuthFee = sysConfigService.findConfigValue(SysConfigConstant.WITHDRAWAL_AUTH_FEE);

        //插入用户结算表
        UserWithdrawal userWithdrawal = insertUserWithdrawal(user.getId(), withdrawalReq, bankCardVo, withdrawalServiceFee, withdrawalAuthSwitch, withdrawalAuthFee);
        //插入账户变更
        HttpResponseResult<UserAccountRecord> accountChange = userAccountService.accountRecord(new UserAccountRecordDto(user.getId(), PostStatusEnum.FROZEN,
                withdrawalReq.getAmountWithdrawal(), InOrOutEnum.OUT, AccountBizTypeEnum.WITHDRAWAL,
                userWithdrawal.getId(), "老师结算", null, null
        ));

        if (accountChange.getStatus()) {
            if (YesOrNoEnum.NO.getCode().toString().equals(withdrawalAuthSwitch)
                    || new BigDecimal(withdrawalAuthFee).compareTo(withdrawalReq.getAmountWithdrawal()) > 0) {
                //不用审核的，直接请求三方
                //交易流水号生成
                Long transNo = idGeneratorService.generatorId("withdrawNo");

                HttpResponseResult<Boolean> withdraw = withdrawSdk.withdraw(
                        transNo.toString(), bankCardVo.getName(), bankCardVo.getPhone(), user.getIdCardNo(),
                        userWithdrawal.getActualAmount().multiply(new BigDecimal("100")).intValue(), bankCardVo.getBankCard(), null
                );
                if (withdraw.getStatus() && withdraw.getData()) {
                    userWithdrawal.setTradeStatus(TradeStatusEnum.pending);
                    userWithdrawal.setTransNo(transNo.toString());
                    updateById(userWithdrawal);
                } else {
                    log.error("结算调用三方接口失败：user is {}, param is {}, res is {}", user.getId(), JSONObject.toJSONString(withdrawalReq), withdraw);
                    throw new BizException("结算失败");
                }
            }
            return HttpResponseResult.succeed(true);
        } else {
            throw new BizException("结算失败");
        }
    }

    @Override
    public HttpResponseResult<Boolean> batchAuth(AuthOperaReq authOperaReq, SysUser sysUser) {
        List<Long> ids = Arrays.asList(StringUtil.toLongArray(StringPool.COMMA, authOperaReq.getId()));

        //先判断三方余额是否充足
        if (authOperaReq.getPass()) {
            List<UserWithdrawal> userWithdrawals = baseMapper.selectList(Wrappers.<UserWithdrawal>lambdaQuery()
                    .in(UserWithdrawal::getId, ids)
                    .eq(UserWithdrawal::getAuthStatus, AuthStatusEnum.DOING));
            //总提现金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (UserWithdrawal withdrawal : userWithdrawals) {
                if (null != withdrawal.getActualAmount()
                        && BigDecimal.ZERO.compareTo(withdrawal.getActualAmount()) <= 0) {
                    totalAmount = totalAmount.add(withdrawal.getActualAmount());
                }
            }
            BigDecimal useDecimal = withdrawSdk.balanceQuery();
            if (useDecimal.compareTo(totalAmount) < 0) {
                return HttpResponseResult.failed("账户余额不足");
            }
        }

        int successNum = 0;
        String msg = "执行完成!";
        for (Long id : ids) {
            AuthOperaReq param = new AuthOperaReq();
            param.setId(id.toString());
            param.setReason(authOperaReq.getReason());
            param.setPass(authOperaReq.getPass());
            param.setUserId(sysUser.getId());
            try {
                HttpResponseResult<UserWithdrawalVo> res = DistributedLock.of(redissonClient)
                        .runIfLockToFunction(CacheNameEnum.LOCK_WITHDRAWAL.getRedisKey(id.toString())
                                , this::doAuth, param, 10L);
                if (!res.getStatus()) {
                    msg += successNum + "条成功，" + "1条失败，" + (ids.size() - successNum - 1) + "条未执行，失败原因：" + res.getMsg();
                    return HttpResponseResult.failed(msg);
                } else {
                    successNum++;
                }
            } catch (BizException e) {
                msg += successNum + "条成功，" + "1条失败，" + (ids.size() - successNum - 1) + "条未执行，失败原因：" + e.getMessage();
                return HttpResponseResult.failed(msg);
            } catch (Exception e) {
                e.printStackTrace();
                msg += successNum + "条成功，" + "1条失败，" + (ids.size() - successNum - 1) + "条未执行，失败原因：结算失败";
                return HttpResponseResult.failed(msg);
            }
        }
        return HttpResponseResult.succeed();
    }

    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<UserWithdrawalVo> doAuth(AuthOperaReq authOperaReq) {
        UserWithdrawalVo build = detail(Long.parseLong(authOperaReq.getId()));
        if (null == build || !AuthStatusEnum.DOING.equals(build.getAuthStatus())) {
            return HttpResponseResult.succeed();
        }
        build.setAuthStatus(authOperaReq.getPass() ? AuthStatusEnum.PASS : AuthStatusEnum.UNPASS);
        build.setReason(authOperaReq.getReason());
        build.setAuthUserId(authOperaReq.getUserId());
        build.setUpdateTime(new Date());
        build.setAuthTime(new Date());

        SysUser withdrawalUser = sysUserService.findUserById(build.getUserId());
        HttpResponseResult res = HttpResponseResult.succeed(build);
        if (authOperaReq.getPass()) {
            //交易流水号生成
            Long transNo = idGeneratorService.generatorId("withdrawNo");

            HttpResponseResult<Boolean> withdraw = withdrawSdk.withdraw(
                    transNo.toString(), build.getRealName(), build.getPhone(), withdrawalUser.getIdCardNo(),
                    build.getActualAmount().multiply(new BigDecimal("100")).intValue(), build.getBankCard(), null
            );
            if (withdraw.getStatus() && withdraw.getData()) {
                build.setTradeStatus(TradeStatusEnum.pending);
                build.setTransNo(transNo.toString());
            } else {
                build.setTradeStatus(TradeStatusEnum.failed);
                build.setTransNo(transNo.toString());
                build.setErrorMsg(withdraw.getMsg());
                res = HttpResponseResult.failed("结算" + authOperaReq.getId() + "失败，失败原因：" + withdraw.getMsg());

                UserAccountRecordVo detail = accountRecordService.detail(null, AccountBizTypeEnum.WITHDRAWAL, Long.parseLong(authOperaReq.getId()));
                userAccountService.accountChange(detail, PostStatusEnum.CANCEL);

                // 结算失崺，重置为DOING;否则审核流程异常
                build.setAuthStatus(AuthStatusEnum.DOING);
            }
        } else {
            //审核不通过，账户解冻
            UserAccountRecordVo detail = accountRecordService.detail(null, AccountBizTypeEnum.WITHDRAWAL, Long.parseLong(authOperaReq.getId()));
            userAccountService.accountChange(detail, PostStatusEnum.CANCEL);

            //发生审核未通过通知
            unpassSend(build.getUserId(), build.getPhone(), authOperaReq.getReason());
        }
        updateById(build);
        return res;
    }

    @Override
    public HttpResponseResult<Boolean> transferAccount(AuthOperaReq authOperaReq, SysUser user) {
        UserWithdrawalVo detail = detail(Long.parseLong(authOperaReq.getId()));
        if (detail == null) {
            return HttpResponseResult.failed("结算记录不存在");
        }
        if (!AuthStatusEnum.PASS.equals(detail.getAuthStatus())) {
            return HttpResponseResult.failed("结算记录未审核");
        }
        if (TradeStatusEnum.succeeded.equals(detail.getTradeStatus())) {
            return HttpResponseResult.failed("结算已经交易成功");
        }

        //交易流水号生成
        Long transNo = idGeneratorService.generatorId("withdrawNo");

        //不用审核的，需要请求三方
        HttpResponseResult<Boolean> withdraw = withdrawSdk.withdraw(
                transNo.toString(), detail.getRealName(), detail.getPhone(), user.getIdCardNo(),
                detail.getActualAmount().multiply(new BigDecimal("100")).intValue(), detail.getBankCard(), null
        );
        if (withdraw.getStatus() && withdraw.getData()) {
            detail.setTradeStatus(TradeStatusEnum.pending);
            detail.setTransNo(transNo.toString());
            updateById(detail);
            return HttpResponseResult.succeed(true);
        } else {
            log.error("结算调用三方接口失败：user is {}, data is {}, res is {}", user.getId(), JSONObject.toJSONString(detail), withdraw);
            throw new BizException("结算失败");
        }
    }

    @Override
    public UserWithdrawalVo totalAmount() {
        return baseMapper.totalAmount();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void callback(UserWithdrawalCallback callback, String jsonStr) {
        if (StringUtil.isEmpty(callback.getOuterOrderNo()) ||
                StringUtil.isEmpty(callback.getStatus())) {
            log.error("参数异常，参数缺失,param is {}", jsonStr);
            return;
        }
        UserWithdrawalVo detail = detailByTransNo(callback.getOuterOrderNo().trim());
        if (null == detail) {
            log.error("参数异常，未找到交易记录,param is {}", jsonStr);
            return;
        }
        if (!TradeStatusEnum.pending.equals(detail.getTradeStatus())) {
            return;
        }
        if ("1".equals(callback.getStatus())) {
            //交易成功
            detail.setTradeStatus(TradeStatusEnum.succeeded);
            detail.setTradeNo(callback.getOrderNo());
            BigDecimal actualAmount = new BigDecimal(callback.getActualAmount());
            detail.setActualAmount(actualAmount.divide(new BigDecimal("100")));
            detail.setTransferTime(callback.getEndTime());

            //结算成功，账户解冻，入账户明细
            UserAccountRecordVo recordVo = accountRecordService.detail(null, AccountBizTypeEnum.WITHDRAWAL, detail.getId());
            userAccountService.accountChange(recordVo, PostStatusEnum.RECORDED);
            //发生结算成功通知
            successSend(detail.getUserId(), detail.getPhone());
        } else if ("2".equals(callback.getStatus())) {
            //交易失败
            detail.setTradeStatus(TradeStatusEnum.failed);
            detail.setTradeNo(callback.getOrderNo());
            detail.setErrorCode(callback.getErrorCode());
            detail.setErrorMsg(callback.getErrorMsg());

            //结算失败，账户解冻
            UserAccountRecordVo recordVo = accountRecordService.detail(null, AccountBizTypeEnum.WITHDRAWAL, detail.getId());
            userAccountService.accountChange(recordVo, PostStatusEnum.CANCEL);

            //发生结算失败通知
            unpassSend(detail.getUserId(), detail.getPhone(), callback.getErrorMsg());
        } else {
            return;
        }
        detail.setCallbackJson(jsonStr);
        updateById(detail);
    }

    @Override
    public void contractCallback(String status, String serialNo, String url, String errMsg) {
        userContractRecordDao.contractCallbackUpdate(status, serialNo, url, errMsg);
    }

    /**
     * 查询用户今天发起的结算次数
     *
     * @param userId
     * @return
     */
    private Integer getNowDayWithdrawalCount(Long userId) {
        return baseMapper.getNowDayWithdrawalCount(userId);
    }

    private void successSend(Long userId, String phone) {
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, phone);
        try {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TEACHER_WITHDRAW_SUCCESS,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode());
        } catch (Exception e) {
            log.error("老师结算极光消息推送异常,userId={}", userId);
        }
    }

    private void unpassSend(Long userId, String phone, String reason) {
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, phone);
        try {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TEACHER_WITHDRAW_UNPASS,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode(), reason);
        } catch (Exception e) {
            log.error("老师结算极光消息推送异常,userId={}", userId);
        }
    }

    /***
     * 入结算表
     * @author liweifan
     * @param: userId
     * @param: withdrawalReq
     * @param: bankCardVo
     * @param: userAccountRecord
     * @updateTime 2022/4/7 16:46
     */
    private UserWithdrawal insertUserWithdrawal(Long userId, WithdrawalReq withdrawalReq,
                                                UserBankCardVo bankCardVo, BigDecimal withdrawalServiceFee,
                                                String withdrawalAuthSwitch, String withdrawalAuthFee) {
        UserWithdrawal userWithdrawal = new UserWithdrawal();
        userWithdrawal.setUserId(userId);
        userWithdrawal.setAmount(withdrawalReq.getAmountWithdrawal());
        userWithdrawal.setPlantformFee(withdrawalServiceFee);
        userWithdrawal.setActualAmount(withdrawalReq.getAmountWithdrawal().subtract(withdrawalServiceFee));
        userWithdrawal.setBankCardId(bankCardVo.getId());
        userWithdrawal.setOpenType(OpenContractEnum.lingxinpay.getCode());

        if (YesOrNoEnum.NO.getCode().toString().equals(withdrawalAuthSwitch)) {
            userWithdrawal.setAuthStatus(AuthStatusEnum.PASS);
            userWithdrawal.setAuthUserId(0L);
            userWithdrawal.setReason("系统审核通过");
        } else {
            if (new BigDecimal(withdrawalAuthFee).compareTo(withdrawalReq.getAmountWithdrawal()) > 0) {
                userWithdrawal.setAuthStatus(AuthStatusEnum.PASS);
                userWithdrawal.setAuthUserId(0L);
                userWithdrawal.setReason("系统审核通过");
            } else {
                userWithdrawal.setAuthStatus(AuthStatusEnum.DOING);
            }
        }
        userWithdrawal.setCreateTime(new Date());
        userWithdrawal.setUpdateTime(new Date());
        baseMapper.insert(userWithdrawal);
        return userWithdrawal;
    }

    /***
     * 获取平台结算服务费
     * @author liweifan
     * @param: userId
     * @updateTime 2022/4/7 14:59
     * @return: java.math.BigDecimal
     */
    private BigDecimal getWithdrawalServiceFee() {
        BigDecimal withdrawalServiceFee;
        try {
            String configValue = sysConfigService.findConfigValue(SysConfigConstant.WITHDRAWAL_SERVICE_FEE);
            withdrawalServiceFee = new BigDecimal(configValue);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取平台配置失败 key={}", SysConfigConstant.WITHDRAWAL_SERVICE_FEE);
            withdrawalServiceFee = new BigDecimal(0);
        }
        return withdrawalServiceFee;
    }

    /***
     * 获取用户可结算金额
     * @author liweifan
     * @param: userId
     * @param: withdrawalServiceFee
     * @updateTime 2022/4/7 15:02
     * @return: java.math.BigDecimal
     */
    private BigDecimal getAmountUsable(Long userId) {
        //查询用户账户余额
        UserAccountVo detail = userAccountService.detail(userId);
        BigDecimal subtract = detail.getAmountUsable();
        if (subtract.intValue() < 0) {
            subtract = new BigDecimal(0);
        }
        return subtract;
    }


       /* @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(List<ExcelDataReaderProperty<UserWithdrawalExport>> dataList, Long userId) {
        List<ErrMsg> errMsgList = new ArrayList<>();
        dataList.sort(Comparator.comparingInt(ExcelDataReaderProperty::getRowIndex));
        List<UserWithdrawal> userWithdrawalList = new ArrayList<>();
        for (ExcelDataReaderProperty<UserWithdrawalExport> dataReaderProperty : dataList) {
            String errMsg = dataReaderProperty.getErrorMessage();
            if (!StringUtil.isEmpty(errMsg)) {
                errMsgList.add(new ErrMsg(dataReaderProperty.getRowIndex(), errMsg));
                continue;
            }
            UserWithdrawalExport data = dataReaderProperty.getClazz();
            StringBuffer buffer = new StringBuffer(data.getId().toString());
            buffer.append(data.getUserId());
            buffer.append(data.getAmount().setScale(2, RoundingMode.HALF_UP));
            buffer.append(data.getPlantformFee().setScale(2, RoundingMode.HALF_UP));
            buffer.append(data.getActualAmount().setScale(2, RoundingMode.HALF_UP));

            String sign = DigestUtils.md5DigestAsHex(buffer.toString().getBytes());
            if (!data.getSign().equals(sign)) {
                errMsgList.add(new ErrMsg(dataReaderProperty.getRowIndex(), "验签失败"));
                continue;
            }
            if (AuthStatusEnum.PASS.equals(data.getStatus()) && StringUtil.isEmpty(data.getBankFlowNo())) {
                errMsgList.add(new ErrMsg(dataReaderProperty.getRowIndex(), "审核通过时，转账流水号不能为空"));
                continue;
            }
            if (!AuthStatusEnum.DOING.equals(data.getStatus())
                    && StringUtil.isEmpty(data.getVerifyReason())) {
                errMsgList.add(new ErrMsg(dataReaderProperty.getRowIndex(), "审核理由不能为空"));
                continue;
            }
            UserWithdrawal userWithdrawal = new UserWithdrawal();
            userWithdrawal.setId(data.getId());
            userWithdrawal.setBankFlowNo(data.getBankFlowNo());
            userWithdrawal.setStatus(data.getStatus());
            userWithdrawal.setVerifyReason(data.getVerifyReason());

            userWithdrawal.setUpdateTime(new Date());
            userWithdrawalList.add(userWithdrawal);
        }
        if (!CollectionUtils.isEmpty(errMsgList)) {
            throw new ExcelException("导入异常", errMsgList);
        }
        authWithdrawalBancth(userWithdrawalList, userId);
    }*/

    /***
     * 审核
     * @author liweifan
     * @param: userWithdrawalList
     * @updateTime 2022/4/20 11:18
     */
    /*private void authWithdrawalBancth(List<UserWithdrawal> userWithdrawalList, Long userId) {
        for (UserWithdrawal userWithdrawal : userWithdrawalList) {
            UserWithdrawal old = baseMapper.selectById(userWithdrawal.getId());
            if (null == old || !AuthStatusEnum.DOING.equals(old.getStatus()) || AuthStatusEnum.DOING.equals(userWithdrawal.getStatus())) {
                continue;
            }
            userWithdrawal.setUpdateTime(new Date());

            if (AuthStatusEnum.PASS.equals(userWithdrawal.getStatus())) {
                userWithdrawal.setVerifyUserId(userId);

                //审核通过，账户解冻，入账户明细
                UserAccountRecordDto accountRecordDto = new UserAccountRecordDto(
                        old.getUserId(), old.getAmount(), InOrOutEnum.OUT, AccountBizTypeEnum.WITHDRAWAL,
                        userWithdrawal.getId(), "老师结算", null
                );
                accountRecordDto.setFrozenType(FrozenTypeEnum.FROZEN_DEDUCT);
                accountRecordDto.setSaveRecord(true);
                userAccountService.accountChange(accountRecordDto);

                userWithdrawal.setTransferTime(new Date());
            } else if (AuthStatusEnum.UNPASS.equals(userWithdrawal.getStatus())) {
                //审核不通过，账户解冻
                UserAccountRecordDto accountRecordDto = new UserAccountRecordDto(
                        old.getUserId(), old.getAmount(), InOrOutEnum.OUT, AccountBizTypeEnum.WITHDRAWAL,
                        userWithdrawal.getId(), "老师结算", null
                );
                accountRecordDto.setFrozenType(FrozenTypeEnum.FROZEN_BACK);
                accountRecordDto.setSaveRecord(false);
                userAccountService.accountChange(accountRecordDto);
            }
            baseMapper.updateById(userWithdrawal);
        }
    }*/
}