package com.yc.ship.module.trade.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.anji.captcha.util.MD5Util;
import lombok.extern.slf4j.Slf4j;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

/**
 * @author qsl
 */
@Slf4j
public class SmsUtil {

    public static String generateParams(String mobiles, String sparams, String templateId, String apId, String sign, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("ecName", "宜昌交运国际旅行社有限公司");
        map.put("apId", apId);
        map.put("templateId", templateId);
        map.put("mobiles", mobiles);
        map.put("params", sparams);
        map.put("sign", sign);
        map.put("addSerial", "");

        StringBuilder builder = new StringBuilder();
        builder.append(map.get("ecName"));
        builder.append(map.get("apId"));
        builder.append(secretKey);
        builder.append(map.get("templateId"));
        builder.append(map.get("mobiles"));
        builder.append(map.get("params"));
        builder.append(map.get("sign"));
        builder.append(map.get("addSerial"));
        log.debug("MAC input: {}", builder);
        String mac = MD5Util.md5(builder.toString());
        map.put("mac", mac);
        map.remove("secretKey");
        String params = JSONUtil.toJsonStr(map);
        log.debug("Encoded params: {}", params);
        return cn.hutool.core.codec.Base64.encode(params);
    }


    /**
     * 生成订单号
     * 订单规则  prefix + yyyyMMddHHmmss + 至少5位序列+2位随机+2位分中心后缀
     *
     * @param prefix 前缀：XS订单，DT退单
     */
    public static String createOrderNo(String prefix) {
        Date now = new Date();
        //生成时间标识
        String date = DateUtil.format(now, "yyyyMMddHHmmss");
        // 生成随机数
        Random random = new Random();
        int ranNum = random.nextInt(100);
        String strRan = String.format("%02d", ranNum);
        //组合生成订单
        return prefix + date + strRan;
    }
}

