package com.ygtx.common.utils.http;

import com.alibaba.fastjson2.JSON;
import com.ygtx.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * ICE SSO HTTP工具类
 * 
 * @author ruoyi
 */
@Component
public class IceSsoHttpUtil
{
    private static final Logger log = LoggerFactory.getLogger(IceSsoHttpUtil.class);
    
    @Autowired
    @Qualifier("iceSsoRestTemplate")
    private RestTemplate restTemplate;

    /**
     * 发送POST请求到ICE SSO接口
     * 
     * @param url 请求地址
     * @param params 请求参数
     * @return 响应内容
     */
    public String sendPostRequest(String url, Map<String, Object> params)
    {
        try 
        {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            // 构建请求体
            StringBuilder bodyBuilder = new StringBuilder();
            for (Map.Entry<String, Object> entry : params.entrySet()) 
            {
                if (bodyBuilder.length() > 0) 
                {
                    bodyBuilder.append("&");
                }
                bodyBuilder.append(entry.getKey())
                          .append("=")
                          .append(java.net.URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
            }
            
            HttpEntity<String> entity = new HttpEntity<>(bodyBuilder.toString(), headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            
            log.debug("ICE SSO请求成功，URL: {}, 参数: {}, 响应: {}", url, params, response.getBody());
            
            return response.getBody();
        } 
        catch (Exception e) 
        {
            log.error("发送ICE SSO请求失败，URL: " + url + ", 参数: " + params, e);
            return null;
        }
    }

    /**
     * 发送POST JSON请求到ICE SSO接口
     * 
     * @param url 请求地址
     * @param jsonData JSON数据
     * @return 响应内容
     */
    public String sendJsonPostRequest(String url, String jsonData)
    {
        try 
        {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            
            log.debug("ICE SSO JSON请求成功，URL: {}, 数据: {}, 响应: {}", url, jsonData, response.getBody());
            
            return response.getBody();
        } 
        catch (Exception e) 
        {
            log.error("发送ICE SSO JSON请求失败，URL: " + url + ", 数据: " + jsonData, e);
            return null;
        }
    }

    /**
     * 发送GET请求到ICE SSO接口
     * 
     * @param url 请求地址（包含查询参数）
     * @return 响应内容
     */
    public String sendGetRequest(String url)
    {
        try 
        {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            
            log.debug("ICE SSO GET请求成功，URL: {}, 响应: {}", url, response.getBody());
            
            return response.getBody();
        } 
        catch (Exception e) 
        {
            log.error("发送ICE SSO GET请求失败，URL: " + url, e);
            return null;
        }
    }

    /**
     * 验证ICE SSO响应格式
     * 
     * @param response 响应内容
     * @return 是否有效
     */
    public boolean isValidResponse(String response)
    {
        if (StringUtils.isEmpty(response)) 
        {
            return false;
        }
        
        try 
        {
            // 解析响应，检查基本格式
            Object obj = JSON.parse(response);
            return obj != null;
        } 
        catch (Exception e) 
        {
            log.warn("无效的ICE SSO响应格式", e);
            return false;
        }
    }
}