package com.mcwl.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.PageDomain;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.core.redis.RedisCache;
import com.mcwl.common.domain.IdsParam;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.DateUtils;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.memberCenter.domain.Member;
import com.mcwl.memberCenter.domain.MemberLevel;
import com.mcwl.memberCenter.domain.RechargeRecord;
import com.mcwl.memberCenter.service.MemberLevelService;
import com.mcwl.memberCenter.service.MemberService;
import com.mcwl.memberCenter.service.RechargeRecordService;
import com.mcwl.myInvitation.domain.Commission;
import com.mcwl.myInvitation.domain.CommissionRatio;
import com.mcwl.myInvitation.domain.Consume;
import com.mcwl.myInvitation.mapper.ConsumeMapper;
import com.mcwl.myInvitation.service.CommissionRatioService;
import com.mcwl.myInvitation.service.CommissionService;
import com.mcwl.myInvitation.service.ConsumeService;
import com.mcwl.pay.domain.ModelPurchaseRecord;
import com.mcwl.pay.domain.OrderTrade;
import com.mcwl.pay.domain.enums.CommissionRationEnum;
import com.mcwl.pay.domain.vo.IncomeVo;
import com.mcwl.pay.domain.vo.TrendVo;
import com.mcwl.pay.domain.vo.WalletRechargeRecordVo;
import com.mcwl.pay.mapper.ModelPurchaseRecordMapper;
import com.mcwl.pay.mapper.OrderTradeMapper;
import com.mcwl.pay.service.OrderTradeService;
import com.mcwl.resource.domain.ModelImage;
import com.mcwl.resource.domain.ModelProduct;
import com.mcwl.resource.domain.WorkFlow;
import com.mcwl.resource.domain.dto.ProductRes;
import com.mcwl.resource.domain.enums.OrderTypeEnum;
import com.mcwl.resource.service.ModelImageService;
import com.mcwl.resource.service.ModelService;
import com.mcwl.resource.service.WorkFlowService;
import com.mcwl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Author：ChenYan
 * @Project：McWl
 * @Package：com.mcwl.pay.service.impl
 * @Filename：OrderTradeServiceImpl
 * @Description TODO
 * @Date：2025/1/3 14:51
 */
@Service
public class OrderTradeServiceImpl extends ServiceImpl<OrderTradeMapper, OrderTrade> implements OrderTradeService {

    @Autowired
    private OrderTradeMapper orderTradeMapper;
    @Autowired
    private MemberLevelService memberLevelService;

    @Autowired
    private OrderTradeService orderTradeService;

    @Autowired
    private CommissionService commissionService;

    @Autowired
    private ModelPurchaseRecordMapper modelPurchaseRecordMapper;

    @Autowired
    private ConsumeService consumeService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private ModelImageService modelImageService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private CommissionRatioService commissionRatioService;

    @Autowired
    private RechargeRecordService rechargeRecordService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ConsumeMapper consumeMapper;

    private static final Cache<String, Object> USER_LOCKS = CacheBuilder.newBuilder()
            .expireAfterAccess(3, TimeUnit.MINUTES)
            .build();

    @PostConstruct
    public void init() {
        CommissionRatio commissionRatio1 = commissionRatioService.lambdaQuery()
                .eq(CommissionRatio::getType, 0)
                .one();
        CommissionRatio commissionRatio2 = commissionRatioService.lambdaQuery()
                .eq(CommissionRatio::getType, 1)
                .one();
        redisCache.setCacheObject(CommissionRationEnum.COMMISSION_RATION_INVITER_USER.getName(), commissionRatio1.getRatio().toString());
        redisCache.setCacheObject(CommissionRationEnum.COMMISSION_RATION_MERCHANT.getName(), commissionRatio2.getRatio().toString());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void productHandler(ProductRes productRes) {

        Long productUserId = productRes.getProductUserId();
        Long productId = productRes.getProductId();
        Integer productType = productRes.getProductType();

        SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());
        // 获取邀请人id
        Long inviterUserId = sysUser.getInviterUserId();

        if (Objects.equals(productUserId, sysUser.getUserId())) {
            throw new ServiceException("不能购买自己的商品", HttpStatus.SHOW_ERROR_MSG);
        }


        // 邀请者获取的提成
        Map<String, Double> map = new HashMap<>();
        if (productType == 0) {
            map = this.modelOrderHandler(productUserId, productId, sysUser);
        } else if (productType == 1) {
            map = this.workFlowOrderHandler(productUserId, productId, sysUser);
        } else if (productType == 2) {
            map = this.imageOrderHandler(productUserId, productId, sysUser);
        }

        if (map.isEmpty()) {
            throw new ServiceException("商品不存在", HttpStatus.SHOW_ERROR_MSG);
        }

        // 邀请人提成
        Double amount = map.get("amount");
        // 商品价格
        Double price = map.get("price");
        // 保存消费表
        Consume consume = new Consume();
        consume.setUserId(SecurityUtils.getUserId());
        consume.setAmount(price);
        consume.setProductId(productId);
        consume.setType(productType);
        consume.setWallet(sysUser.getWallet());
        consumeService.save(consume);

        //添加购买记录表
        ModelPurchaseRecord modelPurchaseRecord = ModelPurchaseRecord.builder()
                .productId(productId)
                .createTime(consume.getCreateTime())
                .userId(SecurityUtils.getUserId())
                .productType(consume.getType()).build();

        modelPurchaseRecordMapper.insert(modelPurchaseRecord);

        // 通过sysUser获取邀请人id
        if (Objects.isNull(inviterUserId)) {
            return;
        }

        if (amount == 0) {
            return;
        }

        // 保存提成
        this.saveCommission(amount, sysUser);

        // 保存商品收入
        this.saveCommission(price, sysUser);


    }

    @Override
    public TableDataInfo getRecord(PageDomain pageDomain, String productName) {

        Page<OrderTrade> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());

        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<OrderTrade> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderTrade::getUserId, userId)
                .eq(OrderTrade::getProductName, productName)
                .eq(OrderTrade::getPayStatus, 2);

        orderTradeService.page(page, lqw);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(BeanUtil.copyToList(page.getRecords(), WalletRechargeRecordVo.class));
        rspData.setTotal(page.getTotal());
        return rspData;
    }

    /**
     * 获取今日收入
     *
     * @return Double
     */
    @Override
    public Double getTodayIncome() {
        Double todayIncome = redisCache.getCacheObject("income:todayIncome");
        if (Objects.nonNull(todayIncome)) {
            return todayIncome;
        }
        todayIncome = orderTradeMapper.getTodayIncome();
        // 保留小数点后两位
        double doubleValue = new BigDecimal(todayIncome).setScale(2, RoundingMode.HALF_UP).doubleValue();
        redisCache.setCacheObject("income:todayIncome", doubleValue, 10, TimeUnit.MINUTES);
        return doubleValue;
    }

    /**
     * 获取本月收入
     *
     * @return Double
     */
    @Override
    public Double getMonthIncome() {
        Double monthIncome = redisCache.getCacheObject("income:monthIncome");
        if (Objects.nonNull(monthIncome)) {
            return monthIncome;
        }
        monthIncome = orderTradeMapper.getMonthIncome();
        double doubleValue = new BigDecimal(monthIncome).setScale(2, RoundingMode.HALF_UP).doubleValue();
        redisCache.setCacheObject("income:monthIncome", doubleValue, 10, TimeUnit.MINUTES);
        return doubleValue;
    }

    /**
     * 获取本年收入
     *
     * @return Double
     */
    @Override
    public Double getYearIncome() {
        Double yearIncome = redisCache.getCacheObject("income:yearIncome");
        if (Objects.nonNull(yearIncome)) {
            return yearIncome;
        }
        yearIncome = orderTradeMapper.getYearIncome();
        double doubleValue = new BigDecimal(yearIncome).setScale(2, RoundingMode.HALF_UP).doubleValue();
        redisCache.setCacheObject("income:yearIncome", doubleValue, 10, TimeUnit.MINUTES);
        return doubleValue;
    }

    /**
     * 获取总收入
     *
     * @return Double
     */
    @Override
    public Double getTotalIncome() {
        Double totalIncome = redisCache.getCacheObject("income:totalIncome");
        if (Objects.nonNull(totalIncome)) {
            return totalIncome;
        }
        totalIncome = orderTradeMapper.getTotalIncome();
        double doubleValue = new BigDecimal(totalIncome).setScale(2, RoundingMode.HALF_UP).doubleValue();
        redisCache.setCacheObject("income:totalIncome", doubleValue, 1, TimeUnit.MINUTES);
        return doubleValue;
    }

    /**
     * 获取同比
     *
     * @return Double
     */
    @Override
    public Double getYoYTrend() {
        // 生成带年月信息的缓存键
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        String cacheKey = String.format("income:yoyTrend:%d-%02d", currentYear, currentMonth);

        // 尝试从缓存获取
        Double yoyTrend = redisCache.getCacheObject(cacheKey);
        if (Objects.nonNull(yoyTrend)) {
            return yoyTrend;
        }

        // 查询数据库
        Double yearIncome = baseMapper.getIncomeByMonth(currentYear, currentMonth);
        Double lastYearIncome = baseMapper.getIncomeByMonth(currentYear - 1, currentMonth);

        // 检查除零
        if (lastYearIncome == 0.0) {
            return 1.0;
        }

        yoyTrend = (yearIncome - lastYearIncome) / lastYearIncome;
        double doubleValue = new BigDecimal(yoyTrend).setScale(2, RoundingMode.HALF_UP).doubleValue();
        redisCache.setCacheObject(cacheKey, doubleValue, 12, TimeUnit.HOURS);

        return doubleValue;
    }

    /**
     * 获取环比
     *
     * @return Double
     */
    @Override
    public Double getMoMTrend() {
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        String cacheKey = String.format("income:momTrend:%d-%02d", currentYear, currentMonth);

        // 尝试从缓存获取
        Double momTrend = redisCache.getCacheObject(cacheKey);
        if (Objects.nonNull(momTrend)) {
            return momTrend;
        }

        // 查询数据库
        Double month = baseMapper.getIncomeByMonth(currentYear, currentMonth);
        Double lastMonth = baseMapper.getIncomeByMonth(currentYear, currentMonth - 1);

        // 检查除零
        if (lastMonth == 0.0) {
            return 1.0;
        }

        momTrend = (month - lastMonth) / lastMonth;
        // 保留小数点后两位
        double doubleValue = new BigDecimal(momTrend).setScale(2, RoundingMode.HALF_UP).doubleValue();

        redisCache.setCacheObject(cacheKey, doubleValue, 12, TimeUnit.HOURS);

        return doubleValue;
    }

    @Override
    public IncomeVo getIncome() {
        return IncomeVo.builder()
                .todayIncome(this.getTodayIncome())
                .monthIncome(this.getMonthIncome())
                .yearIncome(this.getYearIncome())
                .totalIncome(this.getTotalIncome())
                .build();
    }

    /**
     * 获取收入趋势
     *
     * @return IncomeVo
     */
    @Override
    public TrendVo getTrend() {
        return TrendVo.builder()
                .yoyTrend(this.getYoYTrend())
                .momTrend(this.getMoMTrend())
                .build();
    }

    @Override
    public List<OrderTrade> selectMallProductList(OrderTrade orderTrade) {
        // 创建一个 LambdaQueryWrapper 实例
        LambdaQueryWrapper<OrderTrade> queryWrapper = new LambdaQueryWrapper<>();

        // 使用非空检查来添加查询条件
        if (StringUtils.isNotNull(orderTrade.getCode())) {
            queryWrapper.eq(OrderTrade::getCode, orderTrade.getCode());
        }
        if (StringUtils.isNotNull(orderTrade.getUserId())) {
            queryWrapper.eq(OrderTrade::getUserId, orderTrade.getUserId());
        }
        if (StringUtils.isNotNull(orderTrade.getProductId())) {
            queryWrapper.eq(OrderTrade::getProductId, orderTrade.getProductId());
        }
        if (StringUtils.isNotNull(orderTrade.getProductName())) {
            queryWrapper.like(OrderTrade::getProductName, orderTrade.getProductName());
        }
        if (StringUtils.isNotNull(orderTrade.getUserName())) {
            queryWrapper.eq(OrderTrade::getUserName, orderTrade.getUserName());
        }
        if (StringUtils.isNotNull(orderTrade.getOrderTime())) {
            queryWrapper.eq(OrderTrade::getOrderTime, orderTrade.getOrderTime());
        }
        if (StringUtils.isNotNull(orderTrade.getOrderStatus())) {
            queryWrapper.eq(OrderTrade::getOrderStatus, orderTrade.getOrderStatus());
        }
        if (StringUtils.isNotNull(orderTrade.getPayStatus())) {
            queryWrapper.eq(OrderTrade::getPayStatus, orderTrade.getPayStatus());
        }
        if (StringUtils.isNotNull(orderTrade.getTotalAmount())) {
            queryWrapper.eq(OrderTrade::getTotalAmount, orderTrade.getTotalAmount());
        }
        if (StringUtils.isNotNull(orderTrade.getPaymentAmount())) {
            queryWrapper.eq(OrderTrade::getPaymentAmount, orderTrade.getPaymentAmount());
        }

        return orderTradeMapper.selectList(queryWrapper);
    }


    @Override
    public int insertMallProduct(OrderTrade orderTrade) {
        // 保存订单
        return orderTradeMapper.insert(orderTrade);
    }

    @Override
    public void deleteMallProductByIds(IdsParam ids) {
        orderTradeMapper.deleteBatchIds(ids.getIds());
    }

    @Override
    public int updateMallProduct(OrderTrade orderTrade) {
        return orderTradeMapper.updateById(orderTrade);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderHandler(OrderTrade orderTrade, String suffix, Map<String, String> params) throws ExecutionException {
        Object objLock = USER_LOCKS.get(orderTrade.getCode(), () -> new Object());
        synchronized (objLock) {
            orderTrade = orderTradeService.getById(orderTrade.getId());
            if (orderTrade.getPayStatus() == 2) {
                return;
            }
            String buyerPayAmountStr = params.get("buyer_pay_amount");
            if (buyerPayAmountStr != null && !buyerPayAmountStr.isEmpty()) {
                BigDecimal buyerPayAmount = new BigDecimal(buyerPayAmountStr);
                orderTrade.setPaymentAmount(buyerPayAmount.intValue());
            }

            // 根据订单类型进行处理
            if (OrderTypeEnum.POINTS.getName().equals(suffix)) {
                pointsHandler(orderTrade, params);
            } else if (OrderTypeEnum.MEMBER.getName().equals(suffix)) {
                Long promotionId = redisCache.getCacheObject(params.get("out_trade_no") + "_promotionId");
                memberHandler(orderTrade, promotionId);
                redisCache.deleteObject(params.get("out_trade_no") + "_promotionId");
            } else if (OrderTypeEnum.WALLET.getName().equals(suffix)) {
                walletHandler(orderTrade, params);
            } else {
                throw new RuntimeException("订单类型错误");
            }
            // 处理订单
            this.orderHandler(orderTrade, params);
            // 删除redis缓存
            redisCache.deleteObject(orderTrade.getCode());
        }
    }

    private void pointsHandler(OrderTrade orderTrade, Map<String, String> params) {

        // 获取支付金额
        String amount = params.get("buyer_pay_amount");
        Double points = Double.parseDouble(amount) * 100;
        Long userId = orderTrade.getUserId();
        SysUser user = sysUserService.selectUserById(userId);
        user.setFreePoints(user.getFreePoints() + points);
        sysUserService.updateUser(user);

        // 添加充值记录
        RechargeRecord rechargeRecord = new RechargeRecord();
        rechargeRecord.setUserId(userId);
        rechargeRecord.setGetSource("积分充值");
        rechargeRecord.setCode(orderTrade.getCode());
        rechargeRecord.setAmount(Double.parseDouble(amount));
        rechargeRecord.setPoints(points);
        rechargeRecord.setEffectStartTime(new Date());
        rechargeRecord.setEffectEndTime(DateUtil.endOfMonth(new Date()));
        rechargeRecordService.save(rechargeRecord);


    }

    private void walletHandler(OrderTrade orderTrade, Map<String, String> params) {

        // 获取支付金额
        String amount = params.get("buyer_pay_amount");

        BigDecimal amountBigDecimal = new BigDecimal(amount);

        Long userId = orderTrade.getUserId();
        SysUser user = sysUserService.selectUserById(userId);

        BigDecimal wallet = new BigDecimal(user.getWallet().toString());

        BigDecimal walletDecimal = wallet.add(amountBigDecimal).setScale(2, RoundingMode.HALF_UP);

        user.setWallet(walletDecimal.doubleValue());
        sysUserService.updateUser(user);

        Consume consume = new Consume();
        consume.setUserId(SecurityUtils.getUserId());
        consume.setAmount(Double.parseDouble(amount));
        consume.setType(5);
        consume.setWallet(user.getWallet());
        consumeMapper.insert(consume);

        // 添加充值记录
//        RechargeRecord rechargeRecord = new RechargeRecord();
//        rechargeRecord.setUserId(userId);
//        rechargeRecord.setCode(orderTrade.getCode());
//        rechargeRecord.setAmount(Double.parseDouble(amount));
//        rechargeRecord.setPoints(points);
//        rechargeRecord.setCreateBy(user.getUserName());
//        rechargeRecord.setUpdateBy(user.getUserName());
//        rechargeRecord.setUpdateTime(new Date());
//        rechargeRecordService.save(rechargeRecord);


    }

    private void memberHandler(OrderTrade orderTrade, Long promotionId) {
        Long userId = orderTrade.getUserId();
        Long memberLevelId = orderTrade.getProductId();
        String paymentMethod = "aliPay";

        Member userMember = memberService.createUserMember(userId, memberLevelId, paymentMethod, promotionId);

        MemberLevel memberLevel = memberLevelService.getById(memberLevelId);


        // 添加充值记录
        RechargeRecord rechargeRecord = new RechargeRecord();
        rechargeRecord.setUserId(userId);
        rechargeRecord.setGetSource(memberLevel.getMemberName());
        rechargeRecord.setCode(orderTrade.getCode());
        rechargeRecord.setAmount(orderTrade.getPaymentAmount().doubleValue());
        rechargeRecord.setPoints(userMember.getPoints());
        rechargeRecord.setEffectStartTime(new Date());
        rechargeRecord.setEffectEndTime(DateUtil.endOfMonth(new Date()));
        rechargeRecordService.save(rechargeRecord);


    }

    private void orderHandler(OrderTrade orderTrade, Map<String, String> params) {
        // 更新订单状态
        // 支付宝交易凭证号
        orderTrade.setPaymentMethod(params.get("trade_no"));
        orderTrade.setTransactionId(1);
        orderTrade.setOrderTime(DateUtils.parseDate(params.get("gmt_payment")));
        orderTrade.setOrderStatus(2);
        orderTrade.setPayStatus(2);
        String totalAmountStr = params.get("total_amount");
        if (totalAmountStr != null && !totalAmountStr.isEmpty()) {
            BigDecimal totalAmount = new BigDecimal(totalAmountStr);
            orderTrade.setTotalAmount(totalAmount.doubleValue());
        }
        orderTrade.setUpdateTime(new Date());
        orderTradeService.updateById(orderTrade);
    }


    /**
     * 模型订单处理，返回模型金额和邀请人提成
     *
     * @param productUserId 产品用户id
     * @param modelId       模型id
     * @param sysUser       当前用户
     * @return Map<String, Double> 模型金额(price) 邀请人提成(amount)
     */
    protected Map<String, Double> modelOrderHandler(Long productUserId, Long modelId, SysUser sysUser) {
        Consume consume = consumeService.lambdaQuery()
                .eq(Consume::getUserId, sysUser.getUserId())
                .eq(Consume::getProductId, modelId)
                .eq(Consume::getType, 0)
                .one();
        if (Objects.nonNull(consume)) {
            throw new ServiceException("您已经购买过此模型", HttpStatus.SHOW_ERROR_MSG);
        }
        ModelProduct modelProduct = modelService.lambdaQuery()
                .eq(ModelProduct::getId, modelId)
                .eq(ModelProduct::getUserId, productUserId)
                .one();
        if (Objects.isNull(modelProduct)) {
            return new HashMap<>();
        }
        // 获取模型价格
        Double price = modelProduct.getProductPrice();

        return getStringDoubleMap(productUserId, sysUser, price);
    }

    /**
     * 工作流订单处理，返回工作流金额和邀请人提成
     *
     * @param productUserId 产品用户id
     * @param workFlowId    工作流id
     * @param sysUser       当前用户
     * @return Map<String, Double> 工作流金额(price) 邀请人提成(amount)
     */
    protected Map<String, Double> workFlowOrderHandler(Long productUserId, Long workFlowId, SysUser sysUser) {

        Consume consume = consumeService.lambdaQuery()
                .eq(Consume::getUserId, sysUser.getUserId())
                .eq(Consume::getProductId, workFlowId)
                .eq(Consume::getType, 1)
                .one();
        if (Objects.nonNull(consume)) {
            throw new ServiceException("您已经购买过此工作流", HttpStatus.SHOW_ERROR_MSG);
        }


        WorkFlow workFlow = workFlowService.lambdaQuery()
                .eq(WorkFlow::getId, workFlowId)
                .eq(WorkFlow::getUserId, productUserId)
                .one();
        if (Objects.isNull(workFlow)) {
            return new HashMap<>();
        }
        // 获取模型价格
        Double price = workFlow.getProductPrice();

        return getStringDoubleMap(productUserId, sysUser, price);
    }

    /**
     * 图片订单处理，返回图片金额和邀请人提成
     *
     * @param productUserId 产品用户id
     * @param imageId       图片id
     * @param sysUser       当前用户
     * @return Map<String, Double> 图片金额(price) 邀请人提成(amount)
     */
    protected Map<String, Double> imageOrderHandler(Long productUserId, Long imageId, SysUser sysUser) {

        Consume consume = consumeService.lambdaQuery()
                .eq(Consume::getUserId, sysUser.getUserId())
                .eq(Consume::getProductId, imageId)
                .eq(Consume::getType, 3)
                .one();
        if (Objects.nonNull(consume)) {
            throw new ServiceException("您已经购买过此图片", HttpStatus.SHOW_ERROR_MSG);
        }


        ModelImage modelImage = modelImageService.lambdaQuery()
                .eq(ModelImage::getId, imageId)
                .eq(ModelImage::getUserId, productUserId)
                .one();
        if (Objects.isNull(modelImage)) {
            return new HashMap<>();
        }
        // 获取模型价格
        Double price = modelImage.getProductPrice();

        return getStringDoubleMap(productUserId, sysUser, price);
    }


    /**
     * 处理商品、邀请人提成
     *
     * @param productUserId 产品用户id
     * @param sysUser       当前用户
     * @param price         商品价格
     * @return Map<String, Double> 商品价格(price) 邀请人提成(amount)
     */
    protected Map<String, Double> getStringDoubleMap(Long productUserId, SysUser sysUser, Double price) {

        Double wallet = sysUser.getWallet();
        if (wallet < price) {
            throw new ServiceException("钱包余额不足，请充值", HttpStatus.SHOW_ERROR_MSG);
        }

        // 从redis获取提成比例
        // 抽取商家金额比例
        String CommissionRationMerchant = redisCache.getCacheObject(CommissionRationEnum.COMMISSION_RATION_MERCHANT.getName());
        if (Objects.isNull(CommissionRationMerchant)) {
            CommissionRatio commissionRatio = commissionRatioService.lambdaQuery()
                    .eq(CommissionRatio::getType, 1)
                    .one();
            CommissionRationMerchant = commissionRatio.getRatio().toString();
            redisCache.setCacheObject(CommissionRationEnum.COMMISSION_RATION_MERCHANT.getName(), CommissionRationMerchant);
        }

        // 佣金配给邀请者用户比例
        String commissionRationInviterUser = redisCache.getCacheObject(CommissionRationEnum.COMMISSION_RATION_INVITER_USER.getName());
        if (Objects.isNull(commissionRationInviterUser)) {
            CommissionRatio commissionRatio = commissionRatioService.lambdaQuery()
                    .eq(CommissionRatio::getType, 0)
                    .one();
            commissionRationInviterUser = commissionRatio.getRatio().toString();
            redisCache.setCacheObject(CommissionRationEnum.COMMISSION_RATION_INVITER_USER.getName(), commissionRationInviterUser);
        }

        // 将模型价格、抽取商家金额比例、佣金配给邀请者用户比例转换为BigDecimal类型
        BigDecimal priceBigDecimal = new BigDecimal(price.toString());
        BigDecimal rationMerchantBigDecimal = new BigDecimal(CommissionRationMerchant);
        BigDecimal rationInviterUserBigDecimal = new BigDecimal(commissionRationInviterUser);

        // 邀请人获取的金额 = 模型价格 * 抽取商家金额比例 * 邀请人提成比例
        BigDecimal inviterUserAmount = priceBigDecimal
                .multiply(rationMerchantBigDecimal)
                .multiply(rationInviterUserBigDecimal)
                .setScale(2, RoundingMode.HALF_UP);

        // 商家获取的金额 = 模型价格 * (1 - 抽取商家金额比例)
        BigDecimal merchantAmount = priceBigDecimal
                .multiply(new BigDecimal("1.00").subtract(rationMerchantBigDecimal));

        // 通过sysUser获取邀请人id
        if (Objects.nonNull(sysUser.getInviterUserId())) {
            // 更新邀请人钱包金额
            SysUser inviterUser = sysUserService.selectUserById(sysUser.getInviterUserId());
            if (Objects.nonNull(inviterUser)) {
                inviterUser.setWallet(new BigDecimal(inviterUser.getWallet().toString())
                        .add(inviterUserAmount)
                        .setScale(2, RoundingMode.HALF_UP)
                        .doubleValue());
                sysUserService.updateUser(inviterUser);
            }
        }
        // 更新当前用户钱包金额
        sysUser.setWallet(new BigDecimal(sysUser.getWallet().toString())
                .subtract(priceBigDecimal)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue());
        sysUserService.updateUser(sysUser);
        // 更新商家钱包金额
        SysUser merchants = sysUserService.selectUserById(productUserId);
        merchants.setWallet(new BigDecimal(merchants.getWallet().toString())
                .add(merchantAmount)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue());
        sysUserService.updateUser(merchants);


        Map<String, Double> map = new HashMap<>();
        map.put("price", price);
        map.put("amount", inviterUserAmount.doubleValue());

        return map;
    }

    private void saveCommission(double price, SysUser sysUser) {
        Commission commission = new Commission();
        commission.setUserId(sysUser.getInviterUserId());
        commission.setAmount(price);
        commission.setWallet(sysUser.getWallet());
        commissionService.save(commission);
    }


}
