package com.hai.order.utils;

import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.entity.HighChildOrder;

import java.math.BigDecimal;
import java.util.*;

/**
 * 订单工具类
 * @className: OrderUtil
 * @author: HuRui
 * @date: 2022/8/26
 **/
public class OrderUtil {

    /**
     * 计算订单金额
     * @param childOrderList  子订单
     * @return
     * @throws Exception
     */
    public static Map<String, Object> calculateOrderPrice(List<HighChildOrder> childOrderList) {
        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal payablePrice = new BigDecimal("0");
        BigDecimal deductionPrice = new BigDecimal("0");
        for (HighChildOrder childOrder : childOrderList) {
            // 不是赠品才会计算金额
            if (!childOrder.getGiveawayType()) {
                if (childOrder.getTotalPrice() == null || childOrder.getTotalActualPrice() == null || childOrder.getTotalDeductionPrice() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "缺少计算金额");
                }
                totalPrice = totalPrice.add(childOrder.getTotalPrice());
                payablePrice = payablePrice.add(childOrder.getTotalActualPrice());
                deductionPrice = deductionPrice.add(childOrder.getTotalDeductionPrice());
            }
        }
        Map<String,Object> param = new HashMap<>();
        param.put("totalPrice", totalPrice);
        param.put("payablePrice", payablePrice);
        param.put("deductionPrice", deductionPrice);
        return param;
    }

    /**
     * 生成交易订单号
     * @return
     * @throws Exception
     */
    public static String generateOrderNo(){
        try {
            // 5位随机数 + 1位线程生成数
            String randomNum = (new Random().nextInt(8999) + 1000) + IDGenerator.nextId(1);
            // 生成订单号
            return DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + randomNum;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成子订单号
     * @return
     * @throws Exception
     */
    public static String generateChildOrderNo() {
        // 生成子订单号
        return IDGenerator.nextId(16);
    }

    /**
     * 生成退款订单号
     * @return
     * @throws Exception
     */
    public static String generateRefundOrderNo() throws Exception {
        // 5位随机数 + 1位线程生成数
        String randomNum = (new Random().nextInt(899999) + 10000) + IDGenerator.nextId(1);
        // 生成订单号
        return DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + randomNum;
    }

}
