package com.hzs.third.pay.util;

import cn.hutool.core.util.RandomUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

/**
 * 支付工具类
 */
public class PayUtil {

    /**
     * 随机减金额
     */
    final static BigDecimal RANDOM = new BigDecimal("0.5");

    /**
     * 计算随机金额，0.2元进行随机生成
     *
     * @param amount
     * @return
     */
    public static BigDecimal handleAmountRandom(BigDecimal amount) {
        if (amount.compareTo(RANDOM) > 0) {
            // 订单金额大于0.99元才进行处理
            return amount.subtract(RANDOM).add(RandomUtil.randomBigDecimal(new BigDecimal("0.01"), RANDOM).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return amount;
    }

    /**
     * 校验支付金额是否正常
     *
     * @param amount    实际订单金额
     * @param payAmount 支付金额
     * @return
     */
    public static boolean checkAmount(BigDecimal amount, BigDecimal payAmount) {
        // 实际订单金额 - 支付金额 <= 0.2 则为正常处理
        return amount.subtract(payAmount).compareTo(RANDOM) <= 0;
    }


    /**
     * 获取三方订单编号（部分支付方式处理）
     *
     * @param businessCode
     * @param businessType
     * @return
     */
    public static String getThirdOrderCode(String businessCode, Integer businessType) {
        if (null == businessType) {
            return businessCode + "-" + RandomUtil.randomNumbers(4);
        } else {
            // 三方订单编号（因调起微信方式没有扩展参数，需要自处理业务类型）
            return businessCode + "-" + businessType + RandomUtil.randomNumbers(3);
        }
    }


    /**
     * 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     *
     * @param request
     * @return
     */
    public static TreeMap<String, String> getParams(HttpServletRequest request) {
        TreeMap<String, String> map = new TreeMap<>();
        Map<String, String[]> reqMap = request.getParameterMap();
        for (String key : reqMap.keySet()) {
            String value = reqMap.get(key)[0];
            map.put(key, value);
        }
        return map;
    }


}
