package com.pm.web.controller.driverInfo;

import com.pm.common.config.PageData;
import com.pm.common.core.controller.BaseController;
import com.pm.interfaceInfo.service.InterfaceInfoService;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 信息引导及发布系统接口
 */
@RestController
@RequestMapping("/driverInfo/info")
public class DriverInfoController  extends BaseController {


    /**
     * 查询url 访问接口
     */
    @Autowired
    private InterfaceInfoService interfaceInfoService;

    // 生成模拟数据
    private List<Map<String, Object>> generateDeviceData() {
        return Arrays.asList(
                Map.of("id", "DEV2024001", "name", "主入口LED屏", "location", "A栋大厅正门", "deviceType", "户外全彩", "status", "在线", "ipAddress", "192.168.1.10", "screenSize", "86英寸", "lastOnlineTime", "2025-05-30 10:23:15"),
                Map.of("id", "DEV2024002", "name", "电梯广告机", "location", "B1层电梯厅", "deviceType", "液晶广告机", "status", "离线", "ipAddress", "192.168.1.11", "screenSize", "55英寸", "lastOnlineTime", "2025-05-29 18:40:22"),
                Map.of("id", "DEV2024003", "name", "会议室投影", "location", "3F-301会议室", "deviceType", "激光投影", "status", "在线", "ipAddress", "192.168.1.12", "screenSize", "120英寸", "lastOnlineTime", "2025-05-30 09:15:33"),
                Map.of("id", "DEV2024004", "name", "停车场引导屏", "location", "P2层C区通道", "deviceType", "单色LED", "status", "故障", "ipAddress", "192.168.1.13", "screenSize", "-", "lastOnlineTime", "2025-05-28 14:57:01"),
                Map.of("id", "DEV2024005", "name", "餐厅信息屏", "location", "员工餐厅入口", "deviceType", "触摸一体机", "status", "在线", "ipAddress", "192.168.1.14", "screenSize", "65英寸", "lastOnlineTime", "2025-05-30 11:05:44"),
                Map.of("id", "DEV2024006", "name", "户外广告牌", "location", "园区南门", "deviceType", "全彩LED", "status", "在线", "ipAddress", "192.168.1.15", "screenSize", "320英寸", "lastOnlineTime", "2025-05-30 08:30:19"),
                Map.of("id", "DEV2024007", "name", "前台信息终端", "location", "总部服务台", "deviceType", "立式广告机", "status", "在线", "ipAddress", "192.168.1.16", "screenSize", "43英寸", "lastOnlineTime", "2025-05-30 10:44:37"),
                Map.of("id", "DEV2024008", "name", "仓库监控屏", "location", "物流中心D区", "deviceType", "监控电视", "status", "离线", "ipAddress", "192.168.1.17", "screenSize", "75英寸", "lastOnlineTime", "2025-05-27 16:20:58"),
                Map.of("id", "DEV2024009", "name", "展厅互动屏", "location", "创新展厅2号位", "deviceType", "触摸桌", "status", "在线", "ipAddress", "192.168.1.18", "screenSize", "85英寸", "lastOnlineTime", "2025-05-30 09:51:26"),
                Map.of("id", "DEV2024010", "name", "消防信息屏", "location", "安全通道1F", "deviceType", "应急屏", "status", "故障", "ipAddress", "192.168.1.19", "screenSize", "32英寸", "lastOnlineTime", "2025-05-29 22:10:05"),
                Map.of("id", "DEV2024011", "name", "户外气象屏", "location", "园区东广场", "deviceType", "全彩LED", "status", "在线", "ipAddress", "192.168.1.20", "screenSize", "240英寸", "lastOnlineTime", "2025-05-30 07:45:11"),
                Map.of("id", "DEV2024012", "name", "会议预约屏", "location", "行政楼2F走廊", "deviceType", "电子墨水屏", "status", "在线", "ipAddress", "192.168.1.21", "screenSize", "21.5英寸", "lastOnlineTime", "2025-05-30 10:30:48"),
                Map.of("id", "DEV2024013", "name", "医疗宣教屏", "location", "医务室门口", "deviceType", "壁挂广告机", "status", "离线", "ipAddress", "192.168.1.22", "screenSize", "50英寸", "lastOnlineTime", "2025-05-26 11:15:39"),
                Map.of("id", "DEV2024014", "name", "车间看板", "location", "生产车间3线", "deviceType", "工业电视", "status", "在线", "ipAddress", "192.168.1.23", "screenSize", "65英寸", "lastOnlineTime", "2025-05-30 08:17:54"),
                Map.of("id", "DEV2024015", "name", "访客登记屏", "location", "西门接待处", "deviceType", "触摸一体机", "status", "在线", "ipAddress", "192.168.1.24", "screenSize", "32英寸", "lastOnlineTime", "2025-05-30 11:22:06")
        );
    }

    // 查询信息引导及发布（支持分页和条件查询）
    @GetMapping("/driverList")
    public Map<String, Object> getDoorDevices() throws Exception {
        List<Map<String, Object>> data = generateDeviceData();
        PageData pd = this.getPageData();
        String location = pd.getString("location");
        String name = pd.getString("name");
        // 条件过滤
        if (location != null && !location.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("location").toString().contains(location))
                    .collect(Collectors.toList());
        }
        if (name != null && !name.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("name").toString().equalsIgnoreCase(name))
                    .collect(Collectors.toList());
        }

        // 分页逻辑
        int total = data.size();
        int fromIndex = (pd.getInteger("pageNum") - 1) * pd.getInteger("pageSize");
        int toIndex = Math.min(fromIndex + pd.getInteger("pageSize"), total);
        List<Map<String, Object>> pageData = data.subList(fromIndex, toIndex);

        // 返回结果
        Map<String, Object> response = Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", Map.of("list", pageData,"total", total)
        );
        return response;
    }

    /**
     * 查询门禁管理列表
     * @return
     */
    @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 {
            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);
        }
    }
}
