package com.sifang.modules.customer.utils;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.sifang.modules.customer.constant.YueXiuConstants;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


public class TokenTestUtils {

    private static Logger logger = LoggerFactory.getLogger(TokenTestUtils.class);

    /**
     * 测试SIT环境接口地址
     */
//    private static String assetReportForPersonHost = "https://59.37.128.138:442/out/retail_leasing";
    /**
     * 测试UAT环境接口地址
     */
//   private static String assetReportForPersonHost = "https://59.37.128.138:442/retail_leasing";

    /**
     * 生产环境接口地址
     */
    private static String assetReportForPersonHost = "https://carleasing.yuexiu-finance.com:442/retail_leasing";

    private static String IMGURL;

    static {
        try {
          /*  Configuration configuration = new PropertiesConfiguration("conf.properties");
            IMGURL = configuration.getString("img.domain");*/
            IMGURL=  Thread.currentThread().getContextClassLoader().getResource("static/client/prod_client.p12").getFile();
            logger.info("IMGURL: {}", IMGURL);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static String getLvsAccessToken() throws Exception{

        String atUrl = assetReportForPersonHost + "/oauth/token";
        String userName = "nhkj001";
        String password = "NH4vbdyky*";
        String url = atUrl+"?client_id=Finance&client_secret=53e18ab1-67cc-475f-b54b-32c00f8b9bd6&grant_type=password&username="+userName+"&password="+password;
        String sslAddress = IMGURL;
        String sslPassword = "qczl#321";
        String reqJson = new String();
        String resultData = "";
        KeyStore clientKeyStore = KeyStore.getInstance("PKCS12");
        clientKeyStore.load(new BufferedInputStream(new FileInputStream(sslAddress)), sslPassword.toCharArray());
//            此类充当基于密钥内容源的密钥管理器的工厂。每个密钥管理器管理特定类型的、由安全套接字所使用的密钥内容。密钥内容是基于 KeyStore 和/或提供者特定的源。
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, sslPassword.toCharArray());

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                        + session.getPeerHost());
                return true;
            }
        };

        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new TrustUtils();
        trustAllCerts[0] = tm;
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
                .getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        HttpsURLConnection connection = null;
        try {
            URL myURL = new URL(url);
            connection = (HttpsURLConnection) myURL.openConnection();

            connection.setSSLSocketFactory(sslContext.getSocketFactory());
            // 设置不验证服务器，返回true不验证，false为验证，默认为false；也可以根据arg0的值验证或不验证指定服务器；
            connection.setHostnameVerifier((m1, m2) -> true);

            connection.setRequestMethod("POST");
            //从服务器获取数据
            connection.setDoInput(true);
            //向服务器传输数据
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            if (!reqJson.isEmpty()) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(reqJson.getBytes());
                outputStream.flush();
                outputStream.close();
            }
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder results = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    results.append(line);
                }
                resultData = results.toString();
            }
            System.out.println(resultData);
        } catch (Exception e){
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return resultData;
    }

    /**
     * 获取token
     *
     * @param url      地址
     * @param username 用户名
     * @param eDPubKey 秘钥
     * @return
     * @throws Exception
     */

    private static JSONObject getLvsToken(String url, String username, String eDPubKey) {
        LinkedMultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
//        HashMap<String, String> bodyMap = new HashMap<>();
        bodyMap.add("client_id", "Finance");
        bodyMap.add("client_secret", "53e18ab1-67cc-475f-b54b-32c00f8b9bd6");
        bodyMap.add("grant_type", "password");
        bodyMap.add("username", username);
        bodyMap.add("password", eDPubKey);
        logger.info("getLvsToken ----------- bobyMap :{}",bodyMap);
        String urlhe = "?client_id=Finance&client_secret=53e18ab1-67cc-475f-b54b-32c00f8b9bd6&grant_type=password&username=hty001&password=Password@123";
        url = url+urlhe;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<LinkedMultiValueMap<String, String>> httpEntity = new HttpEntity<>(bodyMap, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> accessTokenJsonOb = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JSONObject.class);
        logger.info("getLvsToken -----------:{}",accessTokenJsonOb);
        if (null != accessTokenJsonOb) {
            return accessTokenJsonOb.getBody();
        }
        return null;
    }

    /**
     * 刷新获取token
     *
     * @param url      地址
     * @param refreshToken 刷新token使用
     * @return
     * @throws Exception
     */

    public static JSONObject findRefreshToken(String url, String refreshToken) {
        url=assetReportForPersonHost +url;
        LinkedMultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("client_id", "client2");
        bodyMap.add("client_secret", "secret");
        bodyMap.add("grant_type", "refresh_token");
        bodyMap.add("refresh_token", refreshToken);
        logger.info("getLvsToken ------url:{}-----bodyMap:{}",url,bodyMap);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<LinkedMultiValueMap<String, String>> httpEntity = new HttpEntity<>(bodyMap, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> accessTokenJsonOb = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JSONObject.class);
        logger.info("getLvsToken -----------:{}",accessTokenJsonOb);
        if (null != accessTokenJsonOb) {
            return accessTokenJsonOb.getBody();
        }
        return null;
    }

    public static JSONObject clientPostYXMap(Map<String, Object> map, String url,String token){
        url=assetReportForPersonHost +url;
        Map<String,Object> maps = Maps.newHashMap();

        maps.put("systemId", YueXiuConstants.CLIENT_ID);
        maps.put("serialNumber",UUID.randomUUID().toString());
        maps.put("transactionCode","");
        maps.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        maps.put("version","1");
        map.put("head",maps);
        logger.info("clientPostYXMap====maps:{}",map);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Bearer " +token);
        httpHeaders.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        HttpEntity<String> httpEntity = new HttpEntity<>(new Gson().toJson(map), httpHeaders);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(20 * 1000);
        requestFactory.setReadTimeout(60 * 1000);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
        ResponseEntity<JSONObject> accessTokenJsonOb = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JSONObject.class);
        logger.info("clientPostZYMap -----------:{}",accessTokenJsonOb);
        if (null != accessTokenJsonOb) {
            return accessTokenJsonOb.getBody();
        }
        return null;
    }

    public static JSONObject clientPostYX(Map<String, Object> map, String url,String token){
        url=assetReportForPersonHost +url + "?access_token=" + token;
        logger.info("clientPostYXMap====maps:{}",new Gson().toJson(map));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        HttpEntity<String> httpEntity = new HttpEntity<>(new Gson().toJson(map), httpHeaders);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(20 * 1000);
        requestFactory.setReadTimeout(60 * 1000);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
        ResponseEntity<JSONObject> accessTokenJsonOb = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JSONObject.class);
        logger.info("clientPostZYMap -----------:{}",accessTokenJsonOb);
        if (null != accessTokenJsonOb) {
            return accessTokenJsonOb.getBody();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String obj =getLvsAccessToken();
        JSONObject key = JSONObject.parseObject(obj);
        System.out.println(" ---ddd  " +key.getString("access_token"));

       // System.out.println(Thread.currentThread().getContextClassLoader().getResource("conf.properties"));
    }


}
