package com.fkzy.warn.common.util;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fkzy.warn.common.constants.LawResearchUrlConstants;
import com.fkzy.warn.model.InvocationRecord;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhangjing
 * @date 2026/03/17 14:31
 * @description
 */
public class FyOpenGatewayApiUtil {
    public static final String FY_OPEN_GATEWAY_URL = "https://api.cjbdi.com:8443";

    public static final String ACCESS_TOKEN_URL = FY_OPEN_GATEWAY_URL + "/auth/api/token/getAccess";

    /**
     * 请求开放平台网关获取accessToken
     *
     * @param url       调用地址
     * @param appKey    应用key--从控制台应用系统中获取
     * @param appSecret 应用密码--从控制台应用系统中获取
     * @return 返回数据格式参考在线文档说明
     */
    public static String getAccessToken(String url, String appKey, String appSecret) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appKey", appKey);
        paramMap.put("appSecret", appSecret);
        try {
            return HttpUtil.post(url, paramMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    /**
//     * 接口调用--url传参
//     *
//     * @param method    请求方法类型
//     * @param url       接口地址，包含url参数
//     * @param headerMap 请求头
//     * @return 返回数据格式参考在线文档说明
//     * @see cn.hutool.http.Method
//     */
//    public static String invokeUrlApi(Method method, String url, Map<String, String> headerMap) {
//        HttpRequest request = HttpUtil.createRequest(method, url);
//        request.headerMap(headerMap, true);
//        try (HttpResponse execute = request.execute()) {
//            int status = execute.getStatus();
//            if (status == 200) {
//                return execute.body();
//            }
//        }
//        return null;
//    }

//    /**
//     * 接口调用--form表单提交
//     *
//     * @param url        接口地址，包含url参数
//     * @param headerMap  请求头
//     * @param formParams form表单参数
//     * @return 返回数据格式参考在线文档说明
//     */
//    public static String invokeFormApi(String url, Map<String, String> headerMap, Map<String, Object> formParams) {
//        HttpRequest request = HttpUtil.createPost(url);
//        request.headerMap(headerMap, true);
//        request.form(formParams);
//        try (HttpResponse execute = request.execute()) {
//            int status = execute.getStatus();
//            if (status == 200) {
//                return execute.body();
//            }
//        }
//        return null;
//    }

//    /**
//     * 接口调用--body提交
//     *
//     * @param url       接口地址
//     * @param headerMap 请求头
//     * @param body      body参数
//     * @return 返回数据格式参考在线文档说明
//     */
//    public static String invokeBodyApi(String url, Map<String, String> headerMap, String body) {
//        HttpRequest request = HttpUtil.createPost(url);
//        request.headerMap(headerMap, true);
//        request.body(body);
//        try (HttpResponse execute = request.execute()) {
//            int status = execute.getStatus();
//            if (status == 200) {
//                return execute.body();
//            }
//        }
//        return null;
//    }


    public static void main(String[] args) {
        // 控制台应用系统中的apiKey
        String appKey = "";
        // 控制台应用系统中的apiSecret
        String appSecret = "";
        // 控制台应用系统中的appId
        String appId = "";

        // 请求获取accessToken
        String response = getAccessToken(ACCESS_TOKEN_URL, LawResearchUrlConstants.API_KEY, LawResearchUrlConstants.API_SECRET);
        System.out.println(response);

        // 构建请求头
        Map<String, String> headerMap = new HashMap<>();
        // 请求id，每次请求需重新生成，保证唯一。用于做重复请求验证
        headerMap.put("FYDN-OP-RequestId", UUID.randomUUID().toString().replaceAll("-", ""));
        // 签名串，使用在线文档中的MD5Util示例加密生成
        headerMap.put("FYDN-OP-Sign", "");
        // 需要从getAccessToken返回结果中解析出accessKey，返回结构样例参考在线文档
        headerMap.put("FYDN-OP-AccessToken", LawResearchUrlConstants.ACCESS_KEY);
        headerMap.put("FYDN-OP-AppID", LawResearchUrlConstants.APPID);
        // 调用的环境（prod:线上环境，默认；test:测试环境）
        headerMap.put("FYDN-OP-Env", "prod");
        // 用户所在系统的唯一标识
        headerMap.put("FYDN-OP-UserId", "");

        // 以下url、参数等为示例，以实际调用的信息为准
        /*--------------------------------json传参-----------------------------------*/
//        String jsonApiUrl = "http://127.0.0.1:8080/jsonApi";
//        headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue());
//        String body = "{\"name\":\"test\", \"age\":18}";
//        String jsonApiResult = FyOpenGatewayApiUtil.invokeBodyApi(jsonApiUrl, headerMap, body);
//        System.out.println(jsonApiResult);


//
//        /*--------------------------------form传参-----------------------------------*/
//        String formApiUrl = "http://127.0.0.1:8080/formApi";
//        // 普通form表单时，设置为application/x-www-form-urlencoded
//        headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.FORM_URLENCODED.getValue());
//        // 文件上传form表单提交时，设置为multipart/form-data
////        headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.MULTIPART.getValue());
//        Map<String, Object> formParams = new HashMap<>();
//        formParams.put("name", "test");
//        formParams.put("age", 18);
//        String formApiResult = FyOpenGatewayApiUtil.invokeFormApi(formApiUrl, headerMap, formParams);
//        System.out.println(formApiResult);
//
//        /*--------------------------------url传参-----------------------------------*/
//        String url = "http://127.0.0.1:8080/urlApi?name=test&age=18";
//        headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.FORM_URLENCODED.getValue());
//        String result = FyOpenGatewayApiUtil.invokeUrlApi(Method.GET, url, headerMap);
//        System.out.println(result);
    }
    private static InvocationRecord getData(String apiUrl, JSONArray array, JSONObject jsonObject, String method,
                                            String key, String ticket, String apiName
    ) {
        InvocationRecord invocationRecord = new InvocationRecord();
        invocationRecord.setApiKey(key);
        invocationRecord.setApiTicket(ticket);
        invocationRecord.setApiUrl(apiUrl);
        if (array!=null){
            invocationRecord.setInputArr(array.toJSONString());
        }
        if (jsonObject!=null){
            invocationRecord.setInputObj(jsonObject.toJSONString());
        }
        invocationRecord.setApiName(apiName);

        RestTemplate restTemplate = new RestTemplate();
        HttpComponentsClientHttpRequestFactory requestFactory
            = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectionRequestTimeout(60000);
        requestFactory.setConnectTimeout(60000);
        requestFactory.setReadTimeout(60000);
        restTemplate.setRequestFactory(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("ticket", ticket);
        headers.set("Authorization", ticket);
        String request = (array != null) ? array.toJSONString() : jsonObject.toJSONString();
        try {
            //需要对入参进行 aes 加密
            String requestBody = AES.aesEncrypt(request, key);
            System.out.println("requestBody=====" + requestBody);
            //设置访问的 Entity
            HttpEntity entity = new HttpEntity<>(requestBody, headers);
            //执行  请求

            ResponseEntity<String> result =
                restTemplate.exchange(apiUrl, method == null ? HttpMethod.POST : HttpMethod.GET, entity,
                    String.class);
            // 指定文件路径
            String filePath = "output.txt";
            String resultData=null;
            try (PrintWriter writer = new PrintWriter(new File(filePath))) {
                //接收到返回结果需要进行 aes 解密
                invocationRecord.setIsSuccess(0);
                resultData = AES.aesDecrypt(result.getBody(), key);
                //写入内容
                writer.println(resultData);
                invocationRecord.setIsSuccess(1);
                invocationRecord.setApiResult(resultData);
                // 自动关闭，因为使用了 try-with-resources 语句
            } catch (FileNotFoundException e) {
                System.err.println("文件未找到: " + e.getMessage());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return invocationRecord;
        }
    }
}
