package com.pm.web.controller.estateManagement;

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


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

    // 生成模拟数据 业主档案
    private List<Map<String, Object>> generateOwnerData() {
        return Arrays.asList(
                Map.of("ownerId", "OWN2024001", "name", "林建国", "buildingNo", "8栋", "roomNo", "101", "phone", "13800138000", "moveInDate", "2020-05-18", "emergencyContact", "林小伟", "parkingSpace", "A-01", "petInfo", "金毛犬，体重30kg"),
                Map.of("ownerId", "OWN2024002", "name", "刘文静", "buildingNo", "3栋", "roomNo", "202", "phone", "13500135000", "moveInDate", "2021-03-22", "emergencyContact", "张明", "parkingSpace", "B-12", "petInfo", "无"),
                Map.of("ownerId", "OWN2024003", "name", "王浩宇", "buildingNo", "5栋", "roomNo", "303", "phone", "13900139000", "moveInDate", "2019-12-05", "emergencyContact", "陈燕", "parkingSpace", "C-05", "petInfo", "布偶猫，已绝育"),
                Map.of("ownerId", "OWN2024004", "name", "赵敏", "buildingNo", "2栋", "roomNo", "404", "phone", "13600136000", "moveInDate", "2022-08-10", "emergencyContact", "赵亮", "parkingSpace", "D-18", "petInfo", "无"),
                Map.of("ownerId", "OWN2024005", "name", "陈思远", "buildingNo", "9栋", "roomNo", "505", "phone", "13700137000", "moveInDate", "2020-07-25", "emergencyContact", "李娜", "parkingSpace", "E-09", "petInfo", "鹦鹉，笼养"),
                Map.of("ownerId", "OWN2024006", "name", "周雨欣", "buildingNo", "6栋", "roomNo", "606", "phone", "13400134000", "moveInDate", "2023-01-15", "emergencyContact", "周建国", "parkingSpace", "F-20", "petInfo", "无"),
                Map.of("ownerId", "OWN2024007", "name", "吴俊杰", "buildingNo", "1栋", "roomNo", "707", "phone", "13300133000", "moveInDate", "2018-09-08", "emergencyContact", "吴敏", "parkingSpace", "G-03", "petInfo", "柴犬，疫苗齐全"),
                Map.of("ownerId", "OWN2024008", "name", "郑梦琪", "buildingNo", "4栋", "roomNo", "808", "phone", "13200132000", "moveInDate", "2021-11-30", "emergencyContact", "郑海涛", "parkingSpace", "H-15", "petInfo", "无"),
                Map.of("ownerId", "OWN2024009", "name", "王伟", "buildingNo", "7栋", "roomNo", "909", "phone", "13100131000", "moveInDate", "2020-04-12", "emergencyContact", "张婷", "parkingSpace", "I-07", "petInfo", "金鱼，5条"),
                Map.of("ownerId", "OWN2024010", "name", "李佳怡", "buildingNo", "10栋", "roomNo", "1010", "phone", "18800188000", "moveInDate", "2022-06-01", "emergencyContact", "李建军", "parkingSpace", "J-22", "petInfo", "无"),
                Map.of("ownerId", "OWN2024011", "name", "张雪", "buildingNo", "3栋", "roomNo", "1111", "phone", "18500185000", "moveInDate", "2023-03-18", "emergencyContact", "张强", "parkingSpace", "B-08", "petInfo", "乌龟，两只"),
                Map.of("ownerId", "OWN2024012", "name", "陈明", "buildingNo", "5栋", "roomNo", "1212", "phone", "18600186000", "moveInDate", "2019-07-20", "emergencyContact", "陈璐", "parkingSpace", "C-14", "petInfo", "无"),
                Map.of("ownerId", "OWN2024013", "name", "周思远", "buildingNo", "8栋", "roomNo", "1313", "phone", "18700187000", "moveInDate", "2021-02-28", "emergencyContact", "周洋", "parkingSpace", "A-16", "petInfo", "兔子，白色"),
                Map.of("ownerId", "OWN2024014", "name", "吴雨", "buildingNo", "6栋", "roomNo", "1414", "phone", "18900189000", "moveInDate", "2020-10-05", "emergencyContact", "吴静", "parkingSpace", "F-04", "petInfo", "无毛猫，需特殊照顾"),
                Map.of("ownerId", "OWN2024015", "name", "郑浩然", "buildingNo", "2栋", "roomNo", "1515", "phone", "18000180000", "moveInDate", "2022-12-31", "emergencyContact", "郑云", "parkingSpace", "D-24", "petInfo", "无")
        );
    }

    // 生成模拟数据 物业费用信息
    private List<Map<String, Object>> generateFeeData() {
        return Arrays.asList(
                Map.of("billId", "FEE2024001", "ownerId", "OWN2024001", "feeType", "物业费", "dueAmount", 800.00, "paidAmount", 800.00, "arrearsStatus", "已结清", "dueDate", "2024-05-31"),
                Map.of("billId", "FEE2024002", "ownerId", "OWN2024002", "feeType", "水费", "dueAmount", 56.80, "paidAmount", 0.00, "arrearsStatus", "未缴纳", "dueDate", "2024-05-20"),
                Map.of("billId", "FEE2024003", "ownerId", "OWN2024003", "feeType", "电费", "dueAmount", 123.50, "paidAmount", 123.50, "arrearsStatus", "已结清", "dueDate", "2024-05-15"),
                Map.of("billId", "FEE2024004", "ownerId", "OWN2024004", "feeType", "物业费", "dueAmount", 750.00, "paidAmount", 300.00, "arrearsStatus", "部分缴纳", "dueDate", "2024-06-30"),
                Map.of("billId", "FEE2024005", "ownerId", "OWN2024005", "feeType", "水费", "dueAmount", 48.20, "paidAmount", 48.20, "arrearsStatus", "已结清", "dueDate", "2024-05-25"),
                Map.of("billId", "FEE2024006", "ownerId", "OWN2024006", "feeType", "电费", "dueAmount", 98.70, "paidAmount", 0.00, "arrearsStatus", "未缴纳", "dueDate", "2024-05-10"),
                Map.of("billId", "FEE2024007", "ownerId", "OWN2024007", "feeType", "物业费", "dueAmount", 900.00, "paidAmount", 900.00, "arrearsStatus", "已结清", "dueDate", "2024-05-31"),
                Map.of("billId", "FEE2024008", "ownerId", "OWN2024008", "feeType", "水费", "dueAmount", 62.30, "paidAmount", 0.00, "arrearsStatus", "未缴纳", "dueDate", "2024-05-20"),
                Map.of("billId", "FEE2024009", "ownerId", "OWN2024009", "feeType", "电费", "dueAmount", 156.90, "paidAmount", 156.90, "arrearsStatus", "已结清", "dueDate", "2024-05-15"),
                Map.of("billId", "FEE2024010", "ownerId", "OWN2024010", "feeType", "物业费", "dueAmount", 850.00, "paidAmount", 500.00, "arrearsStatus", "部分缴纳", "dueDate", "2024-06-30"),
                Map.of("billId", "FEE2024011", "ownerId", "OWN2024011", "feeType", "水费", "dueAmount", 52.50, "paidAmount", 52.50, "arrearsStatus", "已结清", "dueDate", "2024-05-25"),
                Map.of("billId", "FEE2024012", "ownerId", "OWN2024012", "feeType", "电费", "dueAmount", 89.40, "paidAmount", 0.00, "arrearsStatus", "未缴纳", "dueDate", "2024-05-10"),
                Map.of("billId", "FEE2024013", "ownerId", "OWN2024013", "feeType", "物业费", "dueAmount", 780.00, "paidAmount", 780.00, "arrearsStatus", "已结清", "dueDate", "2024-05-31"),
                Map.of("billId", "FEE2024014", "ownerId", "OWN2024014", "feeType", "水费", "dueAmount", 59.10, "paidAmount", 0.00, "arrearsStatus", "未缴纳", "dueDate", "2024-05-20"),
                Map.of("billId", "FEE2024015", "ownerId", "OWN2024015", "feeType", "电费", "dueAmount", 112.20, "paidAmount", 112.20, "arrearsStatus", "已结清", "dueDate", "2024-05-15")
        );
    }

    // 生成模拟数据 设施设备信息
    private List<Map<String, Object>> generateFacilityData() {
        return Arrays.asList(
                Map.of("deviceId", "DEV2024001", "name", "乘客电梯", "deviceType", "电梯", "location", "1栋1单元", "brandModel", "通力KONE 3000", "maintenanceCycle", "15天", "status", "正常", "lastMaintenanceDate", "2024-05-20"),
                Map.of("deviceId", "DEV2024002", "name", "消防水泵", "deviceType", "水泵", "location", "地下车库B区", "brandModel", "上海东方泵业 D120-50", "maintenanceCycle", "30天", "status", "正常", "lastMaintenanceDate", "2024-05-10"),
                Map.of("deviceId", "DEV2024003", "name", "配电箱", "deviceType", "配电箱", "location", "3栋负一层", "brandModel", "施耐德 Electric iPM", "maintenanceCycle", "90天", "status", "正常", "lastMaintenanceDate", "2024-04-30"),
                Map.of("deviceId", "DEV2024004", "name", "中央空调主机", "deviceType", "空调", "location", "设备机房", "brandModel", "大金 VRV-X7", "maintenanceCycle", "60天", "status", "待维保", "lastMaintenanceDate", "2024-03-25"),
                Map.of("deviceId", "DEV2024005", "name", "自动扶梯", "deviceType", "电梯", "location", "商业中心1楼", "brandModel", "迅达 Schindler 9300AE", "maintenanceCycle", "15天", "status", "正常", "lastMaintenanceDate", "2024-05-18"),
                Map.of("deviceId", "DEV2024006", "name", "生活水泵", "deviceType", "水泵", "location", "水泵房", "brandModel", "格兰富 CR32-4", "maintenanceCycle", "30天", "status", "正常", "lastMaintenanceDate", "2024-05-05"),
                Map.of("deviceId", "DEV2024007", "name", "消防控制柜", "deviceType", "消防设备", "location", "1栋消防控制室", "brandModel", "北大青鸟 JBF-11S", "maintenanceCycle", "60天", "status", "正常", "lastMaintenanceDate", "2024-04-20"),
                Map.of("deviceId", "DEV2024008", "name", "电梯", "deviceType", "电梯", "location", "2栋2单元", "brandModel", "日立 HGP-825-C090", "maintenanceCycle", "15天", "status", "维修中", "lastMaintenanceDate", "2024-05-15"),
                Map.of("deviceId", "DEV2024009", "name", "配电箱", "deviceType", "配电箱", "location", "5栋首层", "brandModel", "ABB MNS", "maintenanceCycle", "90天", "status", "正常", "lastMaintenanceDate", "2024-04-10"),
                Map.of("deviceId", "DEV2024010", "name", "景观喷泉泵", "deviceType", "水泵", "location", "中心花园", "brandModel", "威乐 WILO-SL 202", "maintenanceCycle", "45天", "status", "正常", "lastMaintenanceDate", "2024-05-01"),
                Map.of("deviceId", "DEV2024011", "name", "电梯", "deviceType", "电梯", "location", "3栋3单元", "brandModel", "通力KONE MonoSpace", "maintenanceCycle", "15天", "status", "正常", "lastMaintenanceDate", "2024-05-22"),
                Map.of("deviceId", "DEV2024012", "name", "消防栓泵", "deviceType", "水泵", "location", "地下车库A区", "brandModel", "凯泉 KQL200/315-45/4", "maintenanceCycle", "30天", "status", "正常", "lastMaintenanceDate", "2024-05-08"),
                Map.of("deviceId", "DEV2024013", "name", "监控主机", "deviceType", "监控设备", "location", "物业监控室", "brandModel", "海康威视 DS-8664N-I8", "maintenanceCycle", "60天", "status", "正常", "lastMaintenanceDate", "2024-04-15"),
                Map.of("deviceId", "DEV2024014", "name", "电梯", "deviceType", "电梯", "location", "4栋1单元", "brandModel", "奥的斯 Gen2", "maintenanceCycle", "15天", "status", "待维保", "lastMaintenanceDate", "2024-03-28"),
                Map.of("deviceId", "DEV2024015", "name", "配电箱", "deviceType", "配电箱", "location", "6栋负一层", "brandModel", "西门子 SIVACON 8PS", "maintenanceCycle", "90天", "status", "正常", "lastMaintenanceDate", "2024-04-05")
        );
    }

    // 生成模拟数据 安防监控中心
    private List<Map<String, Object>> generateSecurityData() {
        return Arrays.asList(
                Map.of("cameraId", "CAM2024001", "location", "园区南门", "status", "在线", "storagePath", "/video/2024/CAM2024001", "lastTriggerTime", "2024-05-30 14:23:15", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024002", "location", "1栋电梯厅", "status", "故障", "storagePath", "/video/2024/CAM2024002", "lastTriggerTime", "2024-05-29 09:40:22", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024003", "location", "地下车库B区", "status", "在线", "storagePath", "/video/2024/CAM2024003", "lastTriggerTime", "2024-05-30 10:15:33", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024004", "location", "中心花园", "status", "在线", "storagePath", "/video/2024/CAM2024004", "lastTriggerTime", "2024-05-28 14:57:01", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024005", "location", "商业中心1楼", "status", "在线", "storagePath", "/video/2024/CAM2024005", "lastTriggerTime", "2024-05-30 11:05:44", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024006", "location", "3栋走廊", "status", "故障", "storagePath", "/video/2024/CAM2024006", "lastTriggerTime", "2024-05-30 08:30:19", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024007", "location", "消防通道", "status", "在线", "storagePath", "/video/2024/CAM2024007", "lastTriggerTime", "2024-05-30 10:44:37", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024008", "location", "停车场入口", "status", "在线", "storagePath", "/video/2024/CAM2024008", "lastTriggerTime", "2024-05-27 16:20:58", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024009", "location", "2栋电梯厅", "status", "在线", "storagePath", "/video/2024/CAM2024009", "lastTriggerTime", "2024-05-30 09:51:26", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024010", "location", "设备机房", "status", "故障", "storagePath", "/video/2024/CAM2024010", "lastTriggerTime", "2024-05-29 22:10:05", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024011", "location", "园区东门", "status", "在线", "storagePath", "/video/2024/CAM2024011", "lastTriggerTime", "2024-05-30 07:45:11", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024012", "location", "行政楼大厅", "status", "在线", "storagePath", "/video/2024/CAM2024012", "lastTriggerTime", "2024-05-30 10:30:48", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024013", "location", "食堂后厨", "status", "在线", "storagePath", "/video/2024/CAM2024013", "lastTriggerTime", "2024-05-26 11:15:39", "alarmType", "人脸识别"),
                Map.of("cameraId", "CAM2024014", "location", "4栋楼梯间", "status", "在线", "storagePath", "/video/2024/CAM2024014", "lastTriggerTime", "2024-05-30 08:17:54", "alarmType", "越界报警"),
                Map.of("cameraId", "CAM2024015", "location", "监控室", "status", "在线", "storagePath", "/video/2024/CAM2024015", "lastTriggerTime", "2024-05-30 11:22:06", "alarmType", "人脸识别")
        );
    }

    // 生成模拟数据 工单管理
    private List<Map<String, Object>> generateWorkOrderData() {
        return Arrays.asList(
                Map.of("orderId", "WO2024001", "submitter", "林建国", "type", "维修", "urgency", "紧急", "handler", "张三", "status", "处理中", "duration", "2.5小时"),
                Map.of("orderId", "WO2024002", "submitter", "刘文静", "type", "清洁", "urgency", "普通", "handler", "李四", "status", "待接单", "duration", "-"),
                Map.of("orderId", "WO2024003", "submitter", "王浩宇", "type", "投诉", "urgency", "普通", "handler", "-", "status", "待接单", "duration", "-"),
                Map.of("orderId", "WO2024004", "submitter", "赵敏", "type", "维修", "urgency", "紧急", "handler", "王五", "status", "完成", "duration", "4小时"),
                Map.of("orderId", "WO2024005", "submitter", "陈思远", "type", "清洁", "urgency", "普通", "handler", "赵六", "status", "处理中", "duration", "1.5小时"),
                Map.of("orderId", "WO2024006", "submitter", "周雨欣", "type", "投诉", "urgency", "紧急", "handler", "陈七", "status", "完成", "duration", "3小时"),
                Map.of("orderId", "WO2024007", "submitter", "吴俊杰", "type", "维修", "urgency", "普通", "handler", "周八", "status", "待接单", "duration", "-"),
                Map.of("orderId", "WO2024008", "submitter", "郑梦琪", "type", "清洁", "urgency", "普通", "handler", "吴九", "status", "处理中", "duration", "2小时"),
                Map.of("orderId", "WO2024009", "submitter", "王伟", "type", "投诉", "urgency", "紧急", "handler", "郑十", "status", "完成", "duration", "2.5小时"),
                Map.of("orderId", "WO2024010", "submitter", "李佳怡", "type", "维修", "urgency", "普通", "handler", "王十一", "status", "待接单", "duration", "-"),
                Map.of("orderId", "WO2024011", "submitter", "张雪", "type", "清洁", "urgency", "普通", "handler", "李十二", "status", "完成", "duration", "1小时"),
                Map.of("orderId", "WO2024012", "submitter", "陈明", "type", "投诉", "urgency", "紧急", "handler", "张十三", "status", "处理中", "duration", "3.5小时"),
                Map.of("orderId", "WO2024013", "submitter", "周思远", "type", "维修", "urgency", "紧急", "handler", "陈十四", "status", "完成", "duration", "5小时"),
                Map.of("orderId", "WO2024014", "submitter", "吴雨", "type", "清洁", "urgency", "普通", "handler", "周十五", "status", "待接单", "duration", "-"),
                Map.of("orderId", "WO2024015", "submitter", "郑浩然", "type", "投诉", "urgency", "普通", "handler", "吴十六", "status", "处理中", "duration", "2小时")
        );
    }

    // 能源监测台
    private List<Map<String, Object>> generateEnergyData() {
        return Arrays.asList(
                Map.of("meterId", "EM2024001", "buildingNo", "1栋", "lastMonthReading", 1250.0, "currentMonthReading", 1380.0, "warningValue", 1500.0, "yoyChange", "+10.4%"),
                Map.of("meterId", "EM2024002", "buildingNo", "2栋", "lastMonthReading", 860.0, "currentMonthReading", 920.0, "warningValue", 1000.0, "yoyChange", "+6.9%"),
                Map.of("meterId", "EM2024003", "buildingNo", "3栋", "lastMonthReading", 2300.0, "currentMonthReading", 2550.0, "warningValue", 2800.0, "yoyChange", "+10.9%"),
                Map.of("meterId", "EM2024004", "buildingNo", "4栋", "lastMonthReading", 1500.0, "currentMonthReading", 1680.0, "warningValue", 1800.0, "yoyChange", "+12.0%"),
                Map.of("meterId", "EM2024005", "buildingNo", "5栋", "lastMonthReading", 950.0, "currentMonthReading", 1020.0, "warningValue", 1100.0, "yoyChange", "+7.4%"),
                Map.of("meterId", "EM2024006", "buildingNo", "6栋", "lastMonthReading", 3200.0, "currentMonthReading", 3500.0, "warningValue", 3800.0, "yoyChange", "+9.4%"),
                Map.of("meterId", "EM2024007", "buildingNo", "7栋", "lastMonthReading", 1800.0, "currentMonthReading", 1950.0, "warningValue", 2100.0, "yoyChange", "+8.3%"),
                Map.of("meterId", "EM2024008", "buildingNo", "8栋", "lastMonthReading", 2100.0, "currentMonthReading", 2320.0, "warningValue", 2500.0, "yoyChange", "+10.5%"),
                Map.of("meterId", "EM2024009", "buildingNo", "9栋", "lastMonthReading", 1450.0, "currentMonthReading", 1580.0, "warningValue", 1700.0, "yoyChange", "+8.9%"),
                Map.of("meterId", "EM2024010", "buildingNo", "10栋", "lastMonthReading", 2800.0, "currentMonthReading", 3050.0, "warningValue", 3300.0, "yoyChange", "+8.9%"),
                Map.of("meterId", "EM2024011", "buildingNo", "11栋", "lastMonthReading", 1650.0, "currentMonthReading", 1780.0, "warningValue", 1950.0, "yoyChange", "+7.9%"),
                Map.of("meterId", "EM2024012", "buildingNo", "12栋", "lastMonthReading", 3100.0, "currentMonthReading", 3420.0, "warningValue", 3700.0, "yoyChange", "+10.3%"),
                Map.of("meterId", "EM2024013", "buildingNo", "13栋", "lastMonthReading", 1900.0, "currentMonthReading", 2050.0, "warningValue", 2200.0, "yoyChange", "+7.9%"),
                Map.of("meterId", "EM2024014", "buildingNo", "14栋", "lastMonthReading", 2400.0, "currentMonthReading", 2650.0, "warningValue", 2900.0, "yoyChange", "+10.4%"),
                Map.of("meterId", "EM2024015", "buildingNo", "15栋", "lastMonthReading", 1750.0, "currentMonthReading", 1890.0, "warningValue", 2050.0, "yoyChange", "+8.0%")
        );
    }

    //租赁资产管家
    private List<Map<String, Object>> generateRentalData() {
        return Arrays.asList(
                Map.of("propertyId", "PROP2024001", "area", 89.5, "layout", "两室一厅", "monthlyRent", 3200.0, "tenant", "张明", "contractStart", "2024-01-15", "contractEnd", "2025-01-14", "depositStatus", "已收", "history", "2023年租给李华"),
                Map.of("propertyId", "PROP2024002", "area", 120.3, "layout", "三室两厅", "monthlyRent", 4500.0, "tenant", "王芳", "contractStart", "2024-03-20", "contractEnd", "2025-03-19", "depositStatus", "已收", "history", "2022年租给赵强"),
                Map.of("propertyId", "PROP2024003", "area", 65.2, "layout", "一室一厅", "monthlyRent", 2500.0, "tenant", "李强", "contractStart", "2024-02-05", "contractEnd", "2025-02-04", "depositStatus", "已收", "history", "2023年租给刘洋"),
                Map.of("propertyId", "PROP2024004", "area", 140.8, "layout", "四室两厅", "monthlyRent", 6800.0, "tenant", "赵敏", "contractStart", "2024-01-10", "contractEnd", "2025-01-09", "depositStatus", "已收", "history", "2022年租给陈明"),
                Map.of("propertyId", "PROP2024005", "area", 95.7, "layout", "两室两厅", "monthlyRent", 3800.0, "tenant", "陈丽", "contractStart", "2024-04-01", "contractEnd", "2025-03-31", "depositStatus", "已收", "history", "2023年租给周佳"),
                Map.of("propertyId", "PROP2024006", "area", 75.3, "layout", "一室一厅", "monthlyRent", 2800.0, "tenant", "周明", "contractStart", "2024-03-15", "contractEnd", "2025-03-14", "depositStatus", "已收", "history", "2022年租给吴昊"),
                Map.of("propertyId", "PROP2024007", "area", 110.2, "layout", "三室一厅", "monthlyRent", 4200.0, "tenant", "吴佳", "contractStart", "2024-02-20", "contractEnd", "2025-02-19", "depositStatus", "已收", "history", "2023年租给郑华"),
                Map.of("propertyId", "PROP2024008", "area", 80.5, "layout", "两室一厅", "monthlyRent", 3300.0, "tenant", "郑丽", "contractStart", "2024-01-25", "contractEnd", "2025-01-24", "depositStatus", "已收", "history", "2022年租给王磊"),
                Map.of("propertyId", "PROP2024009", "area", 135.6, "layout", "四室两厅", "monthlyRent", 6500.0, "tenant", "王强", "contractStart", "2024-03-05", "contractEnd", "2025-03-04", "depositStatus", "已收", "history", "2023年租给赵丽"),
                Map.of("propertyId", "PROP2024010", "area", 90.2, "layout", "两室两厅", "monthlyRent", 3600.0, "tenant", "赵丽", "contractStart", "2024-02-10", "contractEnd", "2025-02-09", "depositStatus", "已收", "history", "2022年租给陈晨"),
                Map.of("propertyId", "PROP2024011", "area", 70.8, "layout", "一室一厅", "monthlyRent", "2600.0", "tenant", "陈晨", "contractStart", "2024-04-15", "contractEnd", "2025-04-14", "depositStatus", "已收", "history", "2023年租给周明"),
                Map.of("propertyId", "PROP2024012", "area", 125.4, "layout", "三室两厅", "monthlyRent", 4800.0, "tenant", "周佳", "contractStart", "2024-03-20", "contractEnd", "2025-03-19", "depositStatus", "已收", "history", "2022年租给吴佳"),
                Map.of("propertyId", "PROP2024013", "area", 85.3, "layout", "两室一厅", "monthlyRent", 3400.0, "tenant", "吴昊", "contractStart", "2024-01-30", "contractEnd", "2025-01-29", "depositStatus", "已收", "history", "2023年租给郑丽"),
                Map.of("propertyId", "PROP2024014", "area", 115.7, "layout", "三室一厅", "monthlyRent", 4400.0, "tenant", "郑华", "contractStart", "2024-02-15", "contractEnd", "2025-02-14", "depositStatus", "已收", "history", "2022年租给王强"),
                Map.of("propertyId", "PROP2024015", "area", 98.6, "layout", "两室两厅", "monthlyRent", 3900.0, "tenant", "王磊", "contractStart", "2024-03-01", "contractEnd", "2025-02-28", "depositStatus", "已收", "history", "2023年租给赵丽")
        );
    }

    //服务工单分析
    private List<Map<String, Object>> generateWorkOrderAnalysisData() {
        return Arrays.asList(
            // 2024年数据
            Map.of("month", "2024-01", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-02", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-03", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-04", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-05", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-06", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-07", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-08", "completionRate", 92.5, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.5, "topIssue", "设备故障"),
            Map.of("month", "2024-09", "completionRate", 94.3, "avgResponseTime", 2.4, "reworkRate", 2.9, "satisfactionScore", 4.6, "topIssue", "公共区域卫生"),
            Map.of("month", "2024-10", "completionRate", 91.8, "avgResponseTime", 3.1, "reworkRate", 3.5, "satisfactionScore", 4.3, "topIssue", "停车管理"),
            Map.of("month", "2024-11", "completionRate", 95.7, "avgResponseTime", 2.2, "reworkRate", 2.3, "satisfactionScore", 4.7, "topIssue", "电梯维护"),
            Map.of("month", "2024-12", "completionRate", 93.9, "avgResponseTime", 2.6, "reworkRate", 3.0, "satisfactionScore", 4.5, "topIssue", "公共设施维修"),
            // 2025年数据
            Map.of("month", "2025-01", "completionRate", 92.8, "avgResponseTime", 2.7, "reworkRate", 3.1, "satisfactionScore", 4.4, "topIssue", "设备故障"),
            Map.of("month", "2025-02", "completionRate", 96.1, "avgResponseTime", 2.0, "reworkRate", 2.2, "satisfactionScore", 4.8, "topIssue", "公共区域卫生"),
            Map.of("month", "2025-03", "completionRate", 94.7, "avgResponseTime", 2.3, "reworkRate", 2.8, "satisfactionScore", 4.6, "topIssue", "停车管理"),
            Map.of("month", "2025-04", "completionRate", 93.2, "avgResponseTime", 2.5, "reworkRate", 2.9, "satisfactionScore", 4.5, "topIssue", "电梯维护"),
            Map.of("month", "2025-05", "completionRate", 95.4, "avgResponseTime", 2.1, "reworkRate", 2.4, "satisfactionScore", 4.7, "topIssue", "公共设施维修"),
            Map.of("month", "2025-06", "completionRate", 92.6, "avgResponseTime", 2.8, "reworkRate", 3.2, "satisfactionScore", 4.4, "topIssue", "设备故障"),
            Map.of("month", "2025-07", "completionRate", 94.9, "avgResponseTime", 2.3, "reworkRate", 2.7, "satisfactionScore", 4.6, "topIssue", "公共区域卫生"),
            Map.of("month", "2025-08", "completionRate", 93.5, "avgResponseTime", 2.6, "reworkRate", 3.0, "satisfactionScore", 4.5, "topIssue", "停车管理"),
            Map.of("month", "2025-09", "completionRate", 95.8, "avgResponseTime", 2.0, "reworkRate", 2.2, "satisfactionScore", 4.8, "topIssue", "电梯维护"),
            Map.of("month", "2025-10", "completionRate", 94.2, "avgResponseTime", 2.4, "reworkRate", 2.8, "satisfactionScore", 4.6, "topIssue", "公共设施维修")
        );
    }

    // 查询业主档案（支持分页和条件查询）
    @GetMapping("/estateManagementList")
    public Map<String, Object> getDoorDevices() throws Exception {
        List<Map<String, Object>> data = generateOwnerData();
        PageData pd = this.getPageData();
        String roomNo = pd.getString("roomNo");
        String name = pd.getString("name");
        // 条件过滤
        if (roomNo != null && !roomNo.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("roomNo").toString().contains(roomNo))
                    .collect(Collectors.toList());
        }
        if (name != null && !name.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("name").toString().contains(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
     * @throws Exception
     */
    @GetMapping("/estateManagementFeeDataList")
    public Map<String, Object> getFeeData() throws Exception {
        List<Map<String, Object>> data = generateFeeData();
        PageData pd = this.getPageData();
        String billId = pd.getString("billId");
        String feeType = pd.getString("feeType");
        // 条件过滤
        if (billId != null && !billId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("billId").toString().contains(billId))
                    .collect(Collectors.toList());
        }
        if (feeType != null && !feeType.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("feeType").toString().equalsIgnoreCase(feeType))
                    .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
     * @throws Exception
     */
    @GetMapping("/estateManagementFacilityDataList")
    public Map<String, Object> getFacilityData() throws Exception {
        List<Map<String, Object>> data = generateFacilityData();
        PageData pd = this.getPageData();
        String deviceId = pd.getString("deviceId");
        String deviceType = pd.getString("deviceType");
        // 条件过滤
        if (deviceId != null && !deviceId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("deviceId").toString().contains(deviceId))
                    .collect(Collectors.toList());
        }
        if (deviceType != null && !deviceType.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("deviceType").toString().equalsIgnoreCase(deviceType))
                    .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
     * @throws Exception
     */
    @GetMapping("/estateManagementSecurityDataList")
    public Map<String, Object> getSecurityData() throws Exception {
        List<Map<String, Object>> data = generateSecurityData();
        PageData pd = this.getPageData();
        String cameraId = pd.getString("cameraId");
        String location = pd.getString("location");
        // 条件过滤
        if (cameraId != null && !cameraId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("cameraId").toString().contains(cameraId))
                    .collect(Collectors.toList());
        }
        if (location != null && !location.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("location").toString().contains(location))
                    .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
     * @throws Exception
     */
    @GetMapping("/estateManagementWorkOrderDataList")
    public Map<String, Object> getWorkOrderData() throws Exception {
        List<Map<String, Object>> data = generateWorkOrderData();
        PageData pd = this.getPageData();
        String orderId = pd.getString("orderId");
        String type = pd.getString("type");
        // 条件过滤
        if (orderId != null && !orderId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("orderId").toString().contains(orderId))
                    .collect(Collectors.toList());
        }
        if (type != null && !type.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("type").toString().contains(type))
                    .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
     * @throws Exception
     */
    @GetMapping("/estateManagementEnergyDataList")
    public Map<String, Object> getEnergyData() throws Exception {
        List<Map<String, Object>> data = generateEnergyData ();
        PageData pd = this.getPageData();
        String meterId = pd.getString("meterId");
        String buildingNo = pd.getString("buildingNo");
        // 条件过滤
        if (meterId != null && !meterId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("meterId").toString().contains(meterId))
                    .collect(Collectors.toList());
        }
        if (buildingNo != null && !buildingNo.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("buildingNo").toString().contains(buildingNo))
                    .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
     * @throws Exception
     */
    @GetMapping("/estateManagementRentalDataList")
    public Map<String, Object> getRentalData() throws Exception {
        List<Map<String, Object>> data = generateRentalData();
        PageData pd = this.getPageData();
        String propertyId = pd.getString("propertyId");
        String layout = pd.getString("layout");
        // 条件过滤
        if (propertyId != null && !propertyId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("propertyId").toString().contains(propertyId))
                    .collect(Collectors.toList());
        }
        if (layout != null && !layout.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("layout").toString().contains(layout))
                    .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
     * @throws Exception
     */
    @GetMapping("/estateManagementWorkOrderAnalysisDataList")
    public Map<String, Object> getWorkOrderAnalysisData() throws Exception {
        List<Map<String, Object>> data = generateWorkOrderAnalysisData();
        PageData pd = this.getPageData();
        String timeRange = pd.getString("timeRange");
        String topIssue = pd.getString("topIssue");

        // 解析时间范围参数（独立字段示例）
        String startMonth = pd.getString("timeRange[0]"); // 开始月份
        String endMonth = pd.getString("timeRange[1]"); // 结束月份
        // 时间范围过滤
        if (startMonth != null && endMonth != null && !startMonth.isEmpty() && !endMonth.isEmpty()) {
            data = data.stream()
                    .filter(item -> isWithinTimeRange((String) item.get("month"), startMonth, endMonth))
                    .collect(Collectors.toList());
        }
        if (topIssue != null && !topIssue.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("topIssue").toString().contains(topIssue))
                    .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;
    }
    /**
     * 时间范围过滤方法（判断月份是否在[start, end]区间内）
     */
    private boolean isWithinTimeRange(String targetMonth, String startMonth, String endMonth) {
        // 转换为年月数值（如：2024-01 -> 202401）
        int target = Integer.parseInt(targetMonth.replace("-", ""));
        int start = Integer.parseInt(startMonth.replace("-", ""));
        int end = Integer.parseInt(endMonth.replace("-", ""));
        return target >= start && target <= end;
    }



    /**
     * 查询业主档案列表
     * @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);
        }
    }
}
