package cn.teammodel.utils;

import cn.teammodel.common.ErrorCode;
import cn.teammodel.config.exception.ServiceException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.core.env.Environment;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupUtil {

    private final Environment env;

     public GroupUtil(Environment env) {
         this.env = env;
     }
    public static Map<String, Object>  getGroupId(Object obj, GroupUtil groupUtil, HttpServletRequest request,String url) {
        Map<String, Object> mapper = new HashMap<>();
        String evnStr =  groupUtil.env.getProperty("spring.env");
        String apiUrl;
        if (evnStr != null && evnStr.equalsIgnoreCase("dev")) {
            apiUrl = "https://test.teammodel.cn" + url;

        }else  {

            apiUrl = "https://www.teammodel.cn" + url;
        }

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(apiUrl);

             //添加请求头
            httpPost.setHeader("Authorization", request.getHeader("Authorization"));
            httpPost.setHeader("X-Auth-Authtoken", request.getHeader("X-Auth-Authtoken"));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");

            // 设置请求体
            String jsonContent = JsonUtil.convertToJson(obj);
            //String requestBody = String.format("{\"school\":\"%s\"}","{\"name\":\"%s\"}","{\"periodId\":\"%s\"}", code,name,periodId);
            httpPost.setEntity(new StringEntity(jsonContent, ContentType.create("application/json", "UTF-8")));

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // 解析响应内容
                    String jsonString = EntityUtils.toString(entity);
                    ObjectMapper objectMapper = new ObjectMapper();
                    mapper = objectMapper.readValue(jsonString, TypeFactory.defaultInstance().constructMapType(Map.class, String.class, Object.class));
                }

                // 检查响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) throw new RuntimeException("Failed : HTTP error code : " + statusCode);
            } catch (IOException e) {
                throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据解析异常");
            }
        } catch (IOException e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "请求头异常");
        }
        return mapper;
    }


    public static List<Map<String, Object>> getUsers(Object obj, GroupUtil groupUtil, HttpServletRequest request, String url) {
        List<Map<String, Object>> mapper = new ArrayList<>();
        String evnStr =  groupUtil.env.getProperty("spring.env");
        String apiUrl;
        if (evnStr != null && evnStr.equalsIgnoreCase("dev")) {
            apiUrl = "https://test.teammodel.cn" + url;

        }else  {

            apiUrl = "https://www.teammodel.cn" + url;
        }

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(apiUrl);

            //添加请求头
            httpPost.setHeader("Authorization", request.getHeader("Authorization"));
            httpPost.setHeader("X-Auth-Authtoken", request.getHeader("X-Auth-Authtoken"));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");

            // 设置请求体
            String jsonContent = JsonUtil.convertToJson(obj);
            //String requestBody = String.format("{\"school\":\"%s\"}","{\"name\":\"%s\"}","{\"periodId\":\"%s\"}", code,name,periodId);
            httpPost.setEntity(new StringEntity(jsonContent, ContentType.create("application/json", "UTF-8")));

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // 解析响应内容
                    String jsonString = EntityUtils.toString(entity);
                    ObjectMapper objectMapper = new ObjectMapper();
                    mapper = objectMapper.readValue(
                            jsonString,
                            new TypeReference<List<Map<String, Object>>>(){}
                    );
                }

                // 检查响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) throw new RuntimeException("Failed : HTTP error code : " + statusCode);
            } catch (IOException e) {
                throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据解析异常");
            }
        } catch (IOException e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "请求头异常");
        }
        return mapper;
    }

    public static Map<String, Object> getTeacherInfo(Object obj, GroupUtil groupUtil, HttpServletRequest request,String url) {
        Map<String, Object> mapper = new HashMap<>();
        String evnStr =  groupUtil.env.getProperty("spring.env");
        String apiUrl;
        if (evnStr != null && evnStr.equalsIgnoreCase("dev")) {
            apiUrl = "https://gp-test.winteach.cn/"+url;

        }else  {

            apiUrl = "https://gp.winteach.cn/"+url;
        }

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(apiUrl);

            //添加请求头
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");

            // 设置请求体
            String jsonContent = JsonUtil.convertToJson(obj);
            httpPost.setEntity(new StringEntity(jsonContent, ContentType.create("application/json", "UTF-8")));

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // 解析响应内容
                    String jsonString = EntityUtils.toString(entity);
                    ObjectMapper objectMapper = new ObjectMapper();
                    mapper = objectMapper.readValue(jsonString, TypeFactory.defaultInstance().constructMapType(Map.class, String.class, Object.class));
                }

                // 检查响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) throw new RuntimeException("Failed : HTTP error code : " + statusCode);
            } catch (IOException e) {
                throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据解析异常");
            }
        } catch (IOException e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "请求头异常");
        }
        return mapper;
    }
}
