package com.yc.ship.module.trade.service.order.handler;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.DateUtils;
import com.anji.captcha.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@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", "宜昌交运国际旅行社有限公司"); // Consider making this configurable or a parameter
        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.toString());
        String mac = MD5Util.md5(builder.toString());
        map.put("mac", mac);
        map.remove("secretKey");
        String params = JSONUtil.toJsonStr(map);
        log.debug("Encoded params: {}", params);
        String encode = cn.hutool.core.codec.Base64.encode(params.toString());
        return encode;
    }

    /**
     * 生成群发短信接口参数
     *
     * @param phones 用户手机号码集合字符串，以英文逗号隔开的手机号码集合,最多1000个手机号
     * @param smsContent 短信内容，最大1000个字符
     * @param sendtime 发送时间，格式 yyyyMMddHHmmss
     * @param sendtermid 扩展号，长度最大12位
     * @param customTaskid 客户任务id，客户侧唯一消息ID,状态报告推送接口原样带回；最大支持70位
     * @return 群发短信接口参数JSON字符串
     */
    public static String generateParams2(String phones, String smsContent, String sendtime, String sendtermid, String customTaskid) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phones", phones);
        paramMap.put("smsContent", smsContent);

        // 可选参数，只有非空时才添加到参数中
        if (sendtime != null && !sendtime.isEmpty()) {
            paramMap.put("sendtime", sendtime);
        }
        if (sendtermid != null && !sendtermid.isEmpty()) {
            paramMap.put("sendtermid", sendtermid);
        }
        if (customTaskid != null && !customTaskid.isEmpty()) {
            paramMap.put("customTaskid", customTaskid);
        }

        return JSONUtil.toJsonStr(paramMap);
    }

    public static String generateUnicomParams(String mobiles, String sparams, String templateId, String apId, String sign, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {

        StringBuffer param = new StringBuffer();
        //企业编号
        param.append("?SpCode=" + sign);
        param.append("&LoginName=" + apId);
        param.append("&Password=" + secretKey);
        //模板内容进行替换 urlCode转换
        String content = sparams;
        try {
            content =  URLEncoder.encode(sparams, "GBK");
        }catch (Exception e){
            content = sparams;
        }
        param.append("&MessageContent=" + content);
        param.append("&UserNumber=" + mobiles);
        param.append("&templateId=" + templateId);
        //生成一个序号
        // 生成随机数
        String serialNumber = "";
        Random random = new Random();
        int ranNum = random.nextInt(9);
        serialNumber = createOrderNo(ranNum + "");
        serialNumber = serialNumber.substring(0, serialNumber.length() - 2);
        param.append("&SerialNumber=" + serialNumber);
        param.append("&ScheduleTime=");
        param.append("&f=1");
        return param.toString();

    }

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

