package com.hzya.frame.ttxofs.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hzya.frame.ttxofs.basics.ApiDtoCacheMap;
import com.hzya.frame.ttxofs.basics.ReturnMessageBasics;
import com.hzya.frame.ttxofs.dto.InterfaceParamByU8CApiDto;
import com.hzya.frame.ttxofs.dto.InterfaceParamDto;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.ttxofs.util.UrlTransUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.util.*;

/**
 * @Author：liuyang
 * @Package：com.hzya.frame.ttxofs.service.impl
 * @Project：kangarooDataCenterV3
 * @name：SalesBusinessServiceImpl
 * @Date：2024/7/30 11:40
 * @Filename：SalesBusinessServiceImpl
 */
@Service(value = "ofsUnifiedService")
public class OfsUnifiedServiceImpl implements OfsUnifiedService {

    Logger logger = LoggerFactory.getLogger(OfsUnifiedServiceImpl.class);

    @Override
    public ReturnMessageBasics unified(InterfaceParamDto interfaceParamDto) throws Exception {
        //从缓存中得到实体类
        interfaceParamDto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        ReturnMessageBasics returnMessageBasics = ApiDtoCacheMap.apiDtoCacheMap.get(interfaceParamDto.getApi());

        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

        String httpUrl = UrlTransUtil.urlTrans(interfaceParamDto);
        try {
            Map<String, String> params = new HashMap<>();
            params.put("data", interfaceParamDto.getData());
            String resultStr = postParams(httpUrl, params);
            if (resultStr != null && !"".equals(resultStr.trim())) {
                ReturnMessageBasics returnMessageBasics1 = JSON.parseObject(resultStr, returnMessageBasics.getClass());
                if ("0".equals(returnMessageBasics1.getCode()) && "false".equals(returnMessageBasics1.getError())) {
                    //成功
                    return returnMessageBasics1;
                } else {
                    //失败
                    Assert.state(false, "OFS接口抛出异常 原因：{}", returnMessageBasics1.getMsg());
                }
            } else {
                //2024年7月30日 12:06:22 接口没有返回任何解决
                Assert.state(false, "OFS接口没有返回任何内容");
            }

            // 设置连接超时和读取超时
//            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(300000) // 连接超时时间为60秒
//                    .setSocketTimeout(300000) // 读取超时时间为60秒
//                    .build();

//            HttpPost post = new HttpPost(httpUrl);
//            post.setHeader("Content-Type", "application/json;charset=UTF-8");
//            post.setConfig(requestConfig);
            //post.setHeader("charset", "utf-8");

//            ByteArrayEntity entity = new ByteArrayEntity(String.valueOf(interfaceParamDto.getData()).getBytes("UTF-8"));
//            entity.setContentType("application/json");
//            post.setEntity(entity);

//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("data", interfaceParamDto.getData());

//            StringEntity stringEntity = new StringEntity(jsonObject.toString(), Consts.UTF_8);
//            stringEntity.setContentType("application/json");
//            stringEntity.setContentEncoding("UTF-8");
//            post.setEntity(stringEntity);

//            HttpResponse response = closeableHttpClient.execute(post);
//            if (response != null && response.getEntity() != null) {
//                String resultStr = EntityUtils.toString(response.getEntity(), "UTF-8");
//                if (resultStr != null && !"".equals(resultStr.trim())) {
//                    return JSON.parseObject(resultStr, returnMessageBasics.getClass());
//                } else {
//                    //2024年7月30日 12:06:22 接口没有返回任何解决
//                    Assert.state(false, "接口没有返回任何内容 请求地址：{}", httpUrl);
//                }
//            }
        } catch (Exception e) {
            //2024年7月30日 12:03:53 抛出方法的调用者
            String msgError = StrUtil.format("拉取/推送失败，错误原因：{} 请求地址:{}", e.getMessage(), httpUrl);
            logger.error(msgError);
            Assert.state(false, msgError);
        } finally {
            try {
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (Exception e) {
                //2024年7月30日 12:04:20这里一般不会抛出异常，记录错误
                logger.error("执行closeableHttpClient.close();时抛出异常", e);
            }
        }
        return null;
    }


    //适用于post请求并传送form-data数据（同样适用于post的Raw类型的application-json格式）
    public static String postParams(String url, Map<String, String> params) {
        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().build();
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse res = null;
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            res = client.execute(post);
            HttpEntity entity = res.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                res.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    @Override
    public ReturnMessageBasics unifiedByU8CApi(InterfaceParamByU8CApiDto interfaceParamDto) throws Exception {
        //从缓存中得到实体类
        interfaceParamDto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        ReturnMessageBasics returnMessageBasics = ApiDtoCacheMap.apiDtoCacheMap.get(interfaceParamDto.getApi());

        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

        String httpUrl = UrlTransUtil.urlTransByU8CApi(interfaceParamDto);
        try {
            Map<String, String> params = new HashMap<>();
            params.put("data", interfaceParamDto.getData());
            String resultStr = postParams(httpUrl, params);
            if (resultStr != null && !"".equals(resultStr.trim())) {
                ReturnMessageBasics returnMessageBasics1 = JSON.parseObject(resultStr, returnMessageBasics.getClass());
                if ("0".equals(returnMessageBasics1.getCode()) && "false".equals(returnMessageBasics1.getError())) {
                    //成功
                    return returnMessageBasics1;
                } else {
                    //失败
                    Assert.state(false, "OFS接口抛出异常 原因：{}", returnMessageBasics1.getMsg());
                }
            } else {
                //2024年7月30日 12:06:22 接口没有返回任何解决
                Assert.state(false, "OFS接口没有返回任何内容");
            }

        } catch (Exception e) {
            //2024年7月30日 12:03:53 抛出方法的调用者
            String msgError = StrUtil.format("拉取/推送失败，错误原因：{} 请求地址:{}", e.getMessage(), httpUrl);
            logger.error(msgError);
            Assert.state(false, msgError);
        } finally {
            try {
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (Exception e) {
                //2024年7月30日 12:04:20这里一般不会抛出异常，记录错误
                logger.error("执行closeableHttpClient.close();时抛出异常", e);
            }
        }
        return null;
    }
}
