package com.kxs.user.biz.util;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import io.micrometer.common.util.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信程序
 *
 * @author 没秃顶的码农
 * @date 2024-04-24
 */
public class SmsUtils {

    public static void sendCode(String mobile, String code){

        Map<String, String> queries = new HashMap<>();
        queries.put("mobile", mobile);
        queries.put("param", "**code**:" +code+",**minute**:5");

        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        queries.put("smsSignId", "0f6eccbf0ff343029a7bffc144591fd8");
        queries.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");



        String path = "https://gyytz.market.alicloudapi.com/sms/smsSend";
        String url = SmsUtils.buildUrl(path, queries);

        HttpRequest.post(url)
                .header(Header.AUTHORIZATION, "APPCODE 8e5704921ca3422f80f0deb935a7ddc6")
                .execute().body();

    }
    /**
     * 构建url
     *
     * @param url    url
     * @param queries 查询
     * @return {@link String}
     */
    public static String buildUrl(String url, Map<String, String> queries) {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        if (null != queries) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : queries.entrySet()) {
                if (!sbQuery.isEmpty()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), StandardCharsets.UTF_8));
                    }
                }
            }
            if (!sbQuery.isEmpty()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }
}
