package com.kiisoo.ic.common.utils;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class SignUtils {

    public final static String APPID = "RqdoSAWO3375";

    /**
     * 企业ID
     */
    public final static String CROP_ID = "wwc8b3e81998fe5394";

    /**
     * 应用的凭证密钥
     */
    public final static String APPSECRET = "scb9m8DEtSwJpB_ZFXg4J9WE91yH-WNBBQ4Vxv1NYy4";

    public final static String USERID = "3fe8a13ad5394491941fcfbf72b3eb0f";

    /**
     * 社交营销系统-接单中心
     */
    public final static String AGENT_ID = "1000037";

    /**
     * 获取微信凭证
     *
     * @param jsapi_ticket 凭证
     * @param url          路径
     * @return
     */
    public static Map<String, Object> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        if (log.isDebugEnabled()) {
            log.debug("微信获取凭证 sign方法", string1);
        }

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error("微信获取凭证 sign方法异常", e);
        } catch (UnsupportedEncodingException e) {
            log.error("微信获取凭证 sign方法异常", e);
        }

        Map<String, Object> root = new HashMap<String, Object>();
        root.put("url", url);
        root.put("jsapi_ticket", jsapi_ticket);
        root.put("nonceStr", nonce_str);
        root.put("timestamp", timestamp);
        root.put("signature", signature);
        root.put("appId", CROP_ID);

        return root;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
