package com.muyu.data.mart.service.impl;

import com.muyu.data.mart.common.BasicApi;
import com.muyu.data.mart.domain.juhe.JuHeResult;
import com.muyu.data.mart.domain.realname.RealNameReq;
import com.muyu.data.mart.domain.realname.RealNameResp;
import com.muyu.data.mart.domain.realname.juhe.JuHeRealNameReq;
import com.muyu.data.mart.domain.realname.juhe.JuHeRealNameResp;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
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;

/**
 * @Author：chaiyapeng
 * @Package：com.muyu.data.mart.service.impl
 * @Project：cloud-port
 * @name：RealNameServiceImpl
 * @Date：2024/9/6 10:23
 *
 *聚合数据接口对接
 */
@Service("juhe-real-name")
public class RealNameServiceImpl implements BasicApi<RealNameReq, RealNameResp> {

    /**
     * 请求
     * @param realNameReq
     * @return
     */
    @Override
    public RealNameResp send(RealNameReq realNameReq) {

        JuHeRealNameReq juHeRealNameReq = JuHeRealNameReq.realNameReqBuilder(realNameReq);
        JuHeResult<JuHeRealNameResp> juHeRealNameRespJuHeResult = null;

        try {
            juHeRealNameRespJuHeResult = sendApi(juHeRealNameReq);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return RealNameResp.builder()
                .code(String.valueOf(juHeRealNameRespJuHeResult.getErrorCode()))
                .mag(juHeRealNameRespJuHeResult.getReason())
                .build();
    }

    public static String API_URL = "http://op.juhe.cn/idcard/query";
    // 接口请求Key
    public static String API_KEY = "3a2afc3ff97304c4f6b16325a99c34b0";
    public JuHeResult<JuHeRealNameResp> sendApi(JuHeRealNameReq juHeRealNameReq){
        HashMap<String, String> map = new HashMap<>();
        map.put("key", API_KEY);
        map.put("idcard", juHeRealNameReq.getIdCard());
        map.put("realname", juHeRealNameReq.getRealName());
        map.put("orderid", "");

        String queryString = params(map);
        URL url = null;
        try {
            url = new URL(API_URL + "?" + queryString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response);
            StringBuffer stringBuffer = new StringBuffer(response);
            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
            String reason = jsonObject.getString("reason");
            JSONObject resultObj = jsonObject.getJSONObject("result");
            String realname = resultObj.getString("realname");
            String idcard = resultObj.getString("idcard");
            int res = resultObj.getIntValue("res");
            int errorCode = jsonObject.getIntValue("error_code");
            return new JuHeResult<JuHeRealNameResp>(){{
                setErrorCode(errorCode);
                setReason(reason);
                setResult(
                        JuHeRealNameResp.builder()
                                .realName(realname)
                                .idCard(idcard)
                                .res(res)
                                .build()
                );
            }};
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


//        return new JuHeResult<JuHeRealNameResp>(){{
//           setErrorCode(0);
//           setReason("成功");
//           setResult(
//                   JuHeRealNameResp.builder()
//                           .realName(juHeRealNameReq.getRealName())
//                           .idCard(juHeRealNameReq.getIdCard())
//                           .res(0)
//                           .build()
//           );
//        }};
    }


    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("&"));
    }
}
