package com.pm.web.controller.meeting;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.pm.common.config.PageData;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.page.TableDataInfo;
import com.pm.interfaceInfo.service.InterfaceInfoService;
import com.pm.topology.service.IItemTopologyService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会议管理
 */
@RestController
@RequestMapping("/meeting/info")
public class MeetingController  extends BaseController
{

    @Autowired
    private InterfaceInfoService interfaceInfoService;

    //@PreAuthorize("@ss.hasPermi('device:control:list')")
    @GetMapping("/list")
    public String list()
    {
        PageData pd = this.getPageData();
        Response response = null;
        try{
            String name = "";
            String appoint_time = "";
            if (pd.containsKey("search")){
                name = pd.getString("search");
            }
            if (pd.containsKey("appoint_time")){
                appoint_time = pd.getString("appoint_time");
            }
            String info = "{\n" +
                    "  \"date\": \""+pd.getString("date")+"\",\n" +
                    "  \"search\": \""+name+"\",\n" +
                    "  \"locationId\": [],\n" +
                    "  \"capacity\": [],\n" +
                    "  \"deviceType\": [],\n" +
                    "  \"roomType\": [\n" +
                    "    -1\n" +
                    "  ],\n" +
                    "  \"appoint_time\": \""+appoint_time+"\",\n" +
                    "  \"status\": 1,\n" +
                    "  \"page\": "+pd.getInteger("pageNum")+",\n" +
                    "  \"page_size\": "+pd.getInteger("pageSize")+"\n" +
                    "}";
            PageData interface_info = interfaceInfoService.selectInterfaceInfoByName(pd.getString("interfaceName"));
            pd.put("url",interface_info.get("url"));
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, info);
            Request request = new Request.Builder()
                    .url(interface_info.getString("url"))
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            response = client.newCall(request).execute();
        } catch (Exception e){
            e.printStackTrace();
        }
        try {
            /*ObjectMapper objectMapper = new ObjectMapper();

            JsonNode rootNode = objectMapper.readTree(response.body().string());

            // 将 url 字段添加到 JSON 对象中
            if (rootNode.isObject()) {
                ObjectNode objectNode = (ObjectNode) rootNode;
                objectNode.put("url", pd.getString("url"));

                // 序列化 JSON 对象为字符串
                String modifiedBody = objectMapper.writeValueAsString(objectNode);
                return modifiedBody;
            } else {
                throw new RuntimeException("响应体不是有效的 JSON 对象");
            }*/
            return response.body().string();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取历史会议
     * @return
     */
    @GetMapping("/listHistory")
    public String listHistory() throws Exception {
        PageData pd = this.getPageData();
        // 获取接口地址
        PageData interface_info = interfaceInfoService.selectInterfaceInfoByName(pd.getString("interfaceName"));
        String url = interface_info.getString("url");

        // 构造请求参数
        Map<String, String> params = new HashMap<>();
        params.put("date", pd.getString("date"));
        params.put("search", pd.getString("search"));
        //params.put("appoint_time", );
        params.put("status", String.valueOf(pd.getInteger("status")));
        params.put("page", String.valueOf(pd.getInteger("pageNum")));
        params.put("pageSize", String.valueOf(pd.getInteger("pageSize")));
        params.put("locationId", ""); // 空数组
        params.put("capacity", "");  // 空数组
        params.put("deviceType", ""); // 空数组
        params.put("roomType", "-1");
        params.put("is_external", String.valueOf(pd.getInteger("is_external")));

        // 构造完整的 URL
        StringBuilder urlBuilder = new StringBuilder(url);
        boolean firstParam = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                if (firstParam) {
                    urlBuilder.append("?");
                    firstParam = false;
                } else {
                    urlBuilder.append("&");
                }
                urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
            }
        }

        // 使用 OkHttpClient 发送 GET 请求
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        Request request = new Request.Builder()
                .url(urlBuilder.toString())
                .method("GET", null)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("External API call failed with status code: " + response.code());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException("Error calling external API", e);
        }
    }
}
