package com.pm.web.controller.accessControl;

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("/accessControl/info")
public class AccessControlController  extends BaseController {


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

    // 模拟生成固定的门禁设备数据
    private List<Map<String, Object>> generateDoorDeviceData() {
        return Arrays.asList(
                // 同一位置设备分布（A座1楼大厅有3台设备）
                Map.of("id", "Device1", "location", "A座1楼大厅", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-01 08:00:00", "eventType", "正常通行", "actions", "解锁门", "processStatus", "已完成"),
                Map.of("id", "Device2", "location", "A座1楼大厅", "doorStatus", "关闭", "deviceStatus", "Offline", "lastEventTime", "2023-10-01 09:30:00", "eventType", "非法入侵", "actions", "触发警报", "processStatus", "待处理"),
                Map.of("id", "Device3", "location", "A座1楼大厅", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-01 10:15:00", "eventType", "正常通行", "actions", "解锁门", "processStatus", "已完成"),

                // B座2楼实验室有2台设备
                Map.of("id", "Device4", "location", "B座2楼实验室", "doorStatus", "关闭", "deviceStatus", "Offline", "lastEventTime", "2023-10-02 08:45:00", "eventType", "正常通行", "actions", "锁门", "processStatus", "已完成"),
                Map.of("id", "Device5", "location", "B座2楼实验室", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-02 14:20:00", "eventType", "火警触发", "actions", "触发警报", "processStatus", "进行中"),

                // C座3楼会议室有3台设备
                Map.of("id", "Device6", "location", "C座3楼会议室", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-03 09:00:00", "eventType", "正常通行", "actions", "解锁门", "processStatus", "已完成"),
                Map.of("id", "Device7", "location", "C座3楼会议室", "doorStatus", "关闭", "deviceStatus", "Offline", "lastEventTime", "2023-10-03 11:30:00", "eventType", "非法入侵", "actions", "触发警报", "processStatus", "待处理"),
                Map.of("id", "Device8", "location", "C座3楼会议室", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-03 16:45:00", "eventType", "正常通行", "actions", "解锁门", "processStatus", "已完成"),

                // D座4楼办公室有2台设备
                Map.of("id", "Device9", "location", "D座4楼办公室", "doorStatus", "关闭", "deviceStatus", "Offline", "lastEventTime", "2023-10-04 08:15:00", "eventType", "正常通行", "actions", "锁门", "processStatus", "已完成"),
                Map.of("id", "Device10", "location", "D座4楼办公室", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-04 15:30:00", "eventType", "火警触发", "actions", "触发警报", "processStatus", "进行中"),

                // E座5楼休息区有5台设备
                Map.of("id", "Device11", "location", "E座5楼休息区", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-05 09:45:00", "eventType", "正常通行", "actions", "解锁门", "processStatus", "已完成"),
                Map.of("id", "Device12", "location", "E座5楼休息区", "doorStatus", "关闭", "deviceStatus", "Offline", "lastEventTime", "2023-10-05 13:20:00", "eventType", "正常通行", "actions", "锁门", "processStatus", "已完成"),
                Map.of("id", "Device13", "location", "E座5楼休息区", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-05 16:10:00", "eventType", "非法入侵", "actions", "触发警报", "processStatus", "待处理"),
                Map.of("id", "Device14", "location", "E座5楼休息区", "doorStatus", "关闭", "deviceStatus", "Offline", "lastEventTime", "2023-10-05 18:45:00", "eventType", "正常通行", "actions", "锁门", "processStatus", "已完成"),
                Map.of("id", "Device15", "location", "E座5楼休息区", "doorStatus", "开启", "deviceStatus", "Online", "lastEventTime", "2023-10-05 20:30:00", "eventType", "火警触发", "actions", "触发警报", "processStatus", "进行中")
        );
    }
    private List<Map<String, Object>> generateAttendanceRecordsData() {
        return Arrays.asList(
            // 张伟（市场部） - 4次打卡（上班、午休外出、午休返回、下班）
            Map.of("employeeId", "E0001", "name", "张伟", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 08:30:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "上班打卡", "dailyAccessCount", 4),
            Map.of("employeeId", "E0001", "name", "张伟", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 12:00:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "午休外出", "dailyAccessCount", 4),
            Map.of("employeeId", "E0001", "name", "张伟", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 13:00:00", "accessResult", "成功", "attendanceStatus", "Absent", "relatedEvent", "午休返回", "dailyAccessCount", 4),
            Map.of("employeeId", "E0001", "name", "张伟", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 18:00:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "下班打卡", "dailyAccessCount", 4),

            // 李娜（市场部） - 3次打卡（上班、午休返回、下班）
            Map.of("employeeId", "E0002", "name", "李娜", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 08:35:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "上班打卡", "dailyAccessCount", 3),
            Map.of("employeeId", "E0002", "name", "李娜", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 13:10:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "午休返回", "dailyAccessCount", 3),
            Map.of("employeeId", "E0002", "name", "李娜", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 18:15:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "下班打卡", "dailyAccessCount", 3),

            // 王军（市场部） - 迟到（2次打卡）
            Map.of("employeeId", "E0003", "name", "王军", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 09:10:00", "accessResult", "失败", "attendanceStatus", "Absent", "relatedEvent", "上班迟到", "dailyAccessCount", 2),
            Map.of("employeeId", "E0003", "name", "王军", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 18:30:00", "accessResult", "成功", "attendanceStatus", "Absent", "relatedEvent", "下班打卡", "dailyAccessCount", 2),

            // 陈雨（市场部） - 4次打卡
            Map.of("employeeId", "E0004", "name", "陈雨", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 08:45:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "上班打卡", "dailyAccessCount", 4),
            Map.of("employeeId", "E0004", "name", "陈雨", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 12:15:00", "accessResult", "成功", "attendanceStatus", "Absent", "relatedEvent", "午休外出", "dailyAccessCount", 4),
            Map.of("employeeId", "E0004", "name", "陈雨", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 13:15:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "午休返回", "dailyAccessCount", 4),
            Map.of("employeeId", "E0004", "name", "陈雨", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 18:45:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "下班打卡", "dailyAccessCount", 4),

            // 刘畅（市场部） - 3次打卡
            Map.of("employeeId", "E0005", "name", "刘畅", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 08:20:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "上班打卡", "dailyAccessCount", 3),
            Map.of("employeeId", "E0005", "name", "刘畅", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 12:30:00", "accessResult", "成功", "attendanceStatus", "Absent", "relatedEvent", "午休外出", "dailyAccessCount", 3),
            Map.of("employeeId", "E0005", "name", "刘畅", "department", "市场部", "accessLocation", "A座1楼门禁", "accessTime", "2023-10-01 18:00:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "下班打卡", "dailyAccessCount", 3),

            // 周敏（研发部） - 4次打卡
            Map.of("employeeId", "E0006", "name", "周敏", "department", "研发部", "accessLocation", "B座2楼门禁", "accessTime", "2023-10-01 08:50:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "上班打卡", "dailyAccessCount", 4),
            Map.of("employeeId", "E0006", "name", "周敏", "department", "研发部", "accessLocation", "B座2楼门禁", "accessTime", "2023-10-01 12:10:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "午休外出", "dailyAccessCount", 4),
            Map.of("employeeId", "E0006", "name", "周敏", "department", "研发部", "accessLocation", "B座2楼门禁", "accessTime", "2023-10-01 13:20:00", "accessResult", "成功", "attendanceStatus", "Absent", "relatedEvent", "午休返回", "dailyAccessCount", 4),
            Map.of("employeeId", "E0006", "name", "周敏", "department", "研发部", "accessLocation", "B座2楼门禁", "accessTime", "2023-10-01 19:00:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "下班打卡", "dailyAccessCount", 4),

            // 吴浩（研发部） - 迟到（2次打卡）
            Map.of("employeeId", "E0007", "name", "吴浩", "department", "研发部", "accessLocation", "B座2楼门禁", "accessTime", "2023-10-01 09:40:00", "accessResult", "失败", "attendanceStatus", "Absent", "relatedEvent", "上班迟到", "dailyAccessCount", 2),
            Map.of("employeeId", "E0007", "name", "吴浩", "department", "研发部", "accessLocation", "B座2楼门禁", "accessTime", "2023-10-01 19:30:00", "accessResult", "成功", "attendanceStatus", "Absent", "relatedEvent", "下班打卡", "dailyAccessCount", 2),

            // 钱芳（财务部） - 3次打卡
            Map.of("employeeId", "E0012", "name", "钱芳", "department", "财务部", "accessLocation", "C座3楼门禁", "accessTime", "2023-10-01 18:15:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "下班打卡", "dailyAccessCount", 4),

            // 周珊（人力资源部） - 3次打卡
            Map.of("employeeId", "E0013", "name", "周珊", "department", "人力资源部", "accessLocation", "D座4楼门禁", "accessTime", "2023-10-01 08:35:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "上班打卡", "dailyAccessCount", 3),
            Map.of("employeeId", "E0013", "name", "周珊", "department", "人力资源部", "accessLocation", "D座4楼门禁", "accessTime", "2023-10-01 12:15:00", "accessResult", "成功", "attendanceStatus", "Present", "relatedEvent", "午休外出", "dailyAccessCount", 3)
        );
    }

    // 查询门禁设备状态（支持分页和条件查询）
    @GetMapping("/door-devices")
    public Map<String, Object> getDoorDevices() throws Exception {
        List<Map<String, Object>> data = generateDoorDeviceData();
        PageData pd = this.getPageData();
        String location = pd.getString("location");
        String deviceStatus = pd.getString("deviceStatus");
        String doorStatus = pd.getString("doorStatus");
        // 条件过滤
        if (location != null && !location.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("location").toString().contains(location))
                    .collect(Collectors.toList());
        }
        if (deviceStatus != null && !deviceStatus.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("deviceStatus").toString().equalsIgnoreCase(deviceStatus))
                    .collect(Collectors.toList());
        }
        if (doorStatus != null && !doorStatus.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("doorStatus").toString().equalsIgnoreCase(doorStatus))
                    .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;
    }

    // 查询考勤记录（支持分页和条件查询）
    @GetMapping("/attendance-records")
    public Map<String, Object> getAttendanceRecords() throws Exception {
        List<Map<String, Object>> data = generateAttendanceRecordsData();
        PageData pd = this.getPageData();
        String name = pd.getString("name");
        String attendanceStatus = pd.getString("attendanceStatus");
        // 条件过滤
        if (name != null && !name.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("name").toString().contains(name))
                    .collect(Collectors.toList());
        }
        if (attendanceStatus != null && !attendanceStatus.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("attendanceStatus").toString().equalsIgnoreCase(attendanceStatus))
                    .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);
        }
    }
}
