package com.openhis.common.utils;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.springframework.web.multipart.MultipartFile;

import com.core.common.core.domain.R;
import com.core.common.utils.poi.ExcelUtil;

/**
 * 共通工具类
 *
 * @author system
 */
public class CommonUtil {

    /**
     * 尝试转化为int
     *
     * @param intStr int字符串
     * @return int值
     */
    public static Integer tryParseInt(String intStr) {
        try {
            return Integer.parseInt(intStr);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 读取导入的Excel文件
     * 
     * @param file 文件
     * @param clazz 转换的Class
     * @return 转换后的实体列表
     */
    public static <T> R<List<T>> readImportedExcelFile(MultipartFile file, Class<T> clazz) {
        ExcelUtil<T> util = new ExcelUtil<>(clazz);
        List<T> importDtoList;
        try {
            importDtoList = util.importExcel(file.getInputStream());
        } catch (IOException e) {
            return R.fail("导入失败！文件读取异常");
        }
        if (importDtoList.isEmpty()) {
            return R.fail("导入失败！文件不能为空");
        }
        return R.ok(importDtoList);
    }

    /**
     * 创建无视SSL验证的SSLSocketFactory
     */
    public static SSLConnectionSocketFactory createIgnoreSslSocketFactory() {
        try {
            // 创建信任所有证书的TrustManager
            X509TrustManager trustAllCert = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {}

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };

            // 初始化SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] {trustAllCert}, new SecureRandom());

            // 创建不验证主机名的SocketFactory
            return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE // 关键：禁用主机名验证
            );
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException("SSL配置失败", e);
        }
    }
}
