package com.cyl.h5.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.config.AESForWeixinGetPhoneNumber;
import com.cyl.h5.pojo.dto.H5LoginDTO;
import com.cyl.h5.pojo.request.*;
import com.cyl.h5.pojo.response.RegisterResponse;
import com.cyl.h5.pojo.response.ValidatePhoneResponse;
import com.cyl.h5.pojo.response.H5LoginResponse;
import com.cyl.h5.pojo.vo.H5OrderVO;
import com.cyl.manager.marketing.domain.WechatMemberCoupon;
import com.cyl.manager.marketing.domain.WechatStock;
import com.cyl.manager.marketing.pojo.SendCouponRequest;
import com.cyl.manager.oms.domain.Order;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.domain.MemberLogininfor;
import com.cyl.manager.ums.domain.MemberWechat;
import com.cyl.manager.ums.mapper.MemberLogininforMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.mapper.MemberWechatMapper;
import com.cyl.manager.ums.pojo.vo.MemberV2VO;
import com.cyl.manager.ums.pojo.vo.MemberVO;
import com.cyl.manager.ums.service.MemberLogininforService;
import com.cyl.manager.ums.service.MemberWechatService;
import com.cyl.wechat.WechatAuthService;
import com.cyl.wechat.response.WechatUserAuth;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.MemberLevel;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class H5MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private WechatAuthService wechatAuthService;


    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private MemberWechatMapper memberWechatMapper;

    @Autowired
    private MemberWechatService memberWechatService;

    @Autowired
    private MemberLogininforService memberLogininforService;

    @Autowired
    private H5MemberCouponService h5MemberCouponService;

    @Autowired
    private MemberLogininforMapper memberLogininforMapper;

    @Autowired
    private  H5OrderService h5OrderService;

    @Autowired
    private  H5CouponService h5CouponService;

    private static List<BigDecimal> levelAmountList = new ArrayList<>();

    private static  Map<Integer,BigDecimal> levelAmountMap = new HashMap<>();

    /**
     * 注册
     * @param request 注册请求体
     * @return 结果
     */
    @Transactional
    public RegisterResponse register(RegisterRequest request){
        LocalDateTime optDate = LocalDateTime.now();
        RegisterResponse response = new RegisterResponse();
        //校验验证码
        //TODO 去掉验证码校验
        //this.validateVerifyCode(request.getUuid(), request.getMobile(), request.getCode());
        //创建会员
        Member member = new Member();
        member.setPhoneEncrypted(AesCryptoUtils.encrypt(aesKey, request.getMobile()));
        member.setPhoneHidden(PhoneUtils.hidePhone(request.getMobile()));
        member.setPassword(SecurityUtils.encryptPassword(request.getPassword()));
        member.setNickname("用户" + request.getMobile().substring(7,11));
        member.setStatus(Constants.MEMBER_ACCOUNT_STATUS.NORMAL);
        member.setGender(0);
        member.setCreateTime(optDate);
       int rows = memberMapper.insert(member);
       if (rows < 1){
           throw new RuntimeException("注册失败，请重试");
       }
       //调用微信授权业务拿到openId等
        WechatUserAuth userToken = wechatAuthService.getUserToken(request.getWechatCode());
       if (userToken == null){
           throw new RuntimeException("授权失败，请重试");
       }
        MemberWechat memberWechat = new MemberWechat();
        memberWechat.setMemberId(member.getId());
        memberWechat.setOpenid(userToken.getOpenid());
        memberWechat.setAccessToken(userToken.getAccess_token());
        memberWechat.setExpiresIn(userToken.getExpires_in());
        memberWechat.setRefreshToken(userToken.getRefresh_token());
        memberWechat.setCreateTime(optDate);
        memberWechat.setCreateBy(member.getId());
        rows = memberWechatMapper.insert(memberWechat);
        if (rows < 1){
            throw new RuntimeException("注册失败，请重试");
        }
        //注册成功直接返回token了
        H5LoginResponse loginResponse = getLoginResponse(member.getId());
        response.setToken(loginResponse.getToken());
        return response;
    }

    public ValidatePhoneResponse validate(String phone) {
        ValidatePhoneResponse response = new ValidatePhoneResponse();
        byte[] decodedBytes = Base64.getDecoder().decode(phone);
        phone = new String(decodedBytes);
        QueryWrapper<Member> qw = new QueryWrapper<>();
        qw.eq("phone_encrypted", AesCryptoUtils.encrypt(aesKey, phone));
        Member member = memberMapper.selectOne(qw);
        if (member != null){
            throw new RuntimeException("该手机号已被占用");
        }
        response.setIfSuccess(true);
        response.setMessage("该手机号可用");
        return response;
    }

    /**
     * 账号密码登录
     * @param data
     * @return
     */
    public H5LoginResponse accountLogin(String data) {
        if (StringUtils.isEmpty(data)){
            throw new RuntimeException(Constants.LOGIN_INFO.WRONG);
        }
        // 解码 转 对象
        H5AccountLoginRequest request = JSON.parseObject(new String(Base64Utils.decodeFromString(data)), H5AccountLoginRequest.class);
        log.info("account login request:{}", JSONUtil.toJsonStr(request));
        QueryWrapper<Member> qw = new QueryWrapper<>();
        qw.eq("phone_encrypted", AesCryptoUtils.encrypt(aesKey, request.getMobile()));
        Member member = memberMapper.selectOne(qw);
        if (member == null){
            throw new RuntimeException(Constants.LOGIN_INFO.WRONG);
        }
        validateMemberStatus(member);
        //check 密码
        if (!SecurityUtils.matchesPassword(request.getPassword(), member.getPassword())){
            throw new RuntimeException(Constants.LOGIN_INFO.WRONG);
        }
        return getLoginResponse(member.getId());
    }

    public H5LoginResponse smsLogin(String data){
        LocalDateTime optDate = LocalDateTime.now();
        if (StringUtils.isEmpty(data)){
            throw new RuntimeException(Constants.LOGIN_INFO.WRONG);
        }
        H5SmsLoginRequest request = JSON.parseObject(new String(Base64Utils.decodeFromString(data)), H5SmsLoginRequest.class);
        //校验验证码
        this.validateVerifyCode(request.getUuid(), request.getMobile(), request.getCode());
        //查会员
        QueryWrapper<Member> qw = new QueryWrapper<>();
        qw.eq("phone_encrypted", AesCryptoUtils.encrypt(aesKey, request.getMobile()));
        Member member = memberMapper.selectOne(qw);
        if (member == null){
            //新会员，注册并登录
            member = new Member();
            member.setPhoneEncrypted(AesCryptoUtils.encrypt(aesKey, request.getMobile()));
            member.setPhoneHidden(PhoneUtils.hidePhone(request.getMobile()));
            member.setNickname("用户" + request.getMobile().substring(7,11));
            member.setStatus(Constants.MEMBER_ACCOUNT_STATUS.NORMAL);
            member.setGender(0);
            member.setCreateTime(optDate);
            int rows = memberMapper.insert(member);
            if (rows < 1){
                throw new RuntimeException("注册失败，请重试");
            }
            MemberWechat memberWechat = new MemberWechat();
            memberWechat.setMemberId(member.getId());
            if (request.getAuthInfo() != null){
                memberWechat.setOpenid(request.getAuthInfo().getOpenid());
                memberWechat.setAccessToken(request.getAuthInfo().getAccess_token());
                memberWechat.setExpiresIn(request.getAuthInfo().getExpires_in());
                memberWechat.setRefreshToken(request.getAuthInfo().getRefresh_token());
            }
            if (StringUtils.isNotEmpty(request.getMpOpenId())){
                memberWechat.setRoutineOpenid(request.getMpOpenId());
            }
            memberWechat.setCreateTime(optDate);
            memberWechat.setCreateBy(member.getId());
            rows = memberWechatMapper.insert(memberWechat);
            if (rows < 1){
                throw new RuntimeException("注册失败，请重试");
            }
        }else {
            //校验会员状态
            validateMemberStatus(member);
            //判断小程序openid是否插入
            if (StringUtils.isNotEmpty(request.getMpOpenId()) || request.getAuthInfo() != null){
                QueryWrapper<MemberWechat> queryWrapper = new QueryWrapper();
                queryWrapper.eq("member_id",member.getId());
                MemberWechat memberWechat = memberWechatMapper.selectOne(queryWrapper);
                Boolean update = false;
                if (StringUtils.isNotEmpty(request.getMpOpenId()) && StringUtils.isEmpty(memberWechat.getRoutineOpenid())) {
                    memberWechat.setRoutineOpenid(request.getMpOpenId());
                    update = true;
                }
                if (request.getAuthInfo() != null && StringUtils.isEmpty(memberWechat.getOpenid())) {
                    memberWechat.setOpenid(request.getAuthInfo().getOpenid());
                    memberWechat.setAccessToken(request.getAuthInfo().getAccess_token());
                    memberWechat.setExpiresIn(request.getAuthInfo().getExpires_in());
                    memberWechat.setRefreshToken(request.getAuthInfo().getRefresh_token());
                    update = true;
                }
                if (update){
                    memberWechatMapper.updateById(memberWechat);
                }
            }
        }

        return getLoginResponse(member.getId());
    }

    /**
     * 校验会员状态
     * @param member 会员信息
     */
    private void validateMemberStatus(Member member) {
        if (Constants.MEMBER_ACCOUNT_STATUS.FORBIDDEN == member.getStatus()){
            throw new RuntimeException(Constants.LOGIN_INFO.FORBIDDEN);
        }
    }

    /**
     * 校验验证码有效性
     * @param uuid 唯一标识
     * @param phone 手机号
     * @param inputCode 输入的验证码
     */
    private void validateVerifyCode(String uuid, String phone, String inputCode){
        String key = uuid + "_" + phone;
        String redisCode = redisCache.getCacheObject(key);
        if (redisCode ==  null){
            throw new RuntimeException(Constants.VERIFY_CODE_INFO.EXPIRED);
        }else if (!redisCode.equals(inputCode)){
            throw new RuntimeException(Constants.VERIFY_CODE_INFO.WRONG);
        }
        //删除缓存
        redisCache.deleteObject(key);
    }

    /**
     * 封装登录响应
     * @param memberId 登录会员id
     * @return 结果
     */
    public H5LoginResponse getLoginResponse(Long memberId){
        LoginMember loginMember = new LoginMember();
        loginMember.setMemberId(memberId);
        String token = tokenService.createMemberToken(loginMember);
        //record登录
        this.insert(memberId);
        H5LoginResponse response = new H5LoginResponse();
        response.setToken(token);
        return response;
    }

    public MemberVO getMemberInfo() {
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        MemberVO memberVO = new MemberVO();
        BeanUtils.copyProperties(member, memberVO);
        memberVO.setPhone(AesCryptoUtils.decrypt(aesKey, member.getPhoneEncrypted()));
        QueryWrapper<MemberWechat> qw = new QueryWrapper<>();
        qw.eq("member_id", member.getId());
        MemberWechat memberWechat = memberWechatMapper.selectOne(qw);
        memberVO.setOpenId(memberWechat.getOpenid());
        return memberVO;
    }

    public WechatUserAuth getWechatUserAuth(String data) {
        BindOpenIdRequest request = JSON.parseObject(new String(Base64Utils.decodeFromString(data)), BindOpenIdRequest.class);
        WechatUserAuth userToken = wechatAuthService.getUserToken(request.getCode());
        if (userToken == null){
            log.error("微信授权失败");
            throw new RuntimeException("授权失败，请重试");
        }
        return userToken;
    }

    public void setWechatInfo(String data) {
        WechatUserAuth authInfo = JSON.parseObject(new String(Base64Utils.decodeFromString(data)), WechatUserAuth.class);
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        UpdateWrapper<MemberWechat> wrapper = new UpdateWrapper<>();
        wrapper.eq("member_id", member.getId());
        wrapper.set("openid", authInfo.getOpenid());
        wrapper.set("access_token", authInfo.getAccess_token());
        wrapper.set("expires_in", authInfo.getExpires_in());
        wrapper.set("refresh_token", authInfo.getRefresh_token());
        wrapper.set("update_time", LocalDateTime.now());
        wrapper.set("update_by", member.getId());
        memberWechatMapper.update(null, wrapper);
    }

    /**
     * 新增会员登录记录
     *
     * @param memberId 会员id
     * @return 结果
     */
    public void insert(Long memberId) {
        Member member = memberMapper.selectById(memberId);
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        MemberLogininfor memberLogininfor = new MemberLogininfor();
        memberLogininfor.setMemberId(memberId);
        memberLogininfor.setPhone(member.getPhoneHidden());
        memberLogininfor.setOs(userAgent.getOperatingSystem().getName());
        memberLogininfor.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        memberLogininfor.setBrowser(userAgent.getBrowser().getName());
        memberLogininfor.setLoginLocation(AddressUtils.getRealAddressByIP(memberLogininfor.getIpaddr()));
        memberLogininfor.setLoginTime(LocalDateTime.now());
        memberLogininforMapper.insert(memberLogininfor);
    }

    public H5LoginResponse wechatLogin(H5LoginDTO params) throws Exception {
        String openId = params.getOpenId();
        String sessionKey = params.getSessionKey();
        //解密手机号
        String mobile = getMobile(sessionKey, params.getKey(), params.getData());
        if(StringUtils.isEmpty(mobile)) {
            throw new Exception("登录异常");
        }
        Member member = createOrUpdateMember(openId,mobile, null);
        return getLoginResponse(member.getId());
    }

    public Member createOrUpdateMember(String openId,String mobile, String wechatId){
        //openid为唯一标识，先查询该微信号是否下过单
        QueryWrapper<MemberWechat> queryMemberWechatWrapper = new QueryWrapper<>();
        queryMemberWechatWrapper.eq("routine_openid", openId);
        MemberWechat memberWechatExist = memberWechatMapper.selectOne(queryMemberWechatWrapper);
        Member member = null;
        if (memberWechatExist != null) {
            member = memberMapper.selectById(memberWechatExist.getMemberId());
        } else {
            //查会员
            QueryWrapper<Member> qw = new QueryWrapper<>();
            qw.eq("phone_encrypted", AesCryptoUtils.encrypt(aesKey, mobile));
            member = memberMapper.selectOne(qw);
        }

        if (member == null){
            //新会员，注册并登录
            member = new Member();
            member.setPhoneEncrypted(AesCryptoUtils.encrypt(aesKey, mobile));
            member.setPhoneHidden(PhoneUtils.hidePhone(mobile));
            member.setNickname("用户" + mobile.substring(7,11));
            member.setStatus(Constants.MEMBER_ACCOUNT_STATUS.NORMAL);
            member.setGender(0);
            member.setCreateTime(LocalDateTime.now());
            int rows = memberMapper.insert(member);
            if (rows < 1){
                throw new RuntimeException("注册失败，请重试");
            }
            if (wechatId == null) {
                MemberWechat memberWechat = new MemberWechat();
                memberWechat.setMemberId(member.getId());
                memberWechat.setRoutineOpenid(openId);
                memberWechat.setWechatId(wechatId);
                memberWechat.setCreateTime(LocalDateTime.now());
                memberWechat.setCreateBy(member.getId());
                rows = memberWechatMapper.insert(memberWechat);
                if (rows < 1){
                    throw new RuntimeException("注册失败，请重试");
                }
            }

            //发放注册优惠券
            SendCouponRequest sendCouponRequest = new SendCouponRequest();

            WechatStock wechatStock = h5CouponService.selectWechatStockByName("新客8.5折优惠");

            if (wechatStock != null) {
                sendCouponRequest.setPhone(mobile);
                sendCouponRequest.setStockId(wechatStock.getId());
                h5CouponService.sendCoupon(sendCouponRequest);
            }
        } else {
            QueryWrapper<MemberWechat> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", member.getId());
            MemberWechat memberWechat = memberWechatMapper.selectOne(queryWrapper);
            if (StringUtils.isEmpty(memberWechat.getRoutineOpenid())) {
                memberWechat.setRoutineOpenid(openId);
                memberWechat.setWechatId(wechatId);
                memberWechatMapper.updateById(memberWechat);
            }
        }
        return member;
    }

    private String getMobile(String sessionKey, String key, String data) {
        AESForWeixinGetPhoneNumber aes = new AESForWeixinGetPhoneNumber(data, sessionKey, key);
        JSONObject decrypt = aes.decrypt();
        if (decrypt != null) {
            return decrypt.getString("phoneNumber");
        }
        return null;
    }

    public MemberV2VO getMemberInfoV2(){
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        if(ObjectUtil.isNull(member)){
            return null;
        }
        MemberV2VO memberV2VO = new MemberV2VO();
        MemberWechat memberWechat =  memberWechatService.selectByMemberId(member.getId());
        BeanUtils.copyProperties(member, memberV2VO);
        memberV2VO.setPhone(AesCryptoUtils.decrypt(aesKey, member.getPhoneEncrypted()));
        memberV2VO.setOpenId(memberWechat.getRoutineOpenid());
        memberV2VO.setLevel(MemberLevel.getName(member.getLevel()));
        memberV2VO.setLevelKey(member.getLevel());
        /**
         * 1、个人信息（等级、名字、头像）
         * 2、自然年累计消费金额、等级升级规则（放参数表）
         * 3、获取积分，集点，卡券数量
         * 4、获取当前订单详情（最新订单）
         */

        //获取卡券数量 通过手机号获取卡券数量
        H5MemberCouponRequest h5MemberCouponRequest = new H5MemberCouponRequest();
        h5MemberCouponRequest.setPhone(memberV2VO.getPhone());
        h5MemberCouponRequest.setOpenId(memberV2VO.getOpenId());
        List<WechatMemberCoupon> list = h5MemberCouponService.selectMemberCouponList(h5MemberCouponRequest);
        if(CollectionUtils.isEmpty(list)){
            memberV2VO.setCoupon(BigDecimal.ZERO);
        }else{
            memberV2VO.setCoupon(new BigDecimal(list.size()));
        }

        //自然年累计消费金额、等级升级规则（放参数表）
        //根据memberId查询所有有效订单
        List<Order> orderList =  h5OrderService.getAllOrderByMemberId(memberV2VO.getId());
        BigDecimal currentYearOrderAmount = BigDecimal.ZERO;
        if(!CollectionUtils.isEmpty(orderList)){
            // 获取当前年份
            int currentYear = Year.now().getValue();
            // 过滤出 paymentTime 在今年的订单，并统计 payAmount 之和
            currentYearOrderAmount = orderList.stream()
                    .filter(order -> order.getPaymentTime() != null &&
                            order.getPaymentTime().getYear() == currentYear)
                    .map(Order::getPayAmount) // 获取支付金额
                    .filter(amount -> amount != null) // 过滤掉 null 值
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 统计金额之和
        }
        memberV2VO.setCurrentYearOrderAmount(currentYearOrderAmount);
        memberV2VO.setOrderNumber(orderList.size());

         // 获取当前订单详情（最新订单）
        Optional<Order> latestOrder = orderList.stream()
                .filter(order -> order.getPaymentTime() != null) // 确保 paymentTime 不为 null
                .max(Comparator.comparing(Order::getPaymentTime)); // 按 paymentTime 排序并找出最大值
        Order order =  null;
        // 检查是否找到订单并打印信息
        if (latestOrder.isPresent()) {
            order = latestOrder.get();
        }
        if(!ObjectUtil.isEmpty(order)){
            H5OrderVO h5OrderVO = h5OrderService.orderDetail(order.getId());
            memberV2VO.setH5OrderVO(h5OrderVO);
        }
        computeConsumptionAndPromotion(currentYearOrderAmount,memberV2VO);

        //获取进度条数据
        String rule = sysConfigService.selectConfigByKey("member.level.rule");
        // 将 JSON 字符串转换为 List
        if(CollectionUtils.isEmpty(levelAmountList)){
            convertJsonToList(rule);
        }
        Map<String,String> result  =  getProgressData(currentYearOrderAmount);
        memberV2VO.setProcess(result.get("progressPercentage"));
        memberV2VO.setNextLevel(result.get("nextLevel"));
        memberV2VO.setAmountNeeded(result.get("amountNeeded"));


        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取当前年的第一天
        LocalDate firstDayOfCurrentYear = today.withDayOfYear(1);
        // 获取下一年的第一天
        LocalDate firstDayOfNextYear = firstDayOfCurrentYear.plusYears(1);
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String formattedNextYear = firstDayOfNextYear.format(formatter);
        memberV2VO.setPromotionDate(formattedNextYear);
        return memberV2VO;
    }

    private void computeConsumptionAndPromotion(BigDecimal currentYearOrderAmount, MemberV2VO memberV2VO) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取当前年的第一天
        LocalDate firstDayOfCurrentYear = today.withDayOfYear(1);
        // 获取下一年的第一天
        LocalDate firstDayOfNextYear = firstDayOfCurrentYear.plusYears(1);
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        // 格式化日期
        String formattedCurrentYear = firstDayOfCurrentYear.format(formatter);
        String formattedNextYear = firstDayOfNextYear.format(formatter);

        int[] consumptionAndPromotion =  evaluateOrderAmount(currentYearOrderAmount);
        Integer  level = consumptionAndPromotion[0]+1;
        int promotionAmount = consumptionAndPromotion[1];

        String consumption = "累计消费"+currentYearOrderAmount+"元("+formattedCurrentYear+"起至今)";
        String promotion = "到"+formattedNextYear+"前再消费"+promotionAmount+"元即可升级至"+ MemberLevel.getName(level);
        memberV2VO.setConsumption(consumption);
        memberV2VO.setPromotion(promotion);
    }

    public   int[] evaluateOrderAmount(BigDecimal amount) {
        if(amount == null){
            amount = BigDecimal.ZERO;
        }
        String rule = sysConfigService.selectConfigByKey("member.level.rule");
        // 将 JSON 字符串转换为 Map
        if(CollectionUtils.isEmpty(levelAmountMap)){
            convertJsonToMap(rule);
        }

        // 定义规则
        int level = 1; // 默认等级
        BigDecimal targetAmount = levelAmountMap.get(1); // 默认目标金额
        // 根据消费金额判断级别和目标金额
        for (Map.Entry<Integer, BigDecimal> entry : levelAmountMap.entrySet()) {
            // 对于第一个级别，直接判断小于
            if (entry.getKey() == 1 && amount.compareTo(entry.getValue()) < 0) {
                targetAmount = entry.getValue();
                break;
            }

            // 对于其他级别，判断范围
            if (entry.getKey() > 1) {
                BigDecimal previousLimit = levelAmountMap.get(entry.getKey() - 1);
                if (amount.compareTo(previousLimit) >= 0 && amount.compareTo(entry.getValue()) < 0) {
                    level = entry.getKey();
                    targetAmount = entry.getValue();
                    break;
                }
            }
        }
        return new int[] {level, targetAmount.intValue()};
    }

    public static  void convertJsonToMap(String jsonString) {
        // 解析 JSON
        JSONArray jsonArray = JSONArray.parseArray(jsonString);
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            int level = jsonObject.getInteger("level");
            BigDecimal amount = jsonObject.getBigDecimal("amount");
            levelAmountMap.put(level, amount);
        }
    }

    public static void convertJsonToList(String jsonString) {
        // 解析 JSON
        JSONArray jsonArray = JSONArray.parseArray(jsonString);
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            BigDecimal amount = jsonObject.getBigDecimal("amount");
            levelAmountList.add(amount);
        }
    }


    public static Map<String,String> getProgressData(BigDecimal amount) {
        int currentLevel = 0;
        int nextLevel = 1;
        BigDecimal amountToNextLevel = BigDecimal.ZERO;
        BigDecimal amountNeeded = BigDecimal.ZERO;
        double progressPercentage = 0.0;
        Map<String,String> resultMap = new HashMap<>();
        for (int i = 0; i < levelAmountList.size(); i++) {
            BigDecimal currentAmount = levelAmountList.get(i);

            if (amount.compareTo(currentAmount) < 0) {
                currentLevel = (i > 0) ? i : 1;
                nextLevel = i + 1 < levelAmountList.size() ? i + 2 : 1;
                amountToNextLevel = currentAmount;
                amountNeeded = amountToNextLevel.subtract(amount);

                if (i > 0) {
                    BigDecimal previousAmount = levelAmountList.get(i - 1);
                    progressPercentage = amount.subtract(previousAmount)
                            .divide(amountToNextLevel.subtract(previousAmount), 2, BigDecimal.ROUND_HALF_UP)
                            .multiply(BigDecimal.valueOf(100)).doubleValue();
                } else {
                    progressPercentage = amount.divide(currentAmount).doubleValue();
                }
                break;
            }

            if (i == levelAmountList.size() - 1) {
                currentLevel = i;
                nextLevel = 1;
                amountToNextLevel = BigDecimal.ZERO;
                amountNeeded = BigDecimal.ZERO;
                progressPercentage = 100;
            }
        }
        resultMap.put("nextLevel",MemberLevel.getName(nextLevel));
        resultMap.put("amountNeeded",String.valueOf(amountNeeded));
        resultMap.put("progressPercentage",String.valueOf(progressPercentage));

        return resultMap;
    }

}
