EnergySearchService.java 60.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
package com.iot.scheduler.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class EnergySearchService {

    @Value("${energy.db.corpCode}")
    private String energyCorpCode;
    @Value("${energy.db.tableName}")
    private String energyTableName;
    @Value("${energy.db.eqKwhTableName}")
    private String eqKwhTableName;
    @Value("${energy.db.eRunDtlTableName}")
    private String eRunDtlTableName;

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 分页查询能耗设备信息
     * 查询表 t_auto_ymk_iot_energy,按设备名称排序
     *
     * @param deviceName 设备名称(模糊匹配)
     * @param runStatus  状态(0:离线,1:停机,2:待机,3:运行)
     * @param pageNo     页码,默认1
     * @param pageSize   每页条数,默认10
     */
    public Map<String, Object> queryEnergyList(String deviceName, String runStatus,
                                               Integer pageNo, Integer pageSize) {
        StringBuilder countSql = new StringBuilder("SELECT COUNT(*) FROM " + energyTableName + " WHERE corp_code = ?");
        StringBuilder querySql = new StringBuilder(
                "SELECT id, deviceName, projectType, projectState, dtuSn, dtuId, deviceId, " +
                        "evalue, duration, runStatus, created_at, updated_at " +
                        "FROM " + energyTableName + " WHERE corp_code = ?");
        List<Object> params = new ArrayList<>();
        params.add(energyCorpCode);

        // 设备名称模糊查询
        if (StringUtils.hasText(deviceName)) {
            countSql.append(" AND deviceName LIKE ?");
            querySql.append(" AND deviceName LIKE ?");
            params.add("%" + deviceName + "%");
        }

        // 设备状态精确匹配
        if (StringUtils.hasText(runStatus)) {
            countSql.append(" AND runStatus = ?");
            querySql.append(" AND runStatus = ?");
            params.add(runStatus);
        }

        Long total = jdbcTemplate.queryForObject(countSql.toString(), Long.class, params.toArray());
        int offset = (pageNo - 1) * pageSize;

        querySql.append(" ORDER BY deviceName ASC LIMIT ?, ?");
        params.add(offset);
        params.add(pageSize);

        List<Map<String, Object>> list = jdbcTemplate.queryForList(querySql.toString(), params.toArray());
        list.forEach(row -> {
            if (row.get("duration") != null) {
                long seconds = Long.parseLong(String.valueOf(row.get("duration")));
                long h = seconds / 3600;
                long m = (seconds % 3600) / 60;
                long s = seconds % 60;
                StringBuilder sb = new StringBuilder();
                if (h > 0) sb.append(h).append("时");
                if (h > 0 || m > 0) sb.append(m).append("分");
                sb.append(s).append("秒");
                row.put("duration", sb.toString());
            }
        });

        return Map.of(
                "code", 200,
                "msg", "请求成功",
                "total", total != null ? total : 0,
                "pageNo", pageNo,
                "pageSize", pageSize,
                "list", list
        );
    }

    /**
     * 统计能耗设备各runStatus数量及总数量
     * runStatus: 0-离线, 1-停机, 2-待机, 3-运行
     */
    public Map<String, Object> queryEnergyStats() {
        String sql = "SELECT runStatus, COUNT(*) AS cnt FROM " + energyTableName
                + " WHERE corp_code = ? GROUP BY runStatus";
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, energyCorpCode);

        int total = 0;
        Map<String, Integer> statusMap = new LinkedHashMap<>();
        statusMap.put("0", 0);
        statusMap.put("1", 0);
        statusMap.put("2", 0);
        statusMap.put("3", 0);

        for (Map<String, Object> row : rows) {
            String key = String.valueOf(row.get("runStatus"));
            int cnt = ((Number) row.get("cnt")).intValue();
            total += cnt;
            statusMap.merge(key, cnt, Integer::sum);
        }

        return Map.of(
                "code", 200,
                "msg", "请求成功",
                "total", total,
                "0", statusMap.get("0"),
                "1", statusMap.get("1"),
                "2", statusMap.get("2"),
                "3", statusMap.get("3")
        );
    }

    /**
     * 根据dtuSn查询指定日期的设备时用电量和OEE时序
     * 1. 时用电量:从t_auto_ymk_iot_eq_kwh表获取,并计算当日总用电量
     * 2. OEE时序:从t_auto_ymk_iot_e_run_dtl表获取,统计总时长、各状态运行时长和占比
     *
     * @param dtuSn 设备序列号
     * @param date  查询日期 yyyy-MM-dd
     */
    public Map<String, Object> queryEnergyDetailByDate(String dtuSn, String date) {
        // 1. 查询时用电量数据 - 原始数据直接返回
        Object kwhRawData = Collections.emptyList();
        BigDecimal totalKwh = BigDecimal.ZERO;
        try {
            String kwhSql = "SELECT description FROM " + eqKwhTableName
                    + " WHERE corp_code = ? AND dtuSn = ? AND use_date = ?";
            Map<String, Object> kwhRow = jdbcTemplate.queryForMap(kwhSql, energyCorpCode, dtuSn, date + " 00:00:00");
            if (kwhRow != null && kwhRow.get("description") != null) {
                String description = String.valueOf(kwhRow.get("description"));
                kwhRawData = JSON.parseArray(description);
                // 计算总用电量
                JSONArray dataArray = JSON.parseArray(description);
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    Double value = item.getDouble("value");
                    if (value != null) {
                        totalKwh = totalKwh.add(BigDecimal.valueOf(value));
                    }
                }
            }
        } catch (Exception e) {
            log.warn("【能耗明细】查询时用电量数据为空或异常 - dtuSn:{}, date:{}", dtuSn, date);
        }

        // 2. 查询OEE时序数据 - 原始数据直接返回
        Object oeeRawData = Collections.emptyList();
        long totalDuration = 0;
        // runStatus状态: 0-离线, 1-停机, 2-待机, 3-运行
        Map<Integer, Long> statusDurationMap = new LinkedHashMap<>();
        statusDurationMap.put(0, 0L); // 离线
        statusDurationMap.put(1, 0L); // 停机
        statusDurationMap.put(2, 0L); // 待机
        statusDurationMap.put(3, 0L); // 运行

        try {
            String oeeSql = "SELECT runStatus1, runStatus2 FROM " + eRunDtlTableName
                    + " WHERE corp_code = ? AND dtuSn = ? AND use_date = ?";
            Map<String, Object> oeeRow = jdbcTemplate.queryForMap(oeeSql, energyCorpCode, dtuSn, date + " 00:00:00");
            if (oeeRow != null) {
                String rs1 = oeeRow.get("runStatus1") != null ? String.valueOf(oeeRow.get("runStatus1")) : "";
                String rs2 = oeeRow.get("runStatus2") != null ? String.valueOf(oeeRow.get("runStatus2")) : "";
                String jsonStr = rs1 + rs2;
                oeeRawData = JSON.parseArray(jsonStr);

                // 统计各状态时长
                JSONArray dataArray = JSON.parseArray(jsonStr);
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    Long duration = item.getLong("duration");
                    Integer runStatus = item.getInteger("runStatus");

                    if (duration != null && duration > 0) {
                        totalDuration += duration;
                        int statusKey = runStatus != null ? runStatus : 0;
                        statusDurationMap.merge(statusKey, duration, Long::sum);
                    }
                }
            }
        } catch (Exception e) {
            log.warn("【能耗明细】查询OEE时序数据为空或异常 - dtuSn:{}, date:{}", dtuSn, date);
        }

        // 3. 构建OEE统计结果(含格式化时长和占比)
        List<Map<String, Object>> statusStats = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : statusDurationMap.entrySet()) {
            long dur = entry.getValue();
            double percent = totalDuration > 0 ? BigDecimal.valueOf(dur * 100.0 / totalDuration)
                    .setScale(2, RoundingMode.HALF_UP).doubleValue() : 0.0;

            Map<String, Object> stat = new LinkedHashMap<>();
            stat.put("status", entry.getKey());
            stat.put("durationSeconds", dur);
            stat.put("durationFormatted", formatDuration(dur));
            stat.put("percent", percent);
            statusStats.add(stat);
        }

        return Map.of(
                "code", 200,
                "msg", "请求成功",
                "dtuSn", dtuSn,
                "date", date,
                "kwhData", Map.of(
                        "list", kwhRawData,
                        "totalKwh", totalKwh.setScale(2, RoundingMode.HALF_UP)
                ),
                "oeeData", Map.of(
                        "list", oeeRawData,
                        "totalDurationFormatted", formatDuration(totalDuration),
                        "totalDurationSeconds", totalDuration,
                        "statusStats", statusStats
                )
        );
    }

    /**
     * 根据dtuSn查询指定设备的运行时长明细
     * 核心数据为设备时用电量(eq_kwh),其中包含每个状态的运行时长,需要统计
     * type=1(时): 传startDate,获取指定日期的时用电量明细+各状态时长统计
     * type=2(天): 传startDate和endDate,按日统计
     * type=3(月): 查本年年初到现在,按月统计
     *
     * @param dtuSn     设备序列号
     * @param type      类型:1-时,2-天,3-月
     * @param startDate 开始日期 yyyy-MM-dd (type=1,2必填)
     * @param endDate   结束日期 yyyy-MM-dd (type=2必填)
     */
    public Map<String, Object> queryEnergyRuntimeDetail(String dtuSn, String type,
                                                        String startDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();

        // 根据type构建日期列表
        if ("1".equals(type)) {
            dateList.add(startDate);
        } else if ("2".equals(type)) {
            try {
                Date start = sdf.parse(startDate);
                Date end = sdf.parse(endDate);
                Calendar cur = Calendar.getInstance();
                cur.setTime(start);
                while (!cur.getTime().after(end)) {
                    dateList.add(sdf.format(cur.getTime()));
                    cur.add(Calendar.DAY_OF_MONTH, 1);
                }
            } catch (Exception e) {
                return Map.of("code", 400, "msg", "日期格式错误");
            }
        } else if ("3".equals(type)) {
            Calendar now = Calendar.getInstance();
            int year = now.get(Calendar.YEAR);
            Calendar startCal = Calendar.getInstance();
            startCal.set(year, Calendar.JANUARY, 1);
            while (!startCal.getTime().after(now.getTime())) {
                dateList.add(sdf.format(startCal.getTime()));
                startCal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }

        // 统计汇总数据
        long totalDurationAll = 0;
        BigDecimal totalKwhAll = BigDecimal.ZERO;
        Map<Integer, Long> statusDurationAllMap = initStatusMap();

        // type=1: 直接返回每日明细; type=2/3: 按日期聚合后返回
        List<Map<String, Object>> detailList = new ArrayList<>();
        // type=3 按月聚合用
        Map<String, Map<String, Object>> monthAggMap = "3".equals(type) ? new LinkedHashMap<>() : null;

        for (String dateStr : dateList) {
            // 从eq_kwh表查询时用电量数据
            Object kwhRawData = Collections.emptyList();
            BigDecimal dayKwh = BigDecimal.ZERO;
            long dayTotalDuration = 0;
            Map<Integer, Long> dayStatusDuration = initStatusMap();

            try {
                String kwhSql = "SELECT description FROM " + eqKwhTableName
                        + " WHERE corp_code = ? AND dtuSn = ? AND use_date = ?";
                Map<String, Object> kwhRow = jdbcTemplate.queryForMap(kwhSql, energyCorpCode, dtuSn, dateStr + " 00:00:00");
                if (kwhRow != null && kwhRow.get("description") != null) {
                    String desc = String.valueOf(kwhRow.get("description"));
                    JSONArray dataArray = JSON.parseArray(desc);

                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject item = dataArray.getJSONObject(i);
                        Double value = item.getDouble("value");
                        if (value != null) dayKwh = dayKwh.add(BigDecimal.valueOf(value));

                        // 从字段 0/1/2/3 统计各状态运行时长 + 格式化新字段
                        for (int statusKey = 0; statusKey <= 3; statusKey++) {
                            Long dur = item.getLong(String.valueOf(statusKey));
                            item.put(statusKey + "Formatted", formatDuration(dur != null ? dur : 0L));
                            if (dur != null && dur > 0) {
                                dayTotalDuration += dur;
                                totalDurationAll += dur;
                                dayStatusDuration.merge(statusKey, dur, Long::sum);
                                statusDurationAllMap.merge(statusKey, dur, Long::sum);
                            }
                        }
                    }
                    kwhRawData = dataArray;
                }
            } catch (Exception ignored) {
            }
            totalKwhAll = totalKwhAll.add(dayKwh);

            String periodKey = "3".equals(type) ? dateStr.substring(0, 7) : dateStr;

            if ("1".equals(type)) {
                // type=1(时): 返回原始kwhList + 当日统计
                Map<String, Object> entry = new LinkedHashMap<>();
                entry.put("date", periodKey);
                entry.put("kwhList", kwhRawData);
                entry.put("totalKwh", dayKwh.setScale(2, RoundingMode.HALF_UP));
                entry.put("totalDurationFormatted", formatDuration(dayTotalDuration));
                entry.put("totalDurationSeconds", dayTotalDuration);
                entry.put("statusStats", buildStatusStats(dayStatusDuration, dayTotalDuration));
                detailList.add(entry);
            } else if ("2".equals(type)) {
                // type=2(天): 返回每日汇总统计,不含kwhList
                Map<String, Object> entry = new LinkedHashMap<>();
                entry.put("date", periodKey);
                entry.put("totalKwh", dayKwh.setScale(2, RoundingMode.HALF_UP));
                entry.put("totalDurationFormatted", formatDuration(dayTotalDuration));
                entry.put("totalDurationSeconds", dayTotalDuration);
                entry.put("statusStats", buildStatusStats(dayStatusDuration, dayTotalDuration));
                detailList.add(entry);
            } else if ("3".equals(type)) {
                // type=3(月): 按月聚合
                monthAggMap.computeIfAbsent(periodKey, k -> {
                    Map<String, Object> m = new LinkedHashMap<>();
                    m.put("date", k);
                    m.put("totalKwh", BigDecimal.ZERO);
                    m.put("totalDurationSeconds", 0L);
                    m.put("statusDurationMap", initStatusMap());
                    return m;
                });
                Map<String, Object> monthEntry = monthAggMap.get(periodKey);
                monthEntry.put("totalKwh", ((BigDecimal) monthEntry.get("totalKwh")).add(dayKwh));
                monthEntry.put("totalDurationSeconds", (Long) monthEntry.get("totalDurationSeconds") + dayTotalDuration);
                @SuppressWarnings("unchecked")
                Map<Integer, Long> mStatusMap = (Map<Integer, Long>) monthEntry.get("statusDurationMap");
                for (int sk = 0; sk <= 3; sk++) {
                    if (dayStatusDuration.get(sk) > 0) {
                        mStatusMap.merge(sk, dayStatusDuration.get(sk), Long::sum);
                    }
                }
            }
        }

        // type=3 构建月度聚合结果
        if ("3".equals(type) && monthAggMap != null) {
            for (Map.Entry<String, Map<String, Object>> me : monthAggMap.entrySet()) {
                Map<String, Object> m = me.getValue();
                long mDur = (Long) m.get("totalDurationSeconds");
                @SuppressWarnings("unchecked")
                Map<Integer, Long> mStatusMap = (Map<Integer, Long>) m.get("statusDurationMap");

                Map<String, Object> entry = new LinkedHashMap<>();
                entry.put("date", m.get("date"));
                entry.put("totalKwh", ((BigDecimal) m.get("totalKwh")).setScale(2, RoundingMode.HALF_UP));
                entry.put("totalDurationFormatted", formatDuration(mDur));
                entry.put("totalDurationSeconds", mDur);
                entry.put("statusStats", buildStatusStats(mStatusMap, mDur));
                detailList.add(entry);
            }
        }

        List<Map<String, Object>> allStatusStats = buildStatusStats(statusDurationAllMap, totalDurationAll);

        return Map.of(
                "code", 200,
                "msg", "请求成功",
                "dtuSn", dtuSn,
                "type", type,
                "detailList", detailList,
                "summary", Map.of(
                        "totalDurationFormatted", formatDuration(totalDurationAll),
                        "totalDurationSeconds", totalDurationAll,
                        "totalKwh", totalKwhAll.setScale(2, RoundingMode.HALF_UP),
                        "statusStats", allStatusStats
                )
        );
    }

    /**
     * 查询能耗时序状态 - 分页查询
     * 从e_run_dtl(OEE时序)表获取指定日期的设备时序数据,每页12条
     * 同时计算每个设备的稼动率和总用电量(从eq_kwh表)
     *
     * @param date     查询日期 yyyy-MM-dd
     * @param pageNo   页码,默认1
     * @param pageSize 每页条数,默认12
     */
    public Map<String, Object> queryEnergyTimelineStatus(String date, Integer pageNo, Integer pageSize) {
        // 先查OEE时序表获取有数据的设备列表
        String countSql = "SELECT COUNT(DISTINCT r.dtuSn) FROM " + eRunDtlTableName + " r "
                + " INNER JOIN " + energyTableName + " e ON e.dtuSn = r.dtuSn AND e.corp_code = r.corp_code "
                + " WHERE r.corp_code = ? AND r.use_date = ?";
        Long total = jdbcTemplate.queryForObject(countSql, Long.class, energyCorpCode, date + " 00:00:00");

        int offset = (pageNo - 1) * pageSize;
        String querySql = "SELECT r.dtuSn, e.deviceName, r.runStatus1, r.runStatus2 FROM " + eRunDtlTableName + " r "
                + " INNER JOIN " + energyTableName + " e ON e.dtuSn = r.dtuSn AND e.corp_code = r.corp_code "
                + " WHERE r.corp_code = ? AND r.use_date = ? "
                + " ORDER BY e.deviceName ASC LIMIT ?, ?";
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(querySql, energyCorpCode, date + " 00:00:00", offset, pageSize);

        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> row : rows) {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("dtuSn", row.get("dtuSn"));
            item.put("deviceName", row.get("deviceName"));

            // OEE时序数据(原始返回)
            Object oeeRawData = Collections.emptyList();
            long totalDuration = 0;
            long runDuration = 0;

            String rs1 = row.get("runStatus1") != null ? String.valueOf(row.get("runStatus1")) : "";
            String rs2 = row.get("runStatus2") != null ? String.valueOf(row.get("runStatus2")) : "";
            if (StringUtils.hasText(rs1) || StringUtils.hasText(rs2)) {
                String jsonStr = rs1 + rs2;
                try {
                    JSONArray dataArray = JSON.parseArray(jsonStr);
                    oeeRawData = dataArray;
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject jo = dataArray.getJSONObject(i);
                        Long duration = jo.getLong("duration");
                        Integer runStatus = jo.getInteger("runStatus");
                        if (duration != null && duration > 0 && runStatus != null) {
                            totalDuration += duration;
                            if (runStatus == 3) runDuration += duration; // 运行状态
                        }
                    }
                } catch (Exception ignored) {
                }
            }

            item.put("timelineList", oeeRawData);
            item.put("totalDurationFormatted", formatDuration(totalDuration));
            item.put("totalDurationSeconds", totalDuration);

            // 从eq_kwh表获取用电量
            BigDecimal totalKwh = BigDecimal.ZERO;
            try {
                String kwhSql = "SELECT description FROM " + eqKwhTableName
                        + " WHERE corp_code = ? AND dtuSn = ? AND use_date = ?";
                Map<String, Object> kwhRow = jdbcTemplate.queryForMap(kwhSql, energyCorpCode, row.get("dtuSn"), date + " 00:00:00");
                if (kwhRow != null && kwhRow.get("description") != null) {
                    JSONArray dataArray = JSON.parseArray(String.valueOf(kwhRow.get("description")));
                    for (int i = 0; i < dataArray.size(); i++) {
                        Double value = dataArray.getJSONObject(i).getDouble("value");
                        if (value != null) totalKwh = totalKwh.add(BigDecimal.valueOf(value));
                    }
                }
            } catch (Exception ignored) {
            }

            item.put("totalKwh", totalKwh.setScale(2, RoundingMode.HALF_UP));
            // 稼动率 = 运行时长 / 总时长
            double utilizationRate = totalDuration > 0
                    ? BigDecimal.valueOf(runDuration * 100.0 / totalDuration).setScale(2, RoundingMode.HALF_UP).doubleValue()
                    : 0.0;
            item.put("utilizationRate", utilizationRate);

            list.add(item);
        }

        return Map.of(
                "code", 200,
                "msg", "请求成功",
                "total", total != null ? total : 0,
                "pageNo", pageNo,
                "pageSize", pageSize,
                "list", list
        );
    }

    private static Map<Integer, Long> initStatusMap() {
        Map<Integer, Long> map = new LinkedHashMap<>();
        map.put(0, 0L);
        map.put(1, 0L);
        map.put(2, 0L);
        map.put(3, 0L);
        return map;
    }

    private static List<Map<String, Object>> buildStatusStats(Map<Integer, Long> statusMap, long totalDur) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : statusMap.entrySet()) {
            long dur = entry.getValue();
            double percent = totalDur > 0 ? BigDecimal.valueOf(dur * 100.0 / totalDur)
                    .setScale(2, RoundingMode.HALF_UP).doubleValue() : 0.0;
            Map<String, Object> stat = new LinkedHashMap<>();
            stat.put("status", entry.getKey());
            stat.put("durationSeconds", dur);
            stat.put("durationFormatted", formatDuration(dur));
            stat.put("percent", percent);
            list.add(stat);
        }
        return list;
    }

    private static Object itemToMap(JSONArray dataArray) {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < dataArray.size(); i++) {
            list.add(dataArray.getJSONObject(i));
        }
        return list;
    }

    /**
     * 格式化时长为 xx时xx分xx秒 格式
     * 时不为0则展示xx时xx分xx秒
     * 时和分都为0则只展示xx秒
     */
    private static String formatDuration(long totalSeconds) {
        long h = totalSeconds / 3600;
        long m = (totalSeconds % 3600) / 60;
        long s = totalSeconds % 60;
        StringBuilder sb = new StringBuilder();
        if (h > 0) sb.append(h).append("时");
        if (h > 0 || m > 0) sb.append(m).append("分");
        sb.append(s).append("秒");
        return sb.toString();
    }

    /**
     * 格式化时长为 xxx.xx 时
     */
    private static String formatDurationToHours(long totalSeconds) {
        double hours = totalSeconds / 3600.0;
        return String.format("%.2f时", hours);
    }

    // ==================== eq_kwh 综合统计查询 ====================

    /**
     * 查询 eq_kwh 表的综合统计数据
     * 返回:
     * 1. 所有设备的总的稼动率 + 每个状态的时间(xxx.xx时)
     * 2. 当前设备的运行状态
     * 3. 异常机台排名(待机+停机时间最长往下排, xx时xx分xx秒)
     * 4. 每个设备统计时间内的总的0/1/2/3的时间(xx时xx分xx秒)
     *
     * @param startDate 开始日期 yyyy-MM-dd
     * @param endDate   结束日期 yyyy-MM-dd
     */
    public Map<String, Object> queryEqKwhStatistics(String startDate, String endDate) {
        log.info("========== [eq_kwh综合统计] startDate={}, endDate={} ==========", startDate, endDate);

        if (!StringUtils.hasText(startDate) || !StringUtils.hasText(endDate)) {
            return Map.of(
                    "code", 400, "msg", "参数错误: startDate和endDate必填",
                    "data", Map.of()
            );
        }

        // 1. 构建日期列表
        List<String> dateList = buildDateList(startDate, endDate);
        if (dateList.isEmpty()) {
            return buildEmptyEqKwhStats();
        }
        log.info("日期范围共 {} 天: {} ~ {}", dateList.size(), dateList.get(0), dateList.get(dateList.size() - 1));

        // 2. 获取所有设备列表及名称
        Map<String, String> deviceNameMap = queryAllEnergyDeviceNames();

        // 3. 从 eq_kwh 表批量查询所有设备在指定日期范围内的数据
        List<Map<String, Object>> allRawData = queryEqKwhBatch(dateList);
        log.info("eq_kwh 批量查询返回 {} 条原始记录", allRawData.size());

        // 4. 按 dtuSn 分组聚合数据,计算每个设备的各状态时长
        Map<String, DeviceStatResult> deviceStatMap = aggregateByDevice(allRawData, deviceNameMap);

        // 确保所有设备都在结果中(无数据的设为0)
        for (String sn : deviceNameMap.keySet()) {
            if (!deviceStatMap.containsKey(sn)) {
                deviceStatMap.put(sn, new DeviceStatResult(sn, deviceNameMap.getOrDefault(sn, "")));
            }
        }

        // 5. 计算全局汇总
        return buildEqKwhStatisticsResult(deviceStatMap, deviceNameMap);
    }

    /**
     * 设备统计内部结构
     */
    static class DeviceStatResult {
        String dtuSn;
        String deviceName;
        long status0; // 离线时长(秒)
        long status1; // 停机时长(秒)
        long status2; // 待机时长(秒)
        long status3; // 运行时长(秒)
        double totalKwh; // 总用电量

        DeviceStatResult(String dtuSn, String deviceName) {
            this.dtuSn = dtuSn;
            this.deviceName = deviceName;
        }

        /**
         * 总时长(秒)
         */
        long totalDuration() {
            return status0 + status1 + status2 + status3;
        }

        /**
         * 异常时长 = 停机 + 待机
         */
        long abnormalDuration() {
            return status1 + status2;
        }

        /**
         * 稼动分母 = 停机 + 待机 + 运行 (排除离线)
         */
        long activeDuration() {
            return status1 + status2 + status3;
        }
    }

    /**
     * 构建空结果
     */
    private Map<String, Object> buildEmptyEqKwhStats() {
        return Map.of(
                "code", 200, "msg", "请求成功", "data",
                Map.of(
                        "summary", Map.of(
                                "availabilityRate", "0.00%",
                                "totalStatusDuration", Map.of(
                                        "status0", Map.of("durationFormatted", "0时0分0秒", "durationSeconds", 0L, "durationHours", "0.00时"),
                                        "status1", Map.of("durationFormatted", "0时0分0秒", "durationSeconds", 0L, "durationHours", "0.00时"),
                                        "status2", Map.of("durationFormatted", "0时0分0秒", "durationSeconds", 0L, "durationHours", "0.00时"),
                                        "status3", Map.of("durationFormatted", "0时0分0秒", "durationSeconds", 0L, "durationHours", "0.00时")
                                )
                        ),
                        "currentStatus", Map.of("0", 0, "1", 0, "2", 0, "3", 0),
                        "abnormalRanking", List.of(),
                        "deviceList", List.of()
                )
        );
    }

    /**
     * 获取能耗设备表所有dtuSn及名称
     */
    private Map<String, String> queryAllEnergyDeviceNames() {
        String sql = "SELECT dtuSn, deviceName FROM " + energyTableName + " WHERE corp_code = ? ORDER BY dtuSn";
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, energyCorpCode);
        Map<String, String> result = new LinkedHashMap<>(rows.size());
        for (Map<String, Object> row : rows) {
            result.put((String) row.get("dtuSn"), (String) row.get("deviceName"));
        }
        return result;
    }

    /**
     * 构建连续日期列表
     */
    private List<String> buildDateList(String startDate, String endDate) {
        List<String> result = new ArrayList<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cur = Calendar.getInstance();
            cur.setTime(sdf.parse(startDate));
            Calendar endCal = Calendar.getInstance();
            endCal.setTime(sdf.parse(endDate));
            while (!cur.after(endCal)) {
                result.add(sdf.format(cur.getTime()));
                cur.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (Exception e) {
            log.error("日期解析失败: {} ~ {}", startDate, endDate, e);
        }
        return result;
    }

    /**
     * 从 eq_kwh 表批量查询指定日期范围的所有记录
     */
    private List<Map<String, Object>> queryEqKwhBatch(List<String> dateList) {
        if (dateList.isEmpty()) return Collections.emptyList();

        StringBuilder sql = new StringBuilder(
                "SELECT dtuSn, use_date, description FROM " + eqKwhTableName +
                        " WHERE corp_code = ? AND use_date IN (");
        List<Object> params = new ArrayList<>();
        params.add(energyCorpCode);

        for (String d : dateList) {
            sql.append("?,");
            params.add(d + "T00:00:00");
        }
        sql.deleteCharAt(sql.length() - 1).append(")");
        sql.append(" ORDER BY dtuSn, use_date");

        return jdbcTemplate.queryForList(sql.toString(), params.toArray());
    }

    /**
     * 按 dtuSn 分组聚合各状态时长
     */
    private Map<String, DeviceStatResult> aggregateByDevice(List<Map<String, Object>> rawData,
                                                            Map<String, String> deviceNameMap) {
        Map<String, DeviceStatResult> resultMap = new LinkedHashMap<>();

        for (Map<String, Object> row : rawData) {
            String sn = (String) row.get("dtuSn");
            String desc = row.get("description") != null ? String.valueOf(row.get("description")) : "";

            DeviceStatResult dsr = resultMap.computeIfAbsent(sn,
                    k -> new DeviceStatResult(k, deviceNameMap.getOrDefault(k, "")));

            if (!StringUtils.hasText(desc)) continue;

            try {
                JSONArray dataArray = JSON.parseArray(desc);
                if (dataArray == null) continue;

                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    if (item == null) continue;

                    // 用电量
                    Double value = item.getDouble("value");
                    if (value != null) dsr.totalKwh += value;

                    // 各状态时长: 0-离线, 1-停机, 2-待机, 3-运行
                    for (int sk = 0; sk <= 3; sk++) {
                        Long dur = item.getLong(String.valueOf(sk));
                        if (dur != null && dur > 0) {
                            switch (sk) {
                                case 0 -> dsr.status0 += dur;
                                case 1 -> dsr.status1 += dur;
                                case 2 -> dsr.status2 += dur;
                                case 3 -> dsr.status3 += dur;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("解析eq_kwh description异常 - dtuSn:{}", sn, e);
            }
        }

        return resultMap;
    }

    /**
     * 构建最终统计结果
     */
    private Map<String, Object> buildEqKwhStatisticsResult(Map<String, DeviceStatResult> deviceStatMap,
                                                           Map<String, String> deviceNameMap) {
        // ---- 全局汇总 ----
        long totalS0 = 0, totalS1 = 0, totalS2 = 0, totalS3 = 0;
        double totalKwhSum = 0;

        // ---- 设备详情列表 ----
        List<Map<String, Object>> deviceList = new ArrayList<>(deviceStatMap.size());

        for (Map.Entry<String, DeviceStatResult> entry : deviceStatMap.entrySet()) {
            DeviceStatResult dsr = entry.getValue();

            totalS0 += dsr.status0;
            totalS1 += dsr.status1;
            totalS2 += dsr.status2;
            totalS3 += dsr.status3;
            totalKwhSum += dsr.totalKwh;

            // 单设备稼动率 = 运行 / (停机+待机+运行)
            long active = dsr.activeDuration();
            double devRate = active > 0 ? Math.round(dsr.status3 * 10000.0 / active) / 100.0 : 0.0;

            Map<String, Object> devItem = new LinkedHashMap<>();
            devItem.put("dtuSn", dsr.dtuSn);
            devItem.put("deviceName", dsr.deviceName);
            // 各状态时长 - 格式化为 xx时xx分xx秒
            devItem.put("status0", Map.of(
                    "durationFormatted", formatDuration(dsr.status0),
                    "durationSeconds", dsr.status0,
                    "durationHours", formatDurationToHours(dsr.status0)
            ));
            devItem.put("status1", Map.of(
                    "durationFormatted", formatDuration(dsr.status1),
                    "durationSeconds", dsr.status1,
                    "durationHours", formatDurationToHours(dsr.status1)
            ));
            devItem.put("status2", Map.of(
                    "durationFormatted", formatDuration(dsr.status2),
                    "durationSeconds", dsr.status2,
                    "durationHours", formatDurationToHours(dsr.status2)
            ));
            devItem.put("status3", Map.of(
                    "durationFormatted", formatDuration(dsr.status3),
                    "durationSeconds", dsr.status3,
                    "durationHours", formatDurationToHours(dsr.status3)
            ));
            devItem.put("totalDurationFormatted", formatDuration(dsr.totalDuration()));
            devItem.put("totalDurationSeconds", dsr.totalDuration());
            devItem.put("totalDurationHours", formatDurationToHours(dsr.totalDuration()));
            devItem.put("totalKwh", Math.round(dsr.totalKwh * 100.0) / 100.0);
            devItem.put("availabilityRate", String.format("%.2f%%", devRate));
            devItem.put("availabilityRateValue", devRate);
            // 异常时长用于排序(内部字段,后面移除)
            devItem.put("_abnormalDur", dsr.abnormalDuration());

            deviceList.add(devItem);
        }

        // ---- ① 总稼动率 ----
        long totalActive = totalS1 + totalS2 + totalS3;
        double overallAvailabilityRate = totalActive > 0
                ? Math.round(totalS3 * 10000.0 / totalActive) / 100.0 : 0.0;

        // ---- ② 当前设备运行状态(从energy表查) ----
        Map<String, Integer> currentStatus = queryCurrentRunStatus();

        // ---- ③ 异常机台排名(按 停机+待机 降序) ----
        deviceList.sort((a, b) -> Long.compare(
                ((Number) b.get("_abnormalDur")).longValue(),
                ((Number) a.get("_abnormalDur")).longValue()
        ));
        // 移除辅助字段
        for (Map<String, Object> d : deviceList) {
            d.remove("_abnormalDur");
        }

        return Map.of(
                "code", 200, "msg", "请求成功", "data",
                Map.of(
                        "summary", Map.of(
                                "availabilityRate", String.format("%.2f%%", overallAvailabilityRate),
                                "availabilityRateValue", overallAvailabilityRate,
                                "totalDevices", deviceNameMap.size(),
                                "totalKwh", Math.round(totalKwhSum * 100.0) / 100.0,
                                "totalStatusDuration", Map.of(
                                        "status0", Map.of(
                                                "durationFormatted", formatDuration(totalS0),
                                                "durationSeconds", totalS0,
                                                "durationHours", formatDurationToHours(totalS0)
                                        ),
                                        "status1", Map.of(
                                                "durationFormatted", formatDuration(totalS1),
                                                "durationSeconds", totalS1,
                                                "durationHours", formatDurationToHours(totalS1)
                                        ),
                                        "status2", Map.of(
                                                "durationFormatted", formatDuration(totalS2),
                                                "durationSeconds", totalS2,
                                                "durationHours", formatDurationToHours(totalS2)
                                        ),
                                        "status3", Map.of(
                                                "durationFormatted", formatDuration(totalS3),
                                                "durationSeconds", totalS3,
                                                "durationHours", formatDurationToHours(totalS3)
                                        )
                                )
                        ),
                        "currentStatus", currentStatus,
                        "abnormalRanking", deviceList,
                        "deviceList", deviceList
                )
        );
    }

    /**
     * 查询当前设备运行状态分布(从energy表) runStatus: 0-离线, 1-停机, 2-待机, 3-运行
     */
    private Map<String, Integer> queryCurrentRunStatus() {
        String sql = "SELECT runStatus, COUNT(*) as cnt FROM " + energyTableName +
                " WHERE corp_code = ? GROUP BY runStatus";
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, energyCorpCode);

        int s0 = 0, s1 = 0, s2 = 0, s3 = 0;
        for (Map<String, Object> row : rows) {
            String key = String.valueOf(row.get("runStatus"));
            int cnt = ((Number) row.get("cnt")).intValue();
            switch (key) {
                case "0" -> s0 = cnt;
                case "1" -> s1 = cnt;
                case "2" -> s2 = cnt;
                case "3" -> s3 = cnt;
            }
        }
        return Map.of("0", s0, "1", s1, "2", s2, "3", s3);
    }

    // ==================== eq_kwh 多设备时/日/月查询 ====================

    /**
     * 查询 eq_kwh 表的多设备能耗数据(按 时/日/月 聚合)
     * <p>
     * type=1 (时): 只需传 startDate,返回该日所有设备的原始用电量明细(kwhList)
     * type=2 (日):
     * - 若传了 startDate+endDate: 按此范围每日统计每台设备能耗
     * - 若只传 startDate: 自动补全为当月的第1天~最后一天
     * type=3 (月): 自动取本年1月~当前月,按月统计每台设备能耗
     *
     * @param type      查询类型: 1-时, 2-日, 3-月
     * @param startDate 开始日期 yyyy-MM-dd (type=1,2必填; type=3可选)
     * @param endDate   结束日期 yyyy-MM-dd (type=2可选)
     */
    public Map<String, Object> queryEqKwhByType(String type, String startDate, String endDate) {
        log.info("========== [eq_kwh多设备查询] type={}, startDate={}, endDate={} ==========", type, startDate, endDate);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();

        // 根据type构建日期列表 + 实际起止日期
        String actualStart;
        String actualEnd;

        if ("1".equals(type)) {
            // type=1: 单日查询,直接返回原始kwh数据
            if (!StringUtils.hasText(startDate)) {
                return Map.of("code", 400, "msg", "参数错误: type=1时startDate必填");
            }
            dateList.add(startDate);
            actualStart = startDate;
            actualEnd = startDate;
        } else if ("2".equals(type)) {
            // type=2: 按日统计
            if (!StringUtils.hasText(startDate)) {
                return Map.of("code", 400, "msg", "参数错误: type=2时startDate必填");
            }
            if (StringUtils.hasText(endDate)) {
                // 有结束日期,直接用传入范围
                try {
                    Date start = sdf.parse(startDate);
                    Date end = sdf.parse(endDate);
                    Calendar cur = Calendar.getInstance();
                    cur.setTime(start);
                    while (!cur.getTime().after(end)) {
                        dateList.add(sdf.format(cur.getTime()));
                        cur.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    actualStart = startDate;
                    actualEnd = endDate;
                } catch (Exception e) {
                    return Map.of("code", 400, "msg", "日期格式错误: " + startDate + " ~ " + endDate);
                }
            } else {
                // 只有开始日期 -> 自动取所在月的1号~最后一天
                try {
                    Date startD = sdf.parse(startDate);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(startD);
                    cal.set(Calendar.DAY_OF_MONTH, 1);       // 月初
                    actualStart = sdf.format(cal.getTime());
                    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); // 月末
                    actualEnd = sdf.format(cal.getTime());

                    Calendar cur = Calendar.getInstance();
                    cur.setTime(sdf.parse(actualStart));
                    while (!cur.after(cal)) { // cur <= actualEnd
                        dateList.add(sdf.format(cur.getTime()));
                        cur.add(Calendar.DAY_OF_MONTH, 1);
                    }
                } catch (Exception e) {
                    return Map.of("code", 400, "msg", "日期格式错误: " + startDate);
                }
            }
        } else if ("3".equals(type)) {
            // type=3: 按月统计
            if (StringUtils.hasText(startDate) && StringUtils.hasText(endDate)) {
                // 有起止日期:按传入范围按月聚合
                try {
                    Date start = sdf.parse(startDate);
                    Date end = sdf.parse(endDate);
                    actualStart = startDate;
                    actualEnd = endDate;
                    Calendar cur = Calendar.getInstance();
                    cur.setTime(start);
                    while (!cur.getTime().after(end)) {
                        dateList.add(sdf.format(cur.getTime()));
                        cur.add(Calendar.DAY_OF_MONTH, 1);
                    }
                } catch (Exception e) {
                    return Map.of("code", 400, "msg", "日期格式错误: " + startDate + " ~ " + endDate);
                }
            } else {
                // 无日期:默认本年1月1日 ~ 今天
                Calendar now = Calendar.getInstance();
                int year = now.get(Calendar.YEAR);
                Calendar startCal = Calendar.getInstance();
                startCal.set(year, Calendar.JANUARY, 1);
                actualStart = sdf.format(startCal.getTime());
                actualEnd = sdf.format(now.getTime());

                Calendar cur = Calendar.getInstance();
                cur.setTime(startCal.getTime());
                while (!cur.getTime().after(now.getTime())) {
                    dateList.add(sdf.format(cur.getTime()));
                    cur.add(Calendar.DAY_OF_MONTH, 1);
                }
            }
        } else {
            return Map.of("code", 400, "msg", "参数错误: type只支持1/2/3");
        }

        log.info("实际日期范围: {} ~ {}, 共{}天", actualStart, actualEnd, dateList.size());

        // 获取所有设备列表及名称
        Map<String, String> deviceNameMap = queryAllEnergyDeviceNames();

        // 从 eq_kwh 批量查询所有记录
        List<Map<String, Object>> allRawData = queryEqKwhBatch(dateList);
        log.info("eq_kwh 批量查询返回 {} 条原始记录", allRawData.size());

        // 构建结果
        return buildEqKwhByTypeResult(type, dateList, allRawData, deviceNameMap, actualStart, actualEnd);
    }

    /**
     * 构建 type=1/2/3 的多设备查询结果
     */
    private Map<String, Object> buildEqKwhByTypeResult(String type, List<String> dateList,
                                                       List<Map<String, Object>> allRawData,
                                                       Map<String, String> deviceNameMap,
                                                       String actualStart, String actualEnd) {
        // 按 dtuSn+日期 建立快速查找Map: key="dtuSn|yyyy-MM-dd" -> JSONArray(kwh原始数据)
        Map<String, Object> rawDataMap = new LinkedHashMap<>();
        for (Map<String, Object> row : allRawData) {
            String sn = (String) row.get("dtuSn");
            String ud = String.valueOf(row.get("use_date"));
            String desc = row.get("description") != null ? String.valueOf(row.get("description")) : "";
            if (StringUtils.hasText(desc)) {
                try {
                    // use_date 可能是 "2026-05-21T00:00:00" 或 "2026-05-21 00:00:00",统一截取前10位作为纯日期key
                    String dateKey = ud.length() > 10 ? ud.substring(0, 10) : ud;
                    rawDataMap.put(sn + "|" + dateKey, JSON.parseArray(desc));
                } catch (Exception ignored) {
                }
            }
        }

        // ---- type=1: 返回所有设备的原始kwh明细 ----
        if ("1".equals(type)) {
            return buildType1Result(dateList.get(0), rawDataMap, deviceNameMap);
        }

        // ---- type=2: 按日统计 ----
        if ("2".equals(type)) {
            return buildType2Result(dateList, rawDataMap, deviceNameMap, actualStart, actualEnd);
        }

        // ---- type=3: 按月统计 ----
        if ("3".equals(type)) {
            return buildType3Result(dateList, rawDataMap, deviceNameMap, actualStart, actualEnd);
        }

        return Map.of("code", 500, "msg", "未知type");
    }

    /**
     * type=1 (时): 单日查询 - 返回每个设备的 kwh 原始数据 + 当日汇总
     */
    private Map<String, Object> buildType1Result(String dateStr, Map<String, Object> rawDataMap,
                                                 Map<String, String> deviceNameMap) {
        List<Map<String, Object>> list = new ArrayList<>();
        BigDecimal totalKwhAll = BigDecimal.ZERO;

        for (String sn : deviceNameMap.keySet()) {
            String mapKey = sn + "|" + dateStr;
            Object rawObj = rawDataMap.getOrDefault(mapKey, Collections.emptyList());
            @SuppressWarnings("unchecked")
            JSONArray dataArray = rawObj instanceof JSONArray ? (JSONArray) rawObj : new JSONArray();

            // 统计当日总用电量
            BigDecimal dayKwh = BigDecimal.ZERO;
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject item = dataArray.getJSONObject(i);
                if (item != null && item.getDouble("value") != null) {
                    dayKwh = dayKwh.add(BigDecimal.valueOf(item.getDouble("value")));
                }
            }
            totalKwhAll = totalKwhAll.add(dayKwh);

            Map<String, Object> item = new LinkedHashMap<>();
            item.put("dtuSn", sn);
            item.put("deviceName", deviceNameMap.getOrDefault(sn, ""));
            item.put("date", dateStr);
            item.put("kwhList", dataArray);
            item.put("totalKwh", dayKwh.setScale(2, RoundingMode.HALF_UP));
            list.add(item);
        }

        return Map.of(
                "code", 200, "msg", "请求成功",
                "type", "1",
                "date", dateStr,
                "totalDevices", deviceNameMap.size(),
                "totalKwh", totalKwhAll.setScale(2, RoundingMode.HALF_UP),
                "list", list
        );
    }

    /**
     * type=2 (日): 按设备统计 - 每个设备一行,包含该设备每天的能耗明细
     */
    private Map<String, Object> buildType2Result(List<String> dateList, Map<String, Object> rawDataMap,
                                                 Map<String, String> deviceNameMap,
                                                 String actualStart, String actualEnd) {
        BigDecimal grandTotalKwh = BigDecimal.ZERO;
        List<Map<String, Object>> deviceList = new ArrayList<>(deviceNameMap.size());

        for (String sn : deviceNameMap.keySet()) {
            Map<String, Object> devItem = new LinkedHashMap<>();
            devItem.put("dtuSn", sn);
            devItem.put("deviceName", deviceNameMap.getOrDefault(sn, ""));

            // 该设备的每日数据列表
            List<Map<String, Object>> dailyDataList = new ArrayList<>(dateList.size());
            BigDecimal devTotalKwh = BigDecimal.ZERO;
            long devTotalDur = 0;
            Map<Integer, Long> devStatusAll = initStatusMap();

            for (String d : dateList) {
                String mapKey = sn + "|" + d;
                Object rawObj = rawDataMap.getOrDefault(mapKey, Collections.emptyList());
                @SuppressWarnings("unchecked")
                JSONArray dataArray = rawObj instanceof JSONArray ? (JSONArray) rawObj : new JSONArray();

                BigDecimal dayKwh = BigDecimal.ZERO;
                long dayDur = 0;
                Map<Integer, Long> dayStatus = initStatusMap();

                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    if (item == null) continue;

                    Double value = item.getDouble("value");
                    if (value != null) dayKwh = dayKwh.add(BigDecimal.valueOf(value));

                    for (int sk = 0; sk <= 3; sk++) {
                        Long dur = item.getLong(String.valueOf(sk));
                        if (dur != null && dur > 0) {
                            dayDur += dur;
                            dayStatus.merge(sk, dur, Long::sum);
                            devTotalDur += dur;
                            devStatusAll.merge(sk, dur, Long::sum);
                        }
                    }
                }

                devTotalKwh = devTotalKwh.add(dayKwh);

                Map<String, Object> dayEntry = new LinkedHashMap<>();
                dayEntry.put("date", d);
                dayEntry.put("totalKwh", dayKwh.setScale(2, RoundingMode.HALF_UP));
                dayEntry.put("totalDurationFormatted", formatDuration(dayDur));
                dayEntry.put("totalDurationSeconds", dayDur);
                dayEntry.put("statusStats", buildStatusStats(dayStatus, dayDur));
                dailyDataList.add(dayEntry);
            }

            grandTotalKwh = grandTotalKwh.add(devTotalKwh);

            devItem.put("totalKwh", devTotalKwh.setScale(2, RoundingMode.HALF_UP));
            devItem.put("totalDurationFormatted", formatDuration(devTotalDur));
            devItem.put("totalDurationSeconds", devTotalDur);
            devItem.put("statusStats", buildStatusStats(devStatusAll, devTotalDur));
            devItem.put("dailyData", dailyDataList);

            deviceList.add(devItem);
        }

        return Map.of(
                "code", 200, "msg", "请求成功",
                "type", "2",
                "actualStartDate", actualStart,
                "actualEndDate", actualEnd,
                "totalDays", dateList.size(),
                "totalDevices", deviceList.size(),
                "grandTotalKwh", grandTotalKwh.setScale(2, RoundingMode.HALF_UP),
                "list", deviceList
        );
    }

    /**
     * type=3 (月): 按设备统计 - 每个设备一行,包含该设备每月的能耗明细
     */
    private Map<String, Object> buildType3Result(List<String> dateList, Map<String, Object> rawDataMap,
                                                 Map<String, String> deviceNameMap,
                                                 String actualStart, String actualEnd) {
        BigDecimal grandTotalKwh = BigDecimal.ZERO;
        List<Map<String, Object>> deviceList = new ArrayList<>(deviceNameMap.size());

        for (String sn : deviceNameMap.keySet()) {
            Map<String, Object> devItem = new LinkedHashMap<>();
            devItem.put("dtuSn", sn);
            devItem.put("deviceName", deviceNameMap.getOrDefault(sn, ""));

            // 该设备的按月聚合数据
            Map<String, Map<String, Object>> monthAgg = new LinkedHashMap<>();

            for (String d : dateList) {
                String monthKey = d.substring(0, 7);

                monthAgg.computeIfAbsent(monthKey, k -> {
                    Map<String, Object> m = new LinkedHashMap<>();
                    m.put("month", k);
                    m.put("label", Integer.parseInt(k.substring(5)) + "月");
                    m.put("totalKwh", BigDecimal.ZERO);
                    m.put("totalDurationSeconds", 0L);
                    m.put("statusDurationMap", initStatusMap());
                    return m;
                });

                String mapKey = sn + "|" + d;
                Object rawObj = rawDataMap.getOrDefault(mapKey, Collections.emptyList());
                @SuppressWarnings("unchecked")
                JSONArray dataArray = rawObj instanceof JSONArray ? (JSONArray) rawObj : new JSONArray();

                Map<String, Object> mEntry = monthAgg.get(monthKey);

                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    if (item == null) continue;

                    Double value = item.getDouble("value");
                    if (value != null) {
                        BigDecimal valBd = BigDecimal.valueOf(value);
                        mEntry.put("totalKwh", ((BigDecimal) mEntry.get("totalKwh")).add(valBd));
                    }

                    for (int sk = 0; sk <= 3; sk++) {
                        Long dur = item.getLong(String.valueOf(sk));
                        if (dur != null && dur > 0) {
                            mEntry.put("totalDurationSeconds", (Long) mEntry.get("totalDurationSeconds") + dur);
                            @SuppressWarnings("unchecked")
                            Map<Integer, Long> sMap = (Map<Integer, Long>) mEntry.get("statusDurationMap");
                            sMap.merge(sk, dur, Long::sum);
                        }
                    }
                }
            }

            // 构建该设备的月度数据列表
            List<Map<String, Object>> monthlyDataList = new ArrayList<>(monthAgg.size());
            BigDecimal devTotalKwh = BigDecimal.ZERO;
            long devTotalDur = 0;
            Map<Integer, Long> devStatusAll = initStatusMap();

            for (Map.Entry<String, Map<String, Object>> me : monthAgg.entrySet()) {
                Map<String, Object> m = me.getValue();
                long mDur = (Long) m.get("totalDurationSeconds");
                BigDecimal mKwh = (BigDecimal) m.get("totalKwh");
                @SuppressWarnings("unchecked")
                Map<Integer, Long> mStatus = (Map<Integer, Long>) m.get("statusDurationMap");

                devTotalKwh = devTotalKwh.add(mKwh);
                devTotalDur += mDur;
                for (int sk = 0; sk <= 3; sk++) {
                    long sd = mStatus.getOrDefault(sk, 0L);
                    if (sd > 0) devStatusAll.merge(sk, sd, Long::sum);
                }

                Map<String, Object> monthEntry = new LinkedHashMap<>();
                monthEntry.put("month", m.get("month"));
                monthEntry.put("label", m.get("label"));
                monthEntry.put("totalKwh", mKwh.setScale(2, RoundingMode.HALF_UP));
                monthEntry.put("totalDurationFormatted", formatDuration(mDur));
                monthEntry.put("totalDurationSeconds", mDur);
                monthEntry.put("statusStats", buildStatusStats(mStatus, mDur));
                monthlyDataList.add(monthEntry);
            }

            grandTotalKwh = grandTotalKwh.add(devTotalKwh);

            devItem.put("totalKwh", devTotalKwh.setScale(2, RoundingMode.HALF_UP));
            devItem.put("totalDurationFormatted", formatDuration(devTotalDur));
            devItem.put("totalDurationSeconds", devTotalDur);
            devItem.put("statusStats", buildStatusStats(devStatusAll, devTotalDur));
            devItem.put("monthlyData", monthlyDataList);

            deviceList.add(devItem);
        }

        return Map.of(
                "code", 200, "msg", "请求成功",
                "type", "3",
                "year", actualStart.substring(0, 4),
                "actualStartDate", actualStart,
                "actualEndDate", actualEnd,
                "totalMonths", dateList.isEmpty() ? 0 :
                        (dateList.stream().map(d -> d.substring(0, 7)).distinct().toList()).size(),
                "totalDevices", deviceList.size(),
                "grandTotalKwh", grandTotalKwh.setScale(2, RoundingMode.HALF_UP),
                "list", deviceList
        );
    }

    /** 调试接口: 查看eq_kwh表中的数据概况 */
    public Map<String, Object> debugEqKwhInfo() {
        // 总记录数
        Long totalCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM " + eqKwhTableName + " WHERE corp_code = ?", Long.class, energyCorpCode);

        // 按日期分组统计
        List<Map<String, Object>> dateStats = jdbcTemplate.queryForList(
                "SELECT use_date, COUNT(*) as cnt FROM " + eqKwhTableName +
                        " WHERE corp_code = ? GROUP BY use_date ORDER BY use_date DESC LIMIT 20",
                energyCorpCode);

        // 按设备分组统计
        List<Map<String, Object>> deviceStats = jdbcTemplate.queryForList(
                "SELECT dtuSn, COUNT(*) as cnt FROM " + eqKwhTableName +
                        " WHERE corp_code = ? GROUP BY dtuSn ORDER BY dtuSn",
                energyCorpCode);

        // 最新一条记录的 description 预览
        Map<String, Object> lastRecord = null;
        try {
            String sql = "SELECT dtuSn, use_date, LEFT(description, 500) AS desc_preview, LENGTH(description) as desc_len " +
                    "FROM " + eqKwhTableName + " WHERE corp_code = ? ORDER BY use_date DESC LIMIT 1";
            lastRecord = jdbcTemplate.queryForMap(sql, energyCorpCode);
        } catch (Exception ignored) {}

        // energy 表设备数
        Long deviceCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM " + energyTableName + " WHERE corp_code = ?", Long.class, energyCorpCode);

        return Map.of(
                "code", 200, "msg", "请求成功",
                "tableName", eqKwhTableName,
                "corpCode", energyCorpCode,
                "totalRecords", totalCount != null ? totalCount : 0,
                "deviceCountInEnergyTable", deviceCount != null ? deviceCount : 0,
                "latestDateRecords", dateStats,
                "perDeviceRecordCount", deviceStats,
                "lastRecordPreview", lastRecord
        );
    }
}