package com.zcloud.primeport.plan.mjDevice;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zcloud.primeport.domain.enums.FileTypeEnum;
import com.zcloud.primeport.domain.enums.SaveTypeEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class OauthUtil {

//    private final String publicKeyUrl = "https://192.168.42.194/evo-apigw/evo-oauth/1.0.0/oauth/public-key";

    @Value("${icc.clientId}")
    private String clientId;
    @Value("${icc.publicKeyUrl}")
    private String publicKeyUrl;
    @Value("${icc.clientSecret}")
    private String clientSecret;
    @Value("${icc.username}")
    private String username;
    @Value("${icc.password}")
    private String password;

    @Value("${icc.url}")
    private String iccUrl;
    @Value("${icc.request.getGenerateIdUrl}")
    private String iccGenerateIdUrl;
    @Value("${icc.request.getGenerateIdListUrl}")
    private String iccGenerateIdListUrl;
    @Value("${icc.request.imgInspectUrl}")
    private String iccImgInspectUrl;
    @Value("${icc.request.getDepartmentIdUrl}")
    private String iccDepartmentIdUrl;

    /**
     * 获取RestTemplate实例
     * @return RestTemplate实例
     */
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = null;
        try {
            // 创建一个信任所有证书的 SSL 上下文
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true)
                    .build();

            // 创建一个忽略主机名验证的 SSL 连接套接字工厂
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            // 创建 HttpClient
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();

            // 创建 ClientHttpRequestFactory
            ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

            // 创建 RestTemplate 并设置请求工厂
            restTemplate = new RestTemplate(requestFactory);

        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restTemplate;
    }

    /**
     * 获取公钥
     * @return 公钥字符串
     */
    public String getPublicKey() {
        ResponseEntity<String> response = getRestTemplate().getForEntity(publicKeyUrl, String.class);
        System.out.println("getPublicKey,response:"+response.getBody());
        Map data = (Map) JSON.parseObject(response.getBody(), new TypeReference<Map<String, Object>>(){}).get("data");
        String publicKey = data.get("publicKey").toString();
        System.out.println("getPublicKey, publicKey:"+ publicKey);
        return publicKey;
    }

    /**
     * 获取token
     * @return token
     * @date 2025-05-10
     * @author hyx
     */
    public String getToken() {
        String token = null;
        // 准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        //获取公钥
        OauthUtil oauthUtil = new OauthUtil();
        String publicKey = oauthUtil.getPublicKey();
        if (StringUtils.isEmpty(publicKey)) {
            System.out.println("get publicKey failed.");
        } else {
            try {
                // 准备请求体
                Map requestBody = new HashMap();
                requestBody.put("grant_type", "password");
                requestBody.put("username", username);
                requestBody.put("password", RSAUtils.encrypt(password,publicKey));
                requestBody.put("client_id", clientId);
                requestBody.put("client_secret", clientSecret);
                requestBody.put("public_key", publicKey);
                // 创建 HttpEntity 对象
                HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(requestBody), headers);
                System.out.println("getToken, request: " + JSON.toJSONString(requestBody));
                // 调用 POST 接口
                String url = iccUrl + "/evo-apigw/evo-oauth/1.0.0/oauth/extend/token";
                ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.POST, entity, String.class);
                // 输出响应内容
                System.out.println("getToken, response: " + response.getBody());
                Map responseBody = JSON.parseObject(response.getBody(), new TypeReference<Map<String, Object>>(){});
                Map data = (Map) responseBody.get("data");
                String code = (String) responseBody.get("code");
                if(!code.equals("0")){
                    System.out.println("get token failed.");
                }else {
                    String accessToken = data.get("access_token").toString();
                    String tokenType = data.get("token_type").toString();
                    token = tokenType + ' ' + accessToken;
                    System.out.println("getToken, token:" + token);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return token;
    }

    /**
     * 获取全局用户ID公用方法
     * @return 全局用户ID
     * @throws Exception
     * @date 2025-05-10
     * @author hyx
     */
    public Long getGenerateId() throws Exception {
        String body = HttpRequest.get(iccUrl + iccGenerateIdUrl).header("Authorization", getToken()).execute().body();
        JSONObject jsonObject = new JSONObject(body);
        if ("true".equals(jsonObject.get("success").toString())) {
            return new JSONObject(jsonObject.get("data")).getLong("id");
        }else {
            throw new RuntimeException("获取全局用户ID失败");
        }
    }

    /**
     * 获取全局用户ID列表公共方法
     * @param idCount 获取ID数量
     * @return List<Long>
     * @date 2025-05-10
     * @author hyx
     */
    public List<Long> getGenerateIdList(Integer idCount){
        String body = HttpRequest
                .get(iccUrl + iccGenerateIdListUrl + idCount)
                .header("Authorization", getToken())
                .execute()
                .body();
        JSONObject jsonObject = new JSONObject(body);
        if ("true".equals(jsonObject.get("success").toString())) {
            return JSON.parseObject(new JSONObject(jsonObject.get("data")).get("idList").toString(), new TypeReference<List<Long>>(){});
        }else {
            throw new RuntimeException("获取全局用户ID失败");
        }
    }

    /**
     * 图片质量检测公用方法
     *
     * @param map {@link FileTypeEnum}
     * 根据FileTypeEnum获取相应文件
     * @return R
     * @date 2025-05-10
     * @author hyx
     */
    public HashMap imgInspect(Map<String,Object> map) {
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("saveType", SaveTypeEnum.SAVE_TYPE3.getCode());
        requestMap.put("ossType",1);
        if (FileTypeEnum.FILE_TYPE1.getCode().equals(map.get("fileType"))){
            //文件格式
            requestMap.put("file", map.get("file"));
            requestMap.put("fileType", FileTypeEnum.FILE_TYPE1.getCode());
        } else if (FileTypeEnum.FILE_TYPE2.getCode().equals(map.get("fileType"))) {
            //url格式
            requestMap.put("fileUrl", map.get("fileUrl"));
            requestMap.put("fileType", FileTypeEnum.FILE_TYPE2.getCode());
        }else if (FileTypeEnum.FILE_TYPE3.getCode().equals(map.get("fileType"))) {
            //base64格式
            requestMap.put("fileBase64", map.get("fileBase64"));
            requestMap.put("fileType", FileTypeEnum.FILE_TYPE3.getCode());
        }
        String body = HttpRequest
                .post(iccUrl + iccImgInspectUrl)
                .contentType("multipart/form-data")
                .header("Authorization", getToken())
                .form(requestMap)
                .execute()
                .body();
        JSONObject jsonObject = new JSONObject(body);
        HashMap<String,Object> result = new HashMap<String,Object>();

        if ("true".equals(jsonObject.get("success").toString())) {
            if ("0".equals(jsonObject.getJSONObject("data").get("result"))){
                result.put("fileUrl",jsonObject.getJSONObject("data").get("fileUrl").toString());
                return result;
//                return R.ok("图片质检成功").put("fileUrl",jsonObject.getJSONObject("data").get("fileUrl").toString());
            }else {
                return result;
//                return R.error("图片质检失败");
            }
        }else {
            return result;
//            return R.error(jsonObject.get("errMsg").toString());
        }
    }

    /**
     * 获取全局部门ID公共方法
     * @return 全局部门ID
     * @throws Exception
     * @author hyx
     * @date 2025-05-12
     */
    public Long getDepartmentId() throws Exception {
        String body = HttpRequest.get(iccUrl + iccDepartmentIdUrl).header("Authorization", getToken()).execute().body();
        JSONObject jsonObject = new JSONObject(body);
        if ("true".equals(jsonObject.get("success").toString())) {
            return new JSONObject(jsonObject.get("data")).getLong("id");
        }else {
            throw new RuntimeException("获取全局部门ID失败");
        }
    }

    /**
     * 获取全局部门ID列表公共方法
     * @param idCount 获取ID数量
     * @return List<Long>
     * @author hyx
     * @date 2025-05-12
     */
    public List<Long> getDepartmentIdList(Integer idCount){
        String body = HttpRequest
                .get(iccUrl + iccGenerateIdListUrl + idCount)
                .header("Authorization", getToken())
                .execute()
                .body();
        JSONObject jsonObject = new JSONObject(body);
        if ("true".equals(jsonObject.get("success").toString())) {
            return JSON.parseObject(new JSONObject(jsonObject.get("data")).get("idList").toString(), new TypeReference<List<Long>>(){});
        }else {
            throw new RuntimeException("获取全局部门ID失败");
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(RSAUtils.encrypt("qinan@202604"
                ,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDM7pxra9uPw/0uFpEgnJXkWTYan9FTbWjNhDiOKogGageqGBjUnEcDpyCL9V8p6xl/gBTPHAJz4s29gWkqnvGiCFekKBCkEgfu4qgSQaMrDywK38C3ydHx/iCJ2u31HE2ULunO/LXQqVK4uUSGyX63Jy9Q/0rYwDUSsoov85FZMQIDAQAB"));
    }


}
