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.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dto.UserAccountRecordDto;
import com.yonge.cooleshow.biz.dal.dto.req.TotalReq;
import com.yonge.cooleshow.biz.dal.entity.PlatformCashAccountRecord;
import com.yonge.cooleshow.biz.dal.entity.UserAccountRecord;
import com.yonge.cooleshow.biz.dal.entity.UserOrder;
import com.yonge.cooleshow.biz.dal.enums.AccountBizTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.GoodTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.InOrOutEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.UserAccountRecordVo;
import com.yonge.cooleshow.biz.dal.vo.res.AccountShareTotal;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.entity.MallOrderItemDto;
import com.yonge.cooleshow.common.enums.CacheNameEnum;
import com.yonge.cooleshow.biz.dal.vo.res.AccountTotal;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.payment.util.DistributedLock;
import com.yonge.toolset.utils.collection.ListUtil;
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.UserAccount;
import com.yonge.cooleshow.biz.dal.vo.UserAccountVo;
import com.yonge.cooleshow.biz.dal.dto.search.UserAccountSearch;
import com.yonge.cooleshow.biz.dal.dao.UserAccountDao;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountDao, UserAccount> implements UserAccountService {
    private final static Logger log = LoggerFactory.getLogger(UserAccountServiceImpl.class);

    @Autowired
    private UserAccountRecordService userAccountRecordService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private UserOrderService orderService;

    @Autowired
    private PlatformCashAccountRecordService platformCashAccountRecordService;

    @Autowired
    private UserOrderService userOrderService;

    @Override
    public UserAccountVo detail(Long id) {
        UserAccountVo detail = baseMapper.detail(id);
        if (null == detail) {
            throw new BizException("用户没有开通账户");
        }
        detail = dealUserAccountVo(detail);
        return detail;
    }

    public UserAccountVo dealUserAccountVo(UserAccountVo detail) {
        detail.setAmountUnrecorded(
                null == detail.getAmountUnrecorded() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : detail.getAmountUnrecorded().setScale(2, RoundingMode.HALF_UP));
        detail.setAmountRecorded(
                null == detail.getAmountRecorded() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : detail.getAmountRecorded().setScale(2, RoundingMode.HALF_UP));
        detail.setAmountTotal(
                null == detail.getAmountTotal() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : detail.getAmountTotal().setScale(2, RoundingMode.HALF_UP));
        detail.setAmountUsable(
                null == detail.getAmountUsable() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : detail.getAmountUsable().setScale(2, RoundingMode.HALF_UP));
        detail.setAmountFrozen(
                null == detail.getAmountFrozen() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : detail.getAmountFrozen().setScale(2, RoundingMode.HALF_UP));
        return detail;
    }

    @Override
    public IPage<UserAccountVo> selectPage(IPage<UserAccountVo> page, UserAccountSearch query) {
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult accountRecord(UserAccountRecordDto accountRecordDto) {
        return accountRecord(Arrays.asList(accountRecordDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult accountRecord(List<UserAccountRecordDto> accountRecordDtos) {
        if (CollectionUtils.isEmpty(accountRecordDtos)) {
            return HttpResponseResult.succeed();
        }
        //0元过滤
        List<UserAccountRecordDto> accountRecords = accountRecordDtos.stream().filter(o ->
                BigDecimal.ZERO.compareTo(o.getTransAmount()) < 0
        ).collect(Collectors.toList());

        //校验参数
        for (UserAccountRecordDto accountRecordDto : accountRecords) {
            if (null == accountRecordDto.getInOrOut()
                    || null == accountRecordDto.getPostStatus()
                    || (!PostStatusEnum.WAIT.equals(accountRecordDto.getPostStatus()) && !PostStatusEnum.FROZEN.equals(accountRecordDto.getPostStatus()))
            ) {
                throw new BizException("记录入账-入账状态异常: param is {}", JSONObject.toJSONString(accountRecordDto));
            }

            if (null == accountRecordDto.getTransAmount() || null == accountRecordDto.getBizId()
                    || null == accountRecordDto.getBizType()) {
                throw new BizException("记录入账-缺少入账参数: param is {}", JSONObject.toJSONString(accountRecordDto));
            }
            if (BigDecimal.ZERO.compareTo(accountRecordDto.getTransAmount()) > 0) {
                if (null == accountRecordDto.getTransAmount() || null == accountRecordDto.getBizId()
                        || null == accountRecordDto.getBizType()) {
                    throw new BizException("记录入账-缺少入账参数: param is {}", JSONObject.toJSONString(accountRecordDto));
                }
                if (BigDecimal.ZERO.compareTo(accountRecordDto.getTransAmount()) < 0) {
                    throw new BizException("记录入账-变动金额不能为负数: param is {}", JSONObject.toJSONString(accountRecordDto));
                }
            }
        }
        //按照不同的账户分组
        Map<Long, List<UserAccountRecordDto>> accountMap = accountRecords.stream().collect(Collectors.groupingBy(UserAccountRecordDto::getAccountId));
        Set<Long> accountIds = accountMap.keySet();

        for (Long accountId : accountIds) {
            List<UserAccountRecordDto> userAccountRecordDtos = accountMap.get(accountId);
            HttpResponseResult<UserAccountRecord> res = DistributedLock.of(redissonClient)
                    .runIfLockToFunction(CacheNameEnum.LOCK_RECORD_ACCOUNT.getRedisKey(accountId)
                            , this::doAccountRecords, userAccountRecordDtos, 10L);
            if (null != res) {
                return res;
            } else {
                throw new BizException("记录入账-插入账户记录失败: param is {}", JSONObject.toJSONString(userAccountRecordDtos));
            }
        }
        return HttpResponseResult.succeed();
    }


    @Transactional(rollbackFor = Exception.class)
    HttpResponseResult doAccountRecords(List<UserAccountRecordDto> accountRecordDtos) {
        if (CollectionUtils.isEmpty(accountRecordDtos)) {
            return HttpResponseResult.succeed();
        }
        Long accountId = accountRecordDtos.get(0).getAccountId();
        //收入入账
        List<UserAccountRecordDto> collectIn = accountRecordDtos.stream().filter(dto -> InOrOutEnum.IN.equals(dto.getInOrOut())).collect(Collectors.toList());
        //支出入账
        List<UserAccountRecordDto> collectOut = accountRecordDtos.stream().filter(dto -> InOrOutEnum.OUT.equals(dto.getInOrOut())).collect(Collectors.toList());

        //******************************************收入***********************************//
        if (!CollectionUtils.isEmpty(collectIn)) {
            //收入按照 业务类型-订单号-入账记录 进行分组
            Map<AccountBizTypeEnum, Map<String, List<UserAccountRecordDto>>> collectInMap = collectIn.stream().collect(
                    Collectors.groupingBy(UserAccountRecordDto::getBizType,
                            Collectors.groupingBy(UserAccountRecordDto::getOrderNo)
                    )
            );

            for (AccountBizTypeEnum bizType : collectInMap.keySet()) {
                Map<String, List<UserAccountRecordDto>> collectBizTypeMap = collectInMap.get(bizType);
                for (String orderNo : collectBizTypeMap.keySet()) {
                    List<UserAccountRecordDto> userAccountRecords = collectBizTypeMap.get(orderNo);
                    //本组入账金额
                    BigDecimal transAmount = BigDecimal.ZERO;
                    //冻结入账金额
                    BigDecimal frozenTransAmount = BigDecimal.ZERO;

                    for (UserAccountRecordDto o : userAccountRecords) {
                        transAmount = transAmount.add(o.getTransAmount());
                        if (PostStatusEnum.FROZEN.equals(o.getPostStatus())) {
                            frozenTransAmount = frozenTransAmount.add(o.getTransAmount());
                        }
                    }
                    if (!checkInOrderAmount(bizType, orderNo, transAmount)) {
                        log.error("记录入账-订单入账金额异常： bizType is {} ,orderNo is {} , transAmount is {} ", bizType.getCode(), orderNo, transAmount);
                        throw new BizException("记录入账-订单入账金额有误");
                    }
                    //冻结入账
                    if (frozenTransAmount.compareTo(BigDecimal.ZERO) > 0) {
                        //有冻结金额入账
                        baseMapper.frozenChangeAccount(accountId, frozenTransAmount, InOrOutEnum.IN.getCode());
                    }
                    //批量入账
                    List<UserAccountRecord> records = ListUtil.convertList(userAccountRecords, UserAccountRecord.class);
                    userAccountRecordService.saveBatch(records);
                }
            }
        }

        //******************************************支出***********************************//
        if (!CollectionUtils.isEmpty(collectOut)) {
            //支出入账金额
            BigDecimal outTransAmount = BigDecimal.ZERO;
            //冻结入账金额
            BigDecimal frozenTransAmount = BigDecimal.ZERO;

            for (UserAccountRecordDto o : collectOut) {
                outTransAmount = outTransAmount.add(o.getTransAmount());
                if (PostStatusEnum.FROZEN.equals(o.getPostStatus())) {
                    frozenTransAmount = frozenTransAmount.add(o.getTransAmount());
                }
            }

            //支出 需要判断所有支出金额不能大于账户余额
            UserAccountVo detail = baseMapper.detail(accountId);

            if (detail.getAmountUsable().compareTo(outTransAmount) < 0) {
                log.error("记录入账-订单入账金额异常： param is {} ", JSONObject.toJSONString(collectOut));
                throw new BizException("记录入账-账户余额不足");
            }
            //冻结入账
            if (frozenTransAmount.compareTo(BigDecimal.ZERO) > 0) {
                //有冻结金额入账
                baseMapper.frozenChangeAccount(accountId, frozenTransAmount, InOrOutEnum.OUT.getCode());
            }
            //批量入账
            List<UserAccountRecord> records = ListUtil.convertList(collectOut, UserAccountRecord.class);
            userAccountRecordService.saveBatch(records);
        }
        return HttpResponseResult.succeed();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<UserAccountRecord> accountChange(UserAccountRecord record, PostStatusEnum postStatus) {
        if (null == postStatus || null == record
                || (!PostStatusEnum.RECORDED.equals(postStatus) && !PostStatusEnum.CANCEL.equals(postStatus))) {
            throw new BizException("入账状态变更, 参数异常: record is {} postStatus is {}", JSONObject.toJSONString(record), postStatus.getCode());
        }
        if (!PostStatusEnum.WAIT.equals(record.getPostStatus())
                && !PostStatusEnum.FROZEN.equals(record.getPostStatus())) {
            return HttpResponseResult.succeed();
        }
        record.setPostStatus(postStatus);
        HttpResponseResult<UserAccountRecord> res = DistributedLock.of(redissonClient)
                .runIfLockToFunction(CacheNameEnum.LOCK_CHANGE_ACCOUNT.getRedisKey(record.getAccountId())
                        , this::doAccountChange, record, 10L);
        if (null != res) {
            return res;
        } else {
            throw new BizException("记录变更-账户记录变更失败: param is {}", JSONObject.toJSONString(record));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public HttpResponseResult<UserAccountRecord> doAccountChange(UserAccountRecord param) {
        //这里需要双重判断，这一次是锁内判断
        UserAccountRecord old = userAccountRecordService.getById(param.getId());
        if (!PostStatusEnum.WAIT.equals(old.getPostStatus())
                && !PostStatusEnum.FROZEN.equals(old.getPostStatus())) {
            return HttpResponseResult.succeed();
        }
        //待入账
        if (PostStatusEnum.WAIT.equals(old.getPostStatus())) {
            if (PostStatusEnum.RECORDED.equals(param.getPostStatus())) {
                //正常入账
                baseMapper.changeAccount(old.getAccountId(), old.getTransAmount(), old.getInOrOut().getCode());
            } else if (PostStatusEnum.CANCEL.equals(param.getPostStatus())) {
                //取消入账
            }
        } else if (PostStatusEnum.FROZEN.equals(old.getPostStatus())) {
            if (PostStatusEnum.RECORDED.equals(param.getPostStatus())) {
                //冻结后正常入账
                baseMapper.frozenDeductChangeAccount(old.getAccountId(), old.getTransAmount(), old.getInOrOut().getCode());
            } else if (PostStatusEnum.CANCEL.equals(param.getPostStatus())) {
                //冻结后取消入账
                baseMapper.frozenBackChangeAccount(old.getAccountId(), old.getTransAmount(), old.getInOrOut().getCode());
            }
        }

        UserAccountVo accountVo = detail(old.getAccountId());
        if (accountVo.getAmountTotal().doubleValue() < 0
                || accountVo.getAmountUsable().doubleValue() < 0 || accountVo.getAmountFrozen().doubleValue() < 0) {
            throw new BizException("账户变更失败");
        }
        //插入账户变更记录
        old.setPostStatus(param.getPostStatus());
        old.setAccountBalance(accountVo.getAmountUsable());
        old.setUpdateTime(new Date());
        userAccountRecordService.updateById(old);
        return HttpResponseResult.succeed(old);
    }

    @Override
    public HttpResponseResult<AccountTotal> accountTotal(TotalReq totalReq) {
        List<AccountTotal> infoList = baseMapper.accountTotal(totalReq.getTimeType().getCode(), totalReq);

        BigDecimal practiceAmount = BigDecimal.ZERO;
        BigDecimal liveAmount = BigDecimal.ZERO;
        BigDecimal videoAmount = BigDecimal.ZERO;
        BigDecimal musicAmount = BigDecimal.ZERO;

        BigDecimal liveShareAmount = BigDecimal.ZERO;
        BigDecimal videoShareAmount = BigDecimal.ZERO;
        BigDecimal musicShareAmount = BigDecimal.ZERO;
        BigDecimal albumShareAmount = BigDecimal.ZERO;
        BigDecimal vipShareAmount = BigDecimal.ZERO;
        BigDecimal mallShareAmount = BigDecimal.ZERO;
        BigDecimal actiRegistShareAmount = BigDecimal.ZERO;

        for (AccountTotal info : infoList) {
            info = dealAccountTotal(info);

            practiceAmount = practiceAmount.add(info.getPracticeAmount());
            liveAmount = liveAmount.add(info.getLiveAmount());
            videoAmount = videoAmount.add(info.getVideoAmount());
            musicAmount = musicAmount.add(info.getMusicAmount());

            liveShareAmount = liveShareAmount.add(info.getLiveShareAmount());
            videoShareAmount = videoShareAmount.add(info.getVideoShareAmount());
            musicShareAmount = musicShareAmount.add(info.getMusicShareAmount());
            albumShareAmount = albumShareAmount.add(info.getAlbumShareAmount());
            vipShareAmount = vipShareAmount.add(info.getVipShareAmount());
            mallShareAmount = mallShareAmount.add(info.getMallShareAmount());
            actiRegistShareAmount = actiRegistShareAmount.add(info.getActiRegistShareAmount());
        }
        AccountTotal total = new AccountTotal();

        total.setTotalInAmount(
                practiceAmount.add(liveAmount).add(videoAmount).add(musicAmount)
                        .add(liveShareAmount).add(videoShareAmount).add(musicShareAmount)
                        .add(vipShareAmount).add(mallShareAmount).add(actiRegistShareAmount).add(albumShareAmount)
        );
        if (total.getTotalInAmount().doubleValue() > 0) {
            total.setPracticeAmount(practiceAmount);
            total.setPracticeRate(total.getPracticeAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setLiveAmount(liveAmount);
            total.setLiveRate(total.getLiveAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setVideoAmount(videoAmount);
            total.setVideoRate(total.getVideoAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setMusicAmount(musicAmount);
            total.setMusicRate(total.getMusicAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setLiveShareAmount(liveShareAmount);
            total.setLiveShareRate(total.getLiveShareAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setVideoShareAmount(videoShareAmount);
            total.setVideoShareRate(total.getVideoShareAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setMusicShareAmount(musicShareAmount);
            total.setMusicShareRate(total.getMusicShareAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setAlbumShareAmount(albumShareAmount);
            total.setAlbumShareRate(total.getAlbumShareAmount()
                                         .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                                         .multiply(new BigDecimal("100")));

            total.setVipShareAmount(vipShareAmount);
            total.setVipShareRate(total.getVipShareAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setMallShareAmount(mallShareAmount);
            total.setMallShareRate(total.getMallShareAmount()
                    .divide(total.getTotalInAmount(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")));

            total.setActiRegistShareAmount(actiRegistShareAmount);
            total.setActiRegistShareRate(
                    BigDecimal.valueOf(100)
                            .subtract(total.getPracticeRate())
                            .subtract(total.getLiveRate())
                            .subtract(total.getVideoRate())
                            .subtract(total.getMusicRate())
                            .subtract(total.getLiveShareRate())
                            .subtract(total.getVideoShareRate())
                            .subtract(total.getAlbumShareRate())
                            .subtract(total.getVipShareRate())
                            .subtract(total.getMallShareRate())
            );
        }
        total.setInfoList(infoList);
        return HttpResponseResult.succeed(total);
    }

    /**
     * 判断是否可以入账
     *
     * @param bizType     入账类型
     * @param orderNo     该笔入账对应订单号
     * @param transAmount 入账金额
     * @return
     */
    private Boolean checkInOrderAmount(AccountBizTypeEnum bizType, String orderNo, BigDecimal transAmount) {
        BigDecimal orderExpectPrice = BigDecimal.ZERO;
        if (AccountBizTypeEnum.MALL_SHARE.equals(bizType)) {
            return true;
        } else {
            UserOrder userOrder = orderService.getOne(Wrappers.<UserOrder>lambdaQuery()
                    .eq(UserOrder::getOrderNo, orderNo));
            if (null == userOrder) {
                return false;
            }
            orderExpectPrice = userOrder.getExpectPrice();
        }

        //收入判断订单金额，所有收入不能大于订单用户付款
        BigDecimal totalTransAmount = baseMapper.totalTransAmountByOrderNo(orderNo);
        if (null == totalTransAmount) {
            totalTransAmount = BigDecimal.ZERO;
        }
        //金额校验失败
        if (totalTransAmount.add(transAmount).compareTo(orderExpectPrice) > 0) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public void mallTeacherRecordState(List<MallOrderItemDto> shareDto) {
        if (CollectionUtils.isEmpty(shareDto)) {
            return;
        }

        for (MallOrderItemDto mallOrderItemDto : shareDto) {
            mallTeacherRecordState(mallOrderItemDto);
        }
    }

    public void mallTeacherRecordState(MallOrderItemDto shareDto) {
        // 平台修改收入状态
        if (shareDto.getStatus().equals(PostStatusEnum.RECORDED)) {
            platformCashAccountRecordService.mallRecordedRecord(shareDto.getProductSkuId(), shareDto.getOrderSn(), AccountBizTypeEnum.MALL.getCode());

        } else if (shareDto.getStatus().equals(PostStatusEnum.CANCEL)) {
            platformCashAccountRecordService.cancelRecord(shareDto.getOrderSn(), AccountBizTypeEnum.MALL.getCode(), shareDto.getProductSkuId());
        }

        // 修改老师分润
        List<UserAccountRecord> list = userAccountRecordService.lambdaQuery()
                .eq(UserAccountRecord::getOrderNo, shareDto.getOrderSn())
                .eq(UserAccountRecord::getBizId, shareDto.getProductSkuId())
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (UserAccountRecord userAccount : list) {
            this.accountChange(userAccount, shareDto.getStatus());
        }
    }


    /**
     * 记录平台收入和用户分润收入
     *
     * @return
     */
    @Override
    @Transactional
    public boolean saveMallAccountRecord(List<MallOrderItemDto> shareDto) {
        if (CollectionUtils.isEmpty(shareDto)) {
            return false;
        }
        for (MallOrderItemDto mallOrderItemDto : shareDto) {
            saveMallAccountRecord(mallOrderItemDto);
        }
        return true;
    }

    @Override
    public HttpResponseResult<AccountShareTotal> accountShareTotal(TotalReq query) {
        return HttpResponseResult.succeed(baseMapper.accountShareTotal(query));
    }

    public void saveMallAccountRecord(MallOrderItemDto shareDto) {
        BigDecimal expectPrice = shareDto.getRealAmount();
        if (expectPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        //平台收入
        PlatformCashAccountRecord platformCashAccountRecord = new PlatformCashAccountRecord(shareDto.getUserId(), expectPrice,
                InOrOutEnum.IN, PostStatusEnum.WAIT, AccountBizTypeEnum.MALL, shareDto.getProductSkuId(), shareDto.getOrderSn(), new Date());

        platformCashAccountRecordService.save(platformCashAccountRecord);

        //分润
        if (null != shareDto.getPromoterId() && !shareDto.getPromoterId().equals(shareDto.getUserId()) && shareDto.getPromoterId() != 0) {
            //获取分润收益费率
            BigDecimal shareFeeRate = userOrderService.getShareFreeByConfigName(SysConfigConstant.MALL_SHARE_FEE);
            if (shareFeeRate.compareTo(BigDecimal.ZERO) > 0) {
                //入老师账户
                BigDecimal shareFee = expectPrice.multiply(shareFeeRate).setScale(2, RoundingMode.HALF_UP);
                if (shareFee.compareTo(BigDecimal.ZERO) <= 0) {
                    return;
                }
                AccountBizTypeEnum bizTypeEnum = AccountBizTypeEnum.MALL_SHARE;
                //插入分润老师账户变更记录-分润老师预收
                HttpResponseResult<UserAccountRecord> recomRecordRes = this.accountRecord(
                        new UserAccountRecordDto(shareDto.getPromoterId(), PostStatusEnum.WAIT, shareFee, InOrOutEnum.IN,
                                bizTypeEnum, shareDto.getProductSkuId(), bizTypeEnum.getMsg(), shareDto.getOrderSn(), shareDto.getUserId()));
                if (recomRecordRes.getStatus()) {
                    //插入平台预支
                    platformCashAccountRecord = new PlatformCashAccountRecord(shareDto.getPromoterId(), shareFee,
                            InOrOutEnum.OUT, PostStatusEnum.WAIT, AccountBizTypeEnum.MALL_SHARE, shareDto.getProductSkuId(), shareDto.getOrderSn(), new Date());
                    platformCashAccountRecordService.save(platformCashAccountRecord);
                }
            }
        }
    }

    public AccountTotal dealAccountTotal(AccountTotal info) {
        if (null == info) {
            info = new AccountTotal();
        }
        info.setTotalInAmount(
                null == info.getTotalInAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getTotalInAmount().setScale(2, RoundingMode.HALF_UP));
        info.setPracticeAmount(
                null == info.getPracticeAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getPracticeAmount().setScale(2, RoundingMode.HALF_UP));
        info.setLiveAmount(
                null == info.getLiveAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getLiveAmount().setScale(2, RoundingMode.HALF_UP));
        info.setVideoAmount(
                null == info.getVideoAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getVideoAmount().setScale(2, RoundingMode.HALF_UP));
        info.setMusicAmount(
                null == info.getMusicAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getMusicAmount().setScale(2, RoundingMode.HALF_UP));

        info.setLiveShareAmount(
                null == info.getLiveShareAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getLiveShareAmount().setScale(2, RoundingMode.HALF_UP));
        info.setVideoShareAmount(
                null == info.getVideoShareAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getVideoShareAmount().setScale(2, RoundingMode.HALF_UP));
        info.setMusicShareAmount(
                null == info.getMusicShareAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getMusicShareAmount().setScale(2, RoundingMode.HALF_UP));
        info.setVipShareAmount(
                null == info.getVipShareAmount() ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getVipShareAmount().setScale(2, RoundingMode.HALF_UP));
        info.setMallShareAmount(
                null == info.getMallShareAmount()? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : info.getMallShareAmount().setScale(2, RoundingMode.HALF_UP));
        return info;
    }

}