package com.zehong.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.zehong.common.core.domain.AjaxResult;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/getout")
public class OutController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);
    /**
     * 返回成功状态码
     */
    private static final int SUCCESS_CODE = 200;

    @GetMapping(value = "/{token}")
    public AjaxResult getindex(@PathVariable String token) throws Exception{
        String accessKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3Z0cqRQ8HtDnuTy1bEow" +
                "XUZD8yG6aXW/nSIMoCLJGD0MMJpx/1SokTksPeJdUDrPZpDk+DJAohEtO2JjOuTj" +
                "1DPMEhSPYnyogNumECnxCL5t/cnVNaPCIdHvQjXT4McvICys7eqw1gJ64I9vM1jx" +
                "yIBEiSMurU84c3XAlPwoXHDtNmEIT91vZr+zSfXpGog9SIOP68oBFX+U98WgVUSY" +
                "w9icXlDByjVJhBK/7vpa8rkT8psgxSrDpiOpUx2aQQo45vuPGgk1mJUXW/PfE9wD" +
                "/i7IMxnx+aK7pvPEv7YC3x2zGiT4OHS8TZ9sgmA4BpJDU7mg40H3a26cG1evQCRR" +
                "iwIDAQAB";
        String privateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDdnRypFDwe0Oe5" +
                "PLVsSjBdRkPzIbppdb+dIgygIskYPQwwmnH/VKiROSw94l1QOs9mkOT4MkCiES07" +
                "YmM65OPUM8wSFI9ifKiA26YQKfEIvm39ydU1o8Ih0e9CNdPgxy8gLKzt6rDWAnrg" +
                "j28zWPHIgESJIy6tTzhzdcCU/ChccO02YQhP3W9mv7NJ9ekaiD1Ig4/rygEVf5T3" +
                "xaBVRJjD2JxeUMHKNUmEEr/u+lryuRPymyDFKsOmI6lTHZpBCjjm+48aCTWYlRdb" +
                "898T3AP+LsgzGfH5orum88S/tgLfHbMaJPg4dLxNn2yCYDgGkkNTuaDjQfdrbpwb" +
                "V69AJFGLAgMBAAECggEBANcrJ1umsOS+sm4w2nlk4uZ9RZY35jVkxQF8wMNuYs9s" +
                "3nwGSK6+9Nfjqef/89fk8eBEyHuO1yBECyXAVlYlTGuJSxc27SyTmktaeDbzcfqq" +
                "YkLqB2AIOoH5whMIDksNOd1EYzaxCrcPO1zzBuXU8xRYLbL0/On6o/W+m5hL56gv" +
                "kcoc84oLHtXJ3VS+W9c3xq1cQqgFMIdg9/GN0nbPee8Uw2McYv/xmQPVXBOhQ59q" +
                "uuvyXhfE9W0un9QA8rGkNFvsD1NSx6mv+GXLn+yQcTIOiGmyTV8ynXKvqZ/auQYQ" +
                "1HLOejzgVrOIFD/2aAICph61+aX4LMTNAJzUV0SHZXECgYEA+AD7TOLRO5vKAJci" +
                "RBAqOUBgu3KRmd2jZQvvNrrRhPPG+hq8+HpVKOtdd6rwoGD+3Z0ewcvjoLbnQ3G0" +
                "GeqXWHu5OjqWXPJJyffos0XOAsiZ6NHOzzIEhclZZPKrfw1Qr8mDm5JZ5TWGN0EM" +
                "MFpl9IHRKPvlCkfYEtx/+c3k3gkCgYEA5MJOjk9TXn7RZXFTiizgMNJMQsKg0KPG" +
                "vP0NwnHskialL8vnefknMXfTNhGjV2krCppj00efEhfE+S7shZ4mil7PRWoH/YET" +
                "uLTbhHmy6ZhcMigJWSjHO3sWKaaR406So2lWSfSluw6XsK27Cj3f3+tKQC7GgxuX" +
                "QS27bekM1/MCgYAicoh1Wn/zhqUdReDVkWU8BIwrHTPKKnX6oBi/Al392JqHvNUI" +
                "sn1HrMGT0KORs0dTYvKVuotIlH806AM7IlGZUb4dr2uZR3ImYo/o7sY5rsFqDFJs" +
                "hycHqjsHgYl+oUvWzue/4SkpZDDbVeaqhLPqrWlvBuX+cpI5tHT2LroeeQKBgQDR" +
                "VY4VZDniSyLLNb1AwHgXtRncLcaDppuC7f7dZOsbgwm+h1U3pOxctE4vOEzE/JRK" +
                "i6W1/eBu6hlx/aKrU2HpVYFPAAx3ytqFN9t5ivRSFv6nV0PWtx46LBTH4Im3/Hrr" +
                "1sUDwEC4wE3He/OhF6X6fpHf0e4Oo/zxxCu0FIOQSQKBgQDLm4jfsykntDeViy/W" +
                "KzxnhMStIyEhRAJT66aveX1R6k11lTlO3aArTzfiaHiDne6R/4LTfWuHq7gyy84E" +
                "NFJBb7kGe1c2zOIFQ/wuVyA7KR6aN6YeTdJHYhV7RsHH4vLfwb0SBqEtBePqxKkV" +
                "xznrDUoIkeDx0+R/fD8uMNnRRQ==";

        // 10 位随机字符串
        String randomStr = randomstring(10);
        // 获取当前时间戳
        String timeStamp = String.valueOf(System.currentTimeMillis());

        String data = String.format("%s%s%s", accessKey, randomStr, timeStamp);


        String signMsg = "";
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKey);

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            PrivateKey key = keyFactory.generatePrivate(keySpec);

            Signature signature = Signature.getInstance("SHA1withRSA");

            signature.initSign(key);

            signature.update(data.getBytes(StandardCharsets.UTF_8));
            signMsg = Base64.getEncoder().encodeToString(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 打印结果
        System.out.println("x-access-key = " + accessKey);
        System.out.println("x-random-str = " + randomStr);
        System.out.println("x-time-stamp = " + timeStamp);
        System.out.println("x-access-sign = " + signMsg);
        Map<String,Object> map = new HashMap<>();
        map.put("x-access-key" , accessKey);
        map.put("x-random-str" , randomStr);
        map.put("x-time-stamp" , timeStamp);
        map.put("x-access-sign" , signMsg);
        String a = sendPostJson("",map,token);
        return AjaxResult.success(a);

    }

    public String sendPostJson(String url, Map<String,Object> map, String token) throws Exception{
        url = "http://61.240.155.30:30539/uni/uniauth/auth/getUserInfoByTicket?ticket="+token;
        JSONObject jsonObject = null;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            /**
             *  创建一个httpclient对象
             */
            client = HttpClients.createDefault();
            /**
             * 创建一个post对象
             */
            HttpGet post = new HttpGet(url);

            /**
             * 设置请求的报文头部的编码
             */
            //post.setHeader(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
            /**
             * 设置请求的报文头部的编码
             */
            post.setHeader(new BasicHeader("x-access-key", (String) map.get("accessKey")));
            post.setHeader(new BasicHeader("x-random-str", (String) map.get("randomStr")));
            post.setHeader(new BasicHeader("x-time-stamp", (String) map.get("timeStamp")));
            post.setHeader(new BasicHeader("x-access-sign", (String) map.get("signMsg")));

            /**
             * 执行post请求
             */
            response = client.execute(post);
            /**
             * 获取响应码
             */
            int statusCode = response.getStatusLine().getStatusCode();
            if (SUCCESS_CODE == statusCode){
                /**
                 * 通过EntityUitls获取返回内容
                 */
                String result = EntityUtils.toString(response.getEntity(),"UTF-8");
                /**
                 * 转换成json,根据合法性返回json或者字符串
                 */
                try{
                    jsonObject = (JSONObject) com.alibaba.fastjson.JSONObject.parseObject(result);
                    Map<String,Object> usermap = (Map<String,Object>)jsonObject.get("result");
                    return (String) usermap.get("tel");
                }catch (Exception e){
                    return result;
                }
            }else{
                LOGGER.error("HttpClientService-line: {}, errorMsg：{}", 146, "POST请求失败！");
            }
        }catch (Exception e){
            LOGGER.error("HttpClientService-line: {}, Exception：{}", 149, e);
        }finally {
            response.close();
            client.close();
        }
        return null;
    }


    public String randomstring(int num){
        String str ="";
        // 获取0到n之间的随机整数
        int n = 9;  // 上限值
        for(int i=0;i<num;i++){
            str =str+(int)(Math.random() * n);
        }
        return str;
    }
}
