package com.usoftchina.dingtalk.sdk.util;

import java.util.Base64;
import java.util.regex.Pattern;

/**
 * @author yingp
 */
public class UrlUtils {

    private final static Pattern urlPattern = Pattern.compile("https{0,1}://[^\\x{4e00}-\\x{9fa5}\\n\\r\\s]{3,}");

    /**
     * 生成获取授权，自动登录后跳转实际界面的auth链接
     *
     * @param corpId       公司ID
     * @param master       账套
     * @param agentCode    应用编号
     * @param agentBaseUrl 应用主页
     * @param authUrl      授权url
     * @param redirectUrl  跳转页
     * @return
     * @throws Exception
     */
    public static String generateAuthUrl(String corpId, String master, String agentCode, String agentBaseUrl, String authUrl, String redirectUrl) throws Exception {
        if (!urlPattern.matcher(redirectUrl).matches()) {
            if (agentBaseUrl.endsWith("/")) {
                if (redirectUrl.startsWith("/")) {
                    redirectUrl = agentBaseUrl + redirectUrl.substring(1);
                } else {
                    redirectUrl = agentBaseUrl + redirectUrl;
                }
            } else {
                if (redirectUrl.startsWith("/")) {
                    redirectUrl = agentBaseUrl + redirectUrl;
                } else {
                    redirectUrl = agentBaseUrl + "/" + redirectUrl;
                }
            }
        }
        String base64Url = Base64.getEncoder().encodeToString(redirectUrl.getBytes());
        return String.format("%s?corpId=%s&agent=%s&url=%s&master=%s", authUrl, corpId, agentCode, base64Url, master);
    }
}
