package com.bjtdba.userCenter.util;

import com.alibaba.druid.util.Base64;
import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class OcrUtil {
    // Access_Token获取
    private static final String ACCESS_TOKEN_HOST = "https://aip.baidubce.com/oauth/2.0/token?";
    // 身份证识别请求URL
    private static final String OCR_HOST = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?";
    // apiKey,secretKey
    private static final String API_KEY ="Utg2bxLY4is7h5DPehVZ63Q4";
    private static final String SECRET_KEY = "yfGMEAO6YQXIE2pqYMiH4MNBE1DcNhyO";


    // 获取百度云OCR的授权access_token
    public static String getAccessToken() {
        return getAccessToken(API_KEY, SECRET_KEY);
    }

    /**
     * 获取百度云OCR的授权access_token
     * @param apiKey
     * @param secretKey
     * @return
     */
    public static String getAccessToken(String apiKey, String secretKey) {
        String accessTokenURL = ACCESS_TOKEN_HOST
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + apiKey
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + secretKey;

        try {
            URL url = new URL(accessTokenURL);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 获取响应头
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "---->" + map.get(key));
            }

            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                result.append(inputLine);
            }
            JSONObject jsonObject = JSONObject.parseObject(result.toString());
            return jsonObject.getString("access_token");

        } catch (Exception e) {
            e.printStackTrace();
            System.err.print("获取access_token失败");
        }
        return null;
    }

    /**
     * 获取身份证识别后的数据
     * @param imageUrl
     * @param idCardSide
     * @return
     */
    public static String getStringIdentityCard(InputStream imageUrl, Integer idCardSide) throws IOException {
        // 身份证OCR的http URL+鉴权token
        String OCRUrl = OCR_HOST+"access_token="+getAccessToken();
        System.out.println(OCRUrl);
        System.out.println("***************************************************");
        System.out.println(getAccessToken());
        // 对图片进行base64处理

        String image = encodeImageToBase64(imageUrl);
        String side="";
        if(idCardSide==1){
            side="front";
        }else{
            side="back";
        }
        // 请求参数
        String requestParam = "detect_direction=true&id_card_side="+side+"&image="+image;

        try {
            // 请求OCR地址
            URL url = new URL(OCRUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("apiKey", API_KEY);
            connection.setDoOutput(true);
            connection.getOutputStream().write(requestParam.getBytes(StandardCharsets.UTF_8));
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                result.append(inputLine);
            }
            bufferedReader.close();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("身份证OCR识别异常");
            return null;
        }
    }

    /**
     * 对图片url进行Base64编码处理
     * @param imageUrl
     * @return
     */
    public static String encodeImageToBase64(InputStream imageUrl) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        try {
            InputStream inputStream = imageUrl;
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();

            // 对字节数组Base64编码
            return URLEncoder.encode(Base64.byteArrayToBase64(data), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static class MyX509TrustManager implements X509TrustManager {

        static MyX509TrustManager manger = new MyX509TrustManager();

        public MyX509TrustManager() {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }
    }


    /**
     * https 远程路径
     *
     * @throws Exception
     */
    public static InputStream getFileInputStreamFromUrlHttps(String urlStr) throws Exception {

        //new一个URL对象
        URL url = new URL(urlStr);
        //打开链接
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        InputStream in = new ByteArrayInputStream(data);

        // 得到输入流
        return in;
    }

    public static byte[] file2Byte(File file) {
        byte[] fileBytes = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }

    private static byte[] readInputStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    /**
     * 提取OCR识别身份证有效信息
     * @param
     * @return
     */
    public static JSONObject getIdCardInfo(InputStream image, int idCardSide) throws IOException {
        String value = getStringIdentityCard(image, idCardSide);
//        String side;
//        if (idCardSide == 1) {
//            side = "正面";
//        }else {
//            side = "背面";
//        }
        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(value);

        return  jsonObject;
//
//        JSONObject words_result = jsonObject.getJSONObject("words_result");
//        if (words_result == null || words_result.isEmpty()) {
//            map.put("side","请提供身份证"+side+"图片");
////            throw new MyException("请提供身份证"+side+"图片");
//        }
//        for (String key : words_result.keySet()) {
//            JSONObject result = words_result.getJSONObject(key);
//            String info = result.getString("words");
//            switch (key) {
//                case "姓名":
//                    map.put("name", info);
//                    break;
//                case "性别":
//                    map.put("sex", info);
//                    break;
//                case "民族":
//                    map.put("nation", info);
//                    break;
//                case "出生":
//                    map.put("birthday", info);
//                    break;
//                case "住址":
//                    map.put("address", info);
//                    break;
//                case "公民身份号码":
//                    map.put("idNumber", info);
//                    break;
//                case "签发机关":
//                    map.put("issuedOrganization", info);
//                    break;
//                case "签发日期":
//                    map.put("issuedAt", info);
//                    break;
//                case "失效日期":
//                    map.put("expiredAt", info);
//                    break;
//            }
//        }
//        return map;

    }

}
