package com.ruoyi.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.base.domain.BaseCategory;
import com.ruoyi.base.service.IBaseCategoryService;
import com.ruoyi.common.config.DlRightsConfig;
import com.ruoyi.common.core.domain.DlBaseEntity;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.member.domain.MemberPoints;
import com.ruoyi.member.mapper.MemberPointsMapper;
import com.ruoyi.member.service.IMemberPointsService;
import io.lettuce.core.LMoveArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * 博主积分变动明细Service业务层处理
 *
 * @author pqz
 * @date 2025-03-17
 */
@Service
public class MemberPointsServiceImpl extends ServiceImpl<MemberPointsMapper, MemberPoints> implements IMemberPointsService {
    @Autowired
    private MemberPointsMapper memberPointsMapper;
    @Autowired
    private IBaseCategoryService categoryService;


    /**
     * 分页查询积分变动明细
     *
     * @param userId 用户id
     * @param page   分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ruoyi.member.domain.MemberPoints>
     * @author PQZ
     * @date 15:24 2025/3/29
     **/
    @Override
    public IPage<MemberPoints> queryListPage(Long userId, Page<MemberPoints> page) {
        return memberPointsMapper.queryListPage(userId,page);
    }

    /**
     * 新增积分变动记录
     *
     * @param memberPoints {@link MemberPoints}
     * @author PQZ
     * @date 15:29 2025/3/29
     **/
    @Override
    public void savePoints(MemberPoints memberPoints) {
        if(memberPoints.getFromCode() != null){
            List<BaseCategory> categoryList = categoryService.selectByCode(memberPoints.getFromCode());
            BaseCategory category = categoryList.get(0);
            memberPoints.setPoints(Double.parseDouble(category.getContent()));
            memberPoints.setTitle(category.getTitle());
        }
        //查询当前用户最近变动记录
        LambdaQueryWrapper<MemberPoints> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DlBaseEntity::getDelFlag,0)
                .eq(MemberPoints::getUserId,memberPoints.getUserId())
                .eq(MemberPoints::getStatus,"01")
                .orderByDesc(DlBaseEntity::getCreateTime);
        List<MemberPoints> list = list(lambdaQueryWrapper);
        //如果没有记录则为初始新增
        if (list.isEmpty()) {
            memberPoints.setBalance(memberPoints.getPoints());
        } else {
            //如果有记录则取最新记录中的剩余值进行计算后得出新值
            double oldBalance = list.get(0).getBalance();
            double newBalance;
            if ("1".equals(memberPoints.getType())) {
                newBalance = oldBalance + memberPoints.getPoints();
            } else {
                newBalance = oldBalance - memberPoints.getPoints();
            }
            memberPoints.setBalance(newBalance);
        }
        memberPoints.setStatus("01");
        save(memberPoints);
    }

    /**
     * 获取积分
     *
     * @param userId 用户id
     * @return java.lang.Integer
     * @author PQZ
     * @date 16:11 2025/3/31
     **/
    @Override
    public double getBloggerBalance(Long userId) {
        LambdaQueryWrapper<MemberPoints> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(MemberPoints::getUserId,userId)
                .eq(MemberPoints::getStatus,"01")
                .orderByDesc(DlBaseEntity::getCreateTime);
        List<MemberPoints> list = list(lambdaQueryWrapper);
        if (list.isEmpty()){
            return 0;
        } else {
            return list.get(0).getBalance();
        }
    }

    /**
     * 积分提现
     *
     * @param memberPoints {@link MemberPoints}
     * @author PQZ
     * @date 17:14 2025/4/28
     **/
    @Override
    public void payout(MemberPoints memberPoints) throws Exception {
        if (memberPoints.getPoints()<= 0){
            throw new Exception("无效提现额度");
        }

        Long userId = SecurityUtils.getUserId();
        List<MemberPoints> wayList = getOnWayOrder(userId);
        if (!wayList.isEmpty()){
            throw new Exception("存在未处理完成的提现订单");
        }

        double nowBalance = getBloggerBalance(userId);
        if (memberPoints.getPoints()>nowBalance){
            throw new Exception("当前用户积分余额为"+nowBalance+"您已超出提现额度");
        }

        if (memberPoints.getPoints()> 200){
            throw new Exception("单次最高提现200元");
        }
        memberPoints.setOrderNo(generateOrderId());
        memberPoints.setStatus("02");
        memberPoints.setUserId(userId);
        memberPoints.setTitle("积分提现-"+memberPoints.getPoints());
        memberPoints.setType("2");
        save(memberPoints);
    }

    /**
     * 支付成功回调
     *
     * @param orderNo 订单编号
     * @author PQZ
     * @date 17:29 2025/4/28
     **/
    @Override
    public void payoutCallback(String orderNo,String type) {

        //通过订单编号查询积分记录
        LambdaQueryWrapper<MemberPoints> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(MemberPoints::getOrderNo,orderNo)
                .eq(DlBaseEntity::getDelFlag,0)
                .eq(MemberPoints::getStatus,"02");
        List<MemberPoints> memberPoints = list(lambdaQueryWrapper);
        /*区分微信调用成功和失败*/
        if (!memberPoints.isEmpty()) {
            MemberPoints points = memberPoints.get(0);
            /*防重复处理*/
            double nowBalance = getBloggerBalance(points.getUserId());
            if ("success".equals(type)) {
                points.setBalance(nowBalance - points.getPoints());
                points.setStatus("01");
                updateById(points);
            } else {
                removeById(points);
            }
        }
    }

    /**
     * 查询当前登录用户状态为未体现成功的记录
     * @author PQZ
     * @date 17:52 2025/4/28
     * @param userId 用户id
     * @return java.util.List<com.ruoyi.member.domain.MemberPoints>
    **/
    @Override
    public List<MemberPoints> getOnWayOrder(Long userId){
        LambdaQueryWrapper<MemberPoints> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(MemberPoints::getUserId,userId)
                .eq(MemberPoints::getStatus,"02")
                .eq(DlBaseEntity::getDelFlag,0)
                .orderByDesc(DlBaseEntity::getCreateTime);
        return list(lambdaQueryWrapper);
    }


    private String generateOrderId() {
        // 获取当前时间戳（以秒为单位）
        long timestamp = System.currentTimeMillis() / 1000;
        // 生成3位随机数
        Random random = new Random();
        // 生成范围在100到999之间的随机数
        int randomNum = random.nextInt(900) + 100;
        // 组合成订单编号
        return "JFTX" + timestamp + String.format("%03d", randomNum);
    }
}
