package com.ruoyi.web.controller.app.juhe;

import com.ruoyi.web.controller.app.baidu.GsonUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class JuheAuthentication {


    public static boolean authentication(String realname, String idcard, String mobile) throws Exception {
        String apiKey = "c4a1fd85f9cf515b3c602279837189f3";
        String apiUrl = "https://v.juhe.cn/telecom/query";

        HashMap<String, String> map = new HashMap<>();
        map.put("key", apiKey);
        map.put("realname", realname);
        map.put("idcard", idcard);
        map.put("mobile", mobile);
        map.put("type", "");
        map.put("showid", "");
        map.put("province", "");
        map.put("detail", "");

        URL url = new URL(String.format("%s?%s", apiUrl, params(map)));
        BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
//        System.out.println(response);
        JuheResponse  responseResult = GsonUtils.fromJson(response.toString(), JuheResponse.class);

        if(responseResult.getResult() != null){
            return responseResult.getResult().getRes() == 1;
        }
        else{
            return false;
        }

    }

    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }
}
