package com.kxs.user.biz.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.kxs.common.core.constant.enums.KindTypeEnum;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.system.api.feign.RemoteOldService;
import com.kxs.user.api.model.*;
import com.kxs.user.api.vo.admin.totalDebt.TotalDebtListVO;
import com.kxs.user.api.vo.kxsapp.totalDebt.TotalDebtDetailVO;
import com.kxs.user.biz.constant.enums.UserErrorTypeEnum;
import com.kxs.user.biz.constant.enums.UserVariationTypeEnum;
import com.kxs.user.biz.mapper.*;
import com.kxs.user.biz.mapper.old.KxsMainServerMapper;
import com.kxs.user.biz.mapper.old.KxsOpServerMapper;
import com.kxs.user.biz.service.KxsPartnerAmountLogService;
import com.kxs.user.biz.service.KxsTotalDebtService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 用户总欠款表(KxsTotalDebt)表服务实现类
 *
 * @author 系统
 * @since 2024-03-22 11:05:40
 */
@Service("kxsTotalDebtService")
@Slf4j
@RequiredArgsConstructor
public class KxsTotalDebtServiceImpl extends ServiceImpl<KxsTotalDebtMapper, KxsTotalDebt> implements KxsTotalDebtService {

    private final KxsUserMapper kxsUserMapper;

    private final KxsLeaderMapper kxsLeaderMapper;

    private final KxsUserAmountMapper kxsUserAmountMapper;

    private final KxsPartnerMapper kxsPartnerMapper;

    private final RemoteOldService remoteOldService;

    private final KxsTotalDebtLogMapper kxsTotalDebtLogMapper;

    private final KxsMainServerMapper kxsMainServerMapper;

    private final KxsOpServerMapper kxsOpServerMapper;

    private final KxsPartnerAmountLogMapper kxsPartnerAmountLogMapper;

    private final KxsLeaderAmountLogMapper kxsLeaderAmountLogMapper;


    @Override
    public IPage<TotalDebtListVO> getByPage(Page<KxsTotalDebt> page, String keyword) {

        return baseMapper.getByPage(page, keyword);
    }

    @Override
    public R addData(KxsTotalDebt param) {
        KxsUser user = kxsUserMapper.selectById(param.getUserId());
        if(user == null){
            return R.failed(UserErrorTypeEnum.USER_NOT_EXIST.getDescription());
        }
        KxsTotalDebt totalDebt = getOne(Wrappers.<KxsTotalDebt>lambdaQuery().eq(KxsTotalDebt::getUserId, param.getUserId()));
        if(totalDebt != null){
            return R.failed(UserErrorTypeEnum.USER_HAS_ADDED_AN_AMOUNT_OWED.getDescription());
        }
        return R.ok(save(param));
    }

    @Override
    public TotalDebtDetailVO detail() {

        Long userId = SecurityUtils.getUser().getId();
        KxsTotalDebt kxsTotalDebt = baseMapper.selectOne(Wrappers.<KxsTotalDebt>lambdaQuery().eq(KxsTotalDebt::getUserId, userId));

        return kxsTotalDebt == null ? null : TotalDebtDetailVO.builder()
                .createTime(kxsTotalDebt.getCreateTime())
                .totalDebt(kxsTotalDebt.getTotalDebt())
                .build();
    }

    @Override
    @DSTransactional(rollbackFor = Exception.class)
    public void deductPartnerAmount(KxsTotalDebt kxsTotalDebt) {
        //执行之前先查询一次
        KxsTotalDebt totalDebt = baseMapper.selectById(kxsTotalDebt.getId());
        if(totalDebt.getTotalDebt().compareTo(BigDecimal.ZERO) <= 0){
            return;
        }
        //查询该创客合伙人/盟主是否有客提现余额，如果大于0则扣除
        KxsPartner kxsPartner = kxsPartnerMapper.selectOne(Wrappers.<KxsPartner>lambdaQuery().eq(KxsPartner::getUserId, kxsTotalDebt.getUserId()));
        if(kxsPartner == null){
            return;
        }
        //合伙人扣除金额
        BigDecimal partnerDeductAmount;
        if(kxsPartner.getWithdrawalAmount().compareTo(BigDecimal.ZERO) > 0){
            //扣除可提现余额
            if(kxsTotalDebt.getTotalDebt().compareTo(kxsPartner.getWithdrawalAmount()) >= 0){
                partnerDeductAmount = kxsPartner.getWithdrawalAmount();
            }else{
                partnerDeductAmount = kxsTotalDebt.getTotalDebt();
            }
            //扣除可提现额度
            kxsPartner.setWithdrawalAmount(NumberUtil.sub(kxsPartner.getWithdrawalAmount(),partnerDeductAmount));
            //扣除运营中心可提现额度
            kxsOpServerMapper.deductMakerUseAmount(kxsPartner);
            //增加运营中心额度日志
            KxsPartnerAmountLog kxsPartnerAmountLog = new KxsPartnerAmountLog();
            kxsPartnerAmountLog.setUserId(kxsTotalDebt.getUserId());
            kxsPartnerAmountLog.setBeforeAmount(NumberUtil.add(kxsPartner.getWithdrawalAmount(),partnerDeductAmount));
            kxsPartnerAmountLog.setAfterAmount(kxsPartner.getWithdrawalAmount());
            kxsPartnerAmountLog.setAmount(partnerDeductAmount);
            kxsPartnerAmountLog.setAfterWithdrawalAmount(kxsPartner.getWithdrawalAmount());
            kxsPartnerAmountLog.setUseWithdrawalAmount(partnerDeductAmount);
            kxsPartnerAmountLog.setKind(KindTypeEnum.SUB.getType());
            kxsPartnerAmountLog.setRemark("预借款项还款");
            kxsPartnerAmountLog.setVariationType(UserVariationTypeEnum.PARTNER_WITHDRAW_BALANCE.getType());
            kxsPartnerAmountLog.setChangeType(21);
            //添加到老库
            kxsOpServerMapper.addAmountLog(kxsPartner, kxsPartnerAmountLog);
            //添加到新库
//            kxsPartnerAmountLogMapper.insert(kxsPartnerAmountLog);
            //扣除成功 增加欠款日志
            BigDecimal afterAmount = NumberUtil.sub(kxsTotalDebt.getTotalDebt(),partnerDeductAmount);
            //添加日志
            KxsTotalDebtLog kxsTotalDebtLog = new KxsTotalDebtLog();
            kxsTotalDebtLog.setKind(KindTypeEnum.SUB.getType());
            kxsTotalDebtLog.setUserId(kxsTotalDebt.getUserId());
            kxsTotalDebtLog.setRemark("扣除合伙人可提现余额");
            kxsTotalDebtLog.setCreateBy("系统");
            kxsTotalDebtLog.setAmount(partnerDeductAmount);
            kxsTotalDebtLog.setAfterAmount(afterAmount);
            kxsTotalDebtLog.setBeforeAmount(kxsTotalDebt.getTotalDebt());
            kxsTotalDebtLogMapper.insert(kxsTotalDebtLog);

            kxsTotalDebt.setTotalDebt(afterAmount);
            baseMapper.updateById(kxsTotalDebt);
            log.info("扣除合伙人:{}可提现额度:{}", kxsPartner.getUserId(), partnerDeductAmount);

        }
    }
    @Override
    @DSTransactional(rollbackFor = Exception.class)
    public void deductLeaderAmount(KxsTotalDebt kxsTotalDebt) {

        KxsTotalDebt totalDebt = baseMapper.selectById(kxsTotalDebt.getId());
        if(totalDebt.getTotalDebt().compareTo(BigDecimal.ZERO) <= 0){
            return;
        }
        //查询该创客合伙人/盟主是否有客提现余额，如果大于0则扣除
        KxsLeader kxsLeader = kxsLeaderMapper.selectOne(Wrappers.<KxsLeader>lambdaQuery().eq(KxsLeader::getUserId, kxsTotalDebt.getUserId()));
        if(kxsLeader == null){
            return;
        }
        KxsUserAmount userAmount = kxsUserAmountMapper.selectOne(Wrappers.<KxsUserAmount>lambdaQuery().eq(KxsUserAmount::getUserId, kxsTotalDebt.getUserId()));
        //合伙人扣除金额
        BigDecimal leaderDeductAmount;
        if(userAmount != null && userAmount.getLeaderBalanceAmount().compareTo(BigDecimal.ZERO) > 0){
            //扣除可提现余额
            if(kxsTotalDebt.getTotalDebt().compareTo(userAmount.getLeaderBalanceAmount()) >= 0){
                leaderDeductAmount = userAmount.getLeaderBalanceAmount();
            }else{
                leaderDeductAmount = kxsTotalDebt.getTotalDebt();
            }
            //扣除盟主可提现额度
            userAmount.setLeaderBalanceAmount(NumberUtil.sub(userAmount.getLeaderBalanceAmount(),leaderDeductAmount));
            kxsMainServerMapper.deductMakerUseAmount(userAmount);
            //添加盟主扣除日志
            KxsLeaderAmountLog kxsLeaderAmountLog = new KxsLeaderAmountLog();
            kxsLeaderAmountLog.setUserId(kxsTotalDebt.getUserId());
            kxsLeaderAmountLog.setRemark("预借款项还款");
            kxsLeaderAmountLog.setBeforeAmount(NumberUtil.add(userAmount.getLeaderBalanceAmount(), leaderDeductAmount));
            kxsLeaderAmountLog.setAfterAmount(userAmount.getLeaderBalanceAmount());
            kxsLeaderAmountLog.setBeforeWithdrawalAmount(NumberUtil.add(userAmount.getLeaderBalanceAmount(), leaderDeductAmount));
            kxsLeaderAmountLog.setAfterWithdrawalAmount(userAmount.getLeaderBalanceAmount());
            kxsLeaderAmountLog.setAmount(leaderDeductAmount);
            kxsLeaderAmountLog.setUseWithdrawalAmount(leaderDeductAmount);
            kxsLeaderAmountLog.setKind(KindTypeEnum.SUB.getType());
            kxsLeaderAmountLog.setVariationType(UserVariationTypeEnum.LEADER_WITHDRAW_BALANCE.getType());
            kxsLeaderAmountLog.setChangeType(342);
            //添加到老库
            kxsMainServerMapper.addAmountLog(kxsLeaderAmountLog);
            //添加到新库
//            kxsLeaderAmountLogMapper.insert(kxsLeaderAmountLog);

            //扣除盟主余额成功
            BigDecimal afterAmount = kxsTotalDebt.getTotalDebt().subtract(leaderDeductAmount);

            //添加欠款日志
            KxsTotalDebtLog kxsTotalDebtLog = new KxsTotalDebtLog();
            kxsTotalDebtLog.setKind(KindTypeEnum.SUB.getType());
            kxsTotalDebtLog.setUserId(kxsTotalDebt.getUserId());
            kxsTotalDebtLog.setRemark("扣除盟主可提现余额");
            kxsTotalDebtLog.setCreateBy("系统");
            kxsTotalDebtLog.setAmount(leaderDeductAmount);
            kxsTotalDebtLog.setAfterAmount(afterAmount);
            kxsTotalDebtLog.setBeforeAmount(kxsTotalDebt.getTotalDebt());
            kxsTotalDebtLogMapper.insert(kxsTotalDebtLog);

            kxsTotalDebt.setTotalDebt(afterAmount);
            baseMapper.updateById(kxsTotalDebt);
            log.info("扣除盟主:{}可提现额度:{}", kxsTotalDebt.getUserId(), leaderDeductAmount);
        }
    }

}

