package io.hmit.config;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import io.hmit.common.utils.DateUtils;
import io.hmit.common.utils.HttpRequestUtil;
import io.hmit.common.utils.MD5;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class ZhelibanUtils {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(ZhelibanAPP.class);
    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    private static Gson gson = new GsonBuilder()
            .registerTypeAdapter(
                    new TypeToken<Map<String, Object>>() {
                    }.getType(),
                    new JsonDeserializer<Map<String, Object>>() {
                        @Override
                        public Map<String, Object> deserialize(
                                JsonElement json, Type typeOfT,
                                JsonDeserializationContext context) throws JsonParseException {

                            Map<String, Object> treeMap = new HashMap<String, Object>();
                            JsonObject jsonObject = json.getAsJsonObject();
                            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                            for (Map.Entry<String, JsonElement> entry : entrySet) {
                                treeMap.put(entry.getKey(), entry.getValue());
                            }
                            return treeMap;
                        }
                    }).create();

    public static JSONObject HttpRequest(String request , String RequestMethod , String output, String type, Map<String, Object> headParam ){
        @SuppressWarnings("unused")
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            //建立连接
            //trustAllHosts();//HTTPS请求需建立信任链接
            URL url = new URL(request);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            if(RequestMethod.equals("POST")) {
                connection.setDoOutput(true);
            }
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(RequestMethod);
            connection.setHostnameVerifier(DO_NOT_VERIFY);
            //一定要设置 Content-Type 要不然服务端接收不到参数
            setHeaderParam(connection,type,headParam);
            connection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
            if(output != null){
                OutputStream out = connection.getOutputStream();
                out.write(output.getBytes("UTF-8"));
                out.close();
            }
            //流处理
            InputStream input = connection.getInputStream();
            InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
            BufferedReader reader = new BufferedReader(inputReader);
            String line;
            while((line=reader.readLine())!=null){
                buffer.append(line);
            }
            //关闭连接、释放资源
            reader.close();
            inputReader.close();
            input.close();
            input = null;
            connection.disconnect();
            logger.info(buffer.toString());
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static Map<String, Object> getAccessToken() throws UnsupportedEncodingException, NoSuchAlgorithmException {
        Long current_time = System.currentTimeMillis();
        Map<String, Object> map = null ;
        String para = "requestKey="+ZhelibanAPP.APP_KEY+"&requestTime="+current_time+"&sign="+ MD5.md5(ZhelibanAPP.APP_KEY+ZhelibanAPP.APP_SECRET+current_time);
        System.out.println(para);
//        Map<String, Object> map_result = HttpRequestUtil.sendPost(ZhelibanAPP.TOKEN_URL, para,false,false);
        Map<String, Object> map_result = new HashMap<>();
        String sp = new Gson().toJson(map_result);
        if (null != sp && !"".equals(sp) ) {
            try {
                map = new Gson().fromJson(sp,new TypeToken<Map<String, Object>>() {
                }.getType());
                if (map.get("result").toString().equals("00")){ //获取成功
                    map.put("accessToken",map.get("resultmsg"));
                } else {
                    logger.info("获取token失败:错误代码--"+map.get("result")+",错误原因--"+map.get("resultmsg"));
                }
                logger.info("获取token成功:"+map.get("resultmsg"));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取token异常!!");
            }
        }
        System.out.println(map);
        return  map;
    }
    public static Map<String, Object> getUserInfo(Map<String, Object> map) {
        Map<String, Object> result_map = ZhelibanUtils.getAppToken(map);
        String current_time = DateUtils.format(new Date(),"yyyyMMddHHmmss");

        if (result_map !=null){
            System.out.println(result_map);
            if ("0".equals(result_map.get("result").toString())){
                String params_vailidation = "&servicecode="+ZhelibanAPP.SERVICE_CODE+"&time="+current_time+"&sign="+MD5.md5(ZhelibanAPP.SERVICE_CODE+ZhelibanAPP.SERVICE_PASS+current_time)+"&token="+result_map.get("token").toString()+"&datatype=json";
                String user_result = HttpRequestUtil.sendZlbGet(ZhelibanAPP.APP_BASE_URL+ZhelibanAPP.USER_INFO,params_vailidation);
                return new Gson().fromJson(user_result,new TypeToken<Map<String, Object>>() {
                }.getType());
            }else {
                return result_map;
            }

        }
        return null;

    }
    public static Map<String, Object> getRootUserInfo(Map<String, Object> map) {
        Long current_time = System.currentTimeMillis();
        String params_vailidation = "token="+map.get("ssotoken").toString();
        String user_result = "sssss";
//        String user_result = HttpRequestUtil.sendHeaderPost(ZhelibanAPP.ROOT_USER_INFO,params_vailidation,false,false);
        System.out.println("111 "+user_result);
        return new Gson().fromJson(user_result,new TypeToken<Map<String, Object>>() {
        }.getType());

    }


    /***
     * 向指定URL发送POST方法的请求
     *
     * @param apiUrl
     * @param data
     * @param headers
     * @return
     */
    public static JSONObject sendPOST(String apiUrl, String data, LinkedHashMap<String, String> headers) {
        StringBuffer strBuffer = null;
        String result = null;
        JSONObject jsonObj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            /* 获取客户端向服务器端传送数据所依据的协议名称 */
            String protocol = url.getProtocol();
            if ("https".equalsIgnoreCase(protocol)) {
                /* 获取HTTPS请求的SSL证书 */
                try {
//                    SSLUtils.ignoreSsl();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpURLConnection.setRequestProperty(key, headers.get(key));
                }
            }
            // 连接会话
            httpURLConnection.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // 设置请求参数
            dos.write(data.getBytes("UTF-8"));
            dos.flush();
            dos.close();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                result = strBuffer.toString();
                if (null == result || result.length() == 0) {
                    throw new Exception("获取企业（法人）信息失败");
                } else {
                    jsonObj = JSONObject.fromObject(result);
                }
            } else {
                throw new Exception(
                        MessageFormat.format("请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode, http_ResponseMessage));
            }
            // 断开连接
            httpURLConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }




    public static Map<String, Object> getAppToken(Map<String, Object> map) {
//        String current_time = DateUtils.getCurrentTimes();
        String current_time = DateUtils.format(new Date(),"yyyyMMddHHmmss");
        String params_vailidation = "&servicecode="+ZhelibanAPP.SERVICE_CODE+"&time="+current_time+"&sign="+MD5.md5(ZhelibanAPP.SERVICE_CODE+ZhelibanAPP.SERVICE_PASS+current_time)+"&st="+map.get("ticket").toString()+"&datatype=json";
        String valid_result = HttpRequestUtil.sendZlbGet(ZhelibanAPP.APP_BASE_URL+ZhelibanAPP.VALIDATION_TICKET,params_vailidation);
        return new Gson().fromJson(valid_result,new TypeToken<Map<String, Object>>() {
        }.getType());
    }
    public static Map<String, Object> getAAccessToken() {
        JSONObject jsonObject = HttpRequest(ZhelibanAPP.TOKEN_URL, "GET", null,"AccessToken",null);
        String accessToken = null;
        String expireTime = null;
        Map<String, Object> map = null;
        // 如果请求成功
        if (null != jsonObject) {
            try {
                if (jsonObject.getString("status").equals("0")){ //获取成功
                    map = new HashMap<String, Object>();
                    JSONObject tokenObject =  jsonObject.getJSONObject("data");
                    accessToken = tokenObject.getString("accessToken");
                    expireTime = tokenObject.getString("expireTime");
                    map.put("accessToken",accessToken);
                    map.put("expireTime",expireTime);
                } else {
                    logger.info("获取token失败:错误代码--"+jsonObject.getString("status")+",错误原因--"+jsonObject.getString("message"));
                }
                logger.info("获取token成功:"+accessToken+"，过期时间:"+expireTime);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取token异常!!");
            }
        }
        return map;
    }
    public static HttpURLConnection setHeaderParam(HttpURLConnection connection, String type, Map<String, Object> headParam) {
        if (type.equals("AccessToken")) {
            connection.setRequestProperty("appId", ZhelibanAPP.APP_ID);
            connection.setRequestProperty("appSecret", ZhelibanAPP.APP_SECRET);
        } else if (type.equals("authlogin")) {
            connection.setRequestProperty("accessToken", headParam.get("accessToken").toString());
            connection.setRequestProperty("token", headParam.get("token").toString());
        } else if (type.equals("pushMessage")) {
            connection.setRequestProperty("accessToken", headParam.get("accessToken").toString());
            connection.setRequestProperty("orgSecret", headParam.get("orgSecret").toString());
            //connection.setRequestProperty("uid", headParam.get("uid").toString());
        } else if (type.equals("getUserInfoByMobile")) {
            connection.setRequestProperty("accessToken", headParam.get("accessToken").toString());
            connection.setRequestProperty("orgSecret", headParam.get("orgSecret").toString());
        }
        return connection;
    }
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Map<String, Object> authLogin(String accessToken, String token) {
        Map<String, Object> headParam = new HashMap<String, Object>();
        Map<String, Object> result = null;
        headParam.put("accessToken",accessToken);
        headParam.put("token",token);
        logger.info("auth login");
        try{
            JSONObject jsonObject = HttpRequest(ZhelibanAPP.AUTH_LOGIN_URL, "GET", null,"authlogin",headParam);
            if (jsonObject != null && jsonObject.getString("status").equals("0")) {
                logger.info("免登授权请求成功");
                result = new HashMap<String, Object>();
                JSONObject userInfo =  jsonObject.getJSONObject("data");
                result.put("uid",userInfo.getString("uid"));
                result.put("mobile",userInfo.getString("mobile"));
                result.put("name",userInfo.getString("name"));
                result.put("orgSecret",userInfo.getString("orgSecret"));
            } else {
                logger.info("无返回值");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("免登授权请求失败！");
        }
        return result;
    }
    public static Map<String, Object> pushMessage(String accessToken, String orgSecret, String uid, String queryParam) {
        Map<String, Object> headParam = new HashMap<String, Object>();
        Map<String, Object> result = null;
        headParam.put("accessToken",accessToken);
        headParam.put("orgSecret",orgSecret);
        headParam.put("uid",uid);
        logger.info("pushMessage start!!");
        try{
            JSONObject jsonObject = HttpRequest(ZhelibanAPP.PUSH_MESSAGE_SIMPLE, "POST", queryParam,"pushMessage",headParam);
            if (jsonObject != null && jsonObject.getString("status").equals("0")) {
                logger.info("消息推送成功");
                result = new HashMap<String, Object>();
                result.put("status",jsonObject.getString("status"));
                result.put("success",jsonObject.getString("success"));
            } else {
                logger.info("消息推送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("消息推送失败！");
        }
        return result;
    }
    public static Map<String, Object> getUserInfoByMobile(String accessToken, String orgSecret, String mobile) {
        Map<String, Object> headParam = new HashMap<String, Object>();
        Map<String, Object> result = null;
        headParam.put("accessToken",accessToken);
        headParam.put("orgSecret",orgSecret);
        headParam.put("mobile",mobile);
        logger.info("getUserInfoByMobile start!!");
        try{
            JSONObject jsonObject = HttpRequestGetUserInfoByMobile(ZhelibanAPP.GET_USER_INFO_BY_MOBILE,headParam,"getUserInfoByMobile");
            if (jsonObject != null && jsonObject.getString("status").equals("0")) {
                logger.info("获取用户信息成功");
                result = new HashMap<String, Object>();
                JSONObject userInfo =  jsonObject.getJSONObject("data");
                result.put("uid",userInfo.getString("uid"));
                result.put("name",userInfo.getString("name"));
            } else {
                logger.info("获取用户信息失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取用户信息失败！");
        }
        return result;
    }
    public static JSONObject HttpRequestGetUserInfoByMobile(String request , Map<String, Object> headParam, String type ){

        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            //建立连接
            trustAllHosts();//HTTPS请求需建立信任链接
            URL url = new URL(request+"?"+"mobile="+headParam.get("mobile").toString());
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            setHeaderParam(connection,type,headParam);
            connection.setHostnameVerifier(DO_NOT_VERIFY);
            //流处理
            InputStream input = connection.getInputStream();
            InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
            BufferedReader reader = new BufferedReader(inputReader);
            String line;
            while((line=reader.readLine())!=null){
                buffer.append(line);
            }
            //关闭连接、释放资源
            reader.close();
            inputReader.close();
            input.close();
            input = null;
            connection.disconnect();
            logger.info(buffer.toString());
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }



    private static String getUtf8Url(String url) {
        char[] chars = url.toCharArray();
        StringBuilder utf8Url = new StringBuilder();
        final int charCount = chars.length;
        for (int i = 0; i < charCount; i++) {
            byte[] bytes = ("" + chars[i]).getBytes();
            if (bytes.length == 1) {
                utf8Url.append(chars[i]);
            }else{
                try {
                    utf8Url.append(URLEncoder.encode(String.valueOf(chars[i]), "UTF-8"));
                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();
                }
            }
        }
        return utf8Url.toString();
    }
    private static String toUTF(String inStr) throws UnsupportedEncodingException {
        String outStr = "";
        if (inStr != null) {
            outStr = new String(inStr.getBytes("iso-8859-1"), "UTF-8");
        }
        return outStr;
    }
    /**
     * 汉字 转换为对应的 UTF-8编码
     * @param s 木
     * @return E69CA8
     */
    public static String convertStringToUTF8(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        try {
            char c;
            for (int i = 0; i < s.length(); i++) {
                c = s.charAt(i);
                if (c >= 0 && c <= 255) {
                    sb.append(c);
                } else {
                    byte[] b;
                    b = Character.toString(c).getBytes("utf-8");
                    for (int j = 0; j < b.length; j++) {
                        int k = b[j];
                        //转换为unsigned integer  无符号integer
					/*if (k < 0)
						k += 256;*/
                        k = k < 0 ? k + 256 : k;
                        //返回整数参数的字符串表示形式 作为十六进制（base16）中的无符号整数
                        //该值以十六进制（base16）转换为ASCII数字的字符串
                        sb.append(Integer.toHexString(k).toUpperCase());

                        // url转置形式
                        // sb.append("%" +Integer.toHexString(k).toUpperCase());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();

    }
    /**
     * 可将中文转换成 "&#" 开头的html实体编码
     *
     *
     * @param str
     * @return*/
    public static String encodeS(String str) {
        char[] arrs = str.toCharArray();//Hex.encodeHex();
        StringBuilder sb = new StringBuilder();
        for (char c : arrs) {
            // \\u 表示Unicode编码。
            if (c >= '\u2E80' && c <= '\uFE4F') {//  [ 只是中文一般 [ \u4e00-\u9fa5]；中日韩统一表意文字（CJK Unified Ideographs） [\u2E80-\uFE4F]
                sb.append("&#x").append((int)c).append(";");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    public static String ZH(String str) {
        String[] string = str.split("u");
        System.out.println(new Gson().toJson(string));
        return "111";
    }
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        System.out.println(StringEscapeUtils.escapeJava("String"));



    }
}
