package com.dkl.web.util;

import com.alibaba.fastjson2.JSON;
import com.dkl.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Repository;

/**
 * @Author :rq
 * @Description : 通过应用id和应用code获取tolken
 * @Date :2025/06/30 09:12
 * @Param :
 * @return :
 **/
@Repository
public class BackendServiceToken {

    @Value("${outData.clientId}")
    String clientId;
    @Value("${outData.clientSecret}")
    String clientSecret;
    @Value("${outData.url}")
    String outUrl;
    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisCache redisCache;

    //获取访问平台接口需要的token
     public void  subsystemToken(String identification ) {
         String url = outUrl+"/ht/uaa/oauth/backendServiceToken";
         // 构建JSON格式的请求体
         String jsonInputString = "{\"clientId\":\"" + clientId + "\",\"clientSecret\":\"" + clientSecret + "\",\"yddh\":\"" + identification + "\"}";
         try {
             // 创建URL对象
             URL obj = new URL(url);
             // 打开连接
             HttpURLConnection con = (HttpURLConnection) obj.openConnection();

             // 设置请求方法为POST
             con.setRequestMethod("POST");
             // 设置请求头信息，指定内容类型为JSON
             con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
             // 设置接受的内容类型为JSON
             con.setRequestProperty("Accept", "application/json");

             // 允许输出请求体
             con.setDoOutput(true);

             // 发送请求体数据
             try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
                 wr.writeBytes(jsonInputString);
                 wr.flush();
             }

             // 获取响应码
             int responseCode = con.getResponseCode();
             System.out.println("Response Code: " + responseCode);

             // 读取响应数据
             try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                 String inputLine;
                 StringBuilder response = new StringBuilder();
                 while ((inputLine = in.readLine()) != null) {
                     response.append(inputLine);
                 }
                 // 打印响应数据
                 System.out.println("Response: " + response.toString());
                 // 解析JSON字符串
                 JSONObject jsonObject =  JSON.parseObject(response.toString());
                 // 获取嵌套的data对象
                 JSONObject dataObject = jsonObject.getJSONObject("data");
                  // 从data对象中提取access_token
                  String accessToken = dataObject.getString("access_token");
                 // 输出access_token
//                 System.out.println("Access Token: " + accessToken);
                 //access_token 存redis
                 redisCache.setCacheObject(identification,accessToken,expireTime, TimeUnit.MINUTES);

             }

         } catch (IOException e) {
             // 打印异常信息
             e.printStackTrace();
         }

     }


}
