package com.weaver.seconddev.chapanda.beisen.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.beisen.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/***
 * 获取考核数据
 */
@Component
public class Esb2BeisenAssessUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2BeisenAssessUtil.class);

    /***
     *
     * @param emails
     * @param beisen_account
     * @param format
     * @param consumer_key
     * @param oauth_token
     * @param oauth_signature_method
     * @param oauth_timestamp
     * @param oauth_nonce
     * @param oauth_version
     * @param oauth_signature
     */
    public String doHttpGet(String emails,String beisen_account,String format,String consumer_key,String oauth_token,String oauth_signature_method,String oauth_timestamp,String oauth_nonce,String oauth_version,String oauth_signature){
        String msg = "";
        String applyUrl = Constants.beishenAssessHost+Constants.queryAssessUrl+"?beisen_account="+beisen_account+"&emails="+emails+"&format="+format+"&oauth_consumer_key="+consumer_key+"&oauth_token="+oauth_token+"&oauth_signature_method="+oauth_signature_method+"&oauth_timestamp="+oauth_timestamp+"&oauth_nonce="+oauth_nonce+"&oauth_version="+oauth_version+"&oauth_signature="+oauth_signature;
        log.error("applyUrl:{}",applyUrl);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        try {
            Request request = new Request.Builder()
                    .url(applyUrl)
                    .method("GET", null)
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            msg = response.body().string();
            log.error("code:{}",code);
            log.error("msg:{}",msg);
        } catch (IOException e) {
            log.error("e:{}",e);
        }
        return msg;
    }

    /***
     * 查询考核数据
     * @param emails
     */
    public void queryAssessData(String emails){
        String applyUrl = Constants.beishenAssessHost+Constants.queryAssessUrl;
        String beisen_account = Constants.beisenAccount;
        String oauth_consumer_key = Constants.consumerKey;
        String oauth_token = Constants.accessToken;
        String oauth_version = Constants.oauthVersion;
        String oauth_nonce = randomString(11);
        String oauth_signature_method = Constants.oauthSignatureMethod;
        String format = Constants.format;
        String oauth_consumer_secret = Constants.consumerSecret;
        String oauth_token_secret = Constants.tokenSecret;

        String oauth_signature = "";

        long oauth_timestamp = System.currentTimeMillis()/1000;
        log.error("oauth_consumer_key:{}",oauth_consumer_key);
        log.error("oauth_nonce:{}",oauth_nonce);
        log.error("oauth_timestamp:{}",oauth_timestamp);
        log.error("oauth_token:{}",oauth_token);
        log.error("oauth_version:{}",oauth_version);

        String key = oauth_consumer_secret+"&"+oauth_token_secret ;
        log.error("key:{}",key);
        try {
            String paramData = "beisen_account="+URLEncoder.encode(beisen_account, "UTF-8")+"&emails="+URLEncoder.encode(emails, "UTF-8")+"&format="+URLEncoder.encode(format, "UTF-8")+"&oauth_consumer_key="+URLEncoder.encode(oauth_consumer_key, "UTF-8")+"&oauth_nonce="+URLEncoder.encode(oauth_nonce, "UTF-8")+"&oauth_signature_method="+URLEncoder.encode(oauth_signature_method, "UTF-8")+"&oauth_timestamp="+URLEncoder.encode(oauth_timestamp+"", "UTF-8")+"&oauth_token="+URLEncoder.encode(oauth_token, "UTF-8")+"&oauth_version="+URLEncoder.encode(oauth_version, "UTF-8");
            log.error("paramData:{}",paramData);
            String encodeParamData = URLEncoder.encode(paramData, "UTF-8");
            log.error("encodeParamData:{}",encodeParamData);
            String concatData = "POST&"+URLEncoder.encode(applyUrl, "UTF-8")+"&"+encodeParamData;
            oauth_signature = calculateHmacSha1(key, concatData);
            log.error("oauth_signature:{}",oauth_signature);
            oauth_signature = URLEncoder.encode(oauth_signature, "UTF-8");
            log.error("oauth_signature2:{}",oauth_signature);
        } catch (UnsupportedEncodingException e) {
            log.error("e:{}",e);
        }

        if(StringUtils.isNotBlank(oauth_signature)){
            String msg = doHttpGet(emails,beisen_account,format,oauth_consumer_key,oauth_token,oauth_signature_method,oauth_timestamp+"",oauth_nonce,oauth_version,oauth_signature);
        }
    }

    /***
     * 计算HmacSHA1
     * @param key
     * @param message
     * @return
     */
    public String calculateHmacSha1(String key, String message) {
        String data = "";
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            mac.init(secretKeySpec);
            byte[] digest = mac.doFinal(message.getBytes());
            data =  Base64.getEncoder().encodeToString(digest);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            log.error("e:{}",e.getMessage());
        }
        return data;
    }

    /***
     *
     * @return
     */
    public String randomString(int length){
        String data = UUID.randomUUID().toString();
        // 定义可能的字符
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = ThreadLocalRandom.current().nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        data = sb.toString();
        return data;

    }
}
