chenluhua1980
2026-01-19 30a7b29d0eb11ce87a9c0cafa0e5dd00c242d699
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
#include "stdafx.h"
#include "Common.h"
#include "AlarmManager.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <ctime>
#include <iomanip>
#include <random>
 
// ³£Á¿
const std::string DATABASE_FILE = R"(AlarmManager.db)";
 
// ¾²Ì¬³ÉÔ±³õʼ»¯
std::mutex AlarmManager::m_mutex;
 
// »ñÈ¡µ¥ÀýʵÀý
AlarmManager& AlarmManager::getInstance() {
    static AlarmManager instance;
    return instance;
}
 
// ¹¹Ô캯Êý
AlarmManager::AlarmManager() {
    m_pDB = new BL::SQLiteDatabase();
}
 
// Îö¹¹º¯Êý
AlarmManager::~AlarmManager() {
    if (m_pDB != nullptr) {
        delete m_pDB;
        m_pDB = nullptr;
    }
}
 
// ³õʼ»¯±¨¾¯±í
bool AlarmManager::initAlarmTable() {
    char path[MAX_PATH];
    GetModuleFileName(NULL, path, MAX_PATH);
    std::string exePath(path);
    std::string dbFileDir = exePath.substr(0, exePath.find_last_of("\\/")) + "\\DB";
    if (!CreateDirectory(dbFileDir.c_str(), NULL) && ERROR_ALREADY_EXISTS != GetLastError()) {
        throw std::runtime_error("Failed to create database directory.");
    }
 
    std::string dbFilePath = dbFileDir + "\\" + DATABASE_FILE;
    if (!m_pDB->connect(dbFilePath, true)) {
        throw std::runtime_error("Failed to connect to database.");
    }
 
    // ´´½¨É豸±í
    const std::string createDevicesTableQuery = R"(
        CREATE TABLE IF NOT EXISTS devices (
            device_id TEXT PRIMARY KEY NOT NULL,
            device_name TEXT NOT NULL
        )
    )";
    if (!m_pDB->executeQuery(createDevicesTableQuery)) {
        return false;
    }
 
    // ´´½¨µ¥Ôª±í£¬É豸IDºÍµ¥ÔªID×éºÏ×÷ΪÖ÷¼ü
    const std::string createUnitsTableQuery = R"(
        CREATE TABLE IF NOT EXISTS units (
            device_id TEXT NOT NULL,
            unit_id TEXT NOT NULL,
            unit_name TEXT NOT NULL,
            PRIMARY KEY (device_id, unit_id),
            FOREIGN KEY (device_id) REFERENCES devices(device_id)
        )
    )";
    if (!m_pDB->executeQuery(createUnitsTableQuery)) {
        return false;
    }
 
    // ´´½¨±¨¾¯±í£¬±¨¾¯¼Ç¼µÄalarm_event_idÊÇÖ÷¼ü
    const std::string createAlarmsTableQuery = R"(
        CREATE TABLE IF NOT EXISTS alarms (
            alarm_event_id INTEGER PRIMARY KEY AUTOINCREMENT,
            id TEXT NOT NULL,
            severity_level INTEGER NOT NULL DEFAULT 0,    
            device_id TEXT NOT NULL ,
            unit_id TEXT NOT NULL,
            description TEXT NOT NULL,
            start_time DATETIME NOT NULL,
            end_time DATETIME,
            FOREIGN KEY (device_id) REFERENCES devices(device_id),
            FOREIGN KEY (unit_id) REFERENCES units(unit_id)
        )
    )";
    if (!m_pDB->executeQuery(createAlarmsTableQuery)) {
        return false;
    }
 
    // É豸Áбí (ID -> Ãû³Æ)
    std::vector<std::pair<int, std::string>> devices = {
        {EQ_ID_LOADPORT1, EQ_NAME_LOADPORT1},
        {EQ_ID_LOADPORT2, EQ_NAME_LOADPORT2},
        {EQ_ID_LOADPORT3, EQ_NAME_LOADPORT3},
        {EQ_ID_LOADPORT4, EQ_NAME_LOADPORT4},
        {EQ_ID_ARM_TRAY1, EQ_NAME_ARM_TRAY1},
        {EQ_ID_ARM_TRAY2, EQ_NAME_ARM_TRAY2},
        {EQ_ID_ALIGNER, EQ_NAME_ALIGNER},
        {EQ_ID_FLIPER, EQ_NAME_FLIPER},
        {EQ_ID_VACUUMBAKE, EQ_NAME_VACUUMBAKE},
        {EQ_ID_Bonder1, EQ_NAME_BONDER1},
        {EQ_ID_Bonder2, EQ_NAME_BONDER2},
        {EQ_ID_BAKE_COOLING, EQ_NAME_BAKE_COOLING},
        {EQ_ID_MEASUREMENT, EQ_NAME_MEASUREMENT},
        {EQ_ID_EFEM, EQ_NAME_EFEM},
        {EQ_ID_ARM, EQ_NAME_ARM},
        {EQ_ID_OPERATOR_REMOVE, EQ_NAME_OPERATOR_REMOVE}
    };
 
    // ²åÈë devices ºÍ¶ÔÓ¦µÄĬÈÏ unit
    for (const auto& dev : devices) {
        int nDeviceId = dev.first;
        const std::string& strDeviceName = dev.second;
 
        // ²åÈëÉ豸
        std::ostringstream ossDev;
        ossDev << "INSERT OR IGNORE INTO devices (device_id, device_name) VALUES("
            << nDeviceId << ", '" << strDeviceName << "')";
        if (!m_pDB->executeQuery(ossDev.str())) {
            return false;
        }
 
        // ²åÈëĬÈϵ¥Ôª (unit_id = 0, unit_name = device_name)
        std::ostringstream ossUnit;
        ossUnit << "INSERT OR IGNORE INTO units (device_id, unit_id, unit_name) VALUES("
            << nDeviceId << ", 0, '" << strDeviceName << "')";
        if (!m_pDB->executeQuery(ossUnit.str())) {
            return false;
        }
    }
 
    return true;
}
 
// Ïú»Ù±¨¾¯±í
void AlarmManager::termAlarmTable() {
    if (m_pDB != nullptr) {
        m_pDB->disconnect();
    }
}
 
// Ïú»Ù±¨¾¯±í
bool AlarmManager::destroyAlarmTable() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    const std::string dropTableQuery = "DROP TABLE IF EXISTS alarms";
    return m_pDB->executeQuery(dropTableQuery);
}
 
// ²åÈëÄ£ÄâÊý¾Ý
void AlarmManager::insertMockData() {
    // ²åÈëÉ豸Êý¾Ý
    for (int i = 1; i <= 3; ++i) {
        std::string deviceName = "Device" + std::to_string(i);
        std::stringstream query;
        query << "INSERT INTO devices (device_id, device_name) VALUES (" << i << ", '" << deviceName << "');";
        if (!m_pDB->executeQuery(query.str())) {
            std::cerr << "Failed to insert device: " << i << std::endl;
        }
    }
 
    // ²åÈëµ¥ÔªÊý¾Ý
    for (int i = 1; i <= 3; ++i) {
        for (int j = 0; j <= 3; ++j) {
            int unitId = j;
            std::string deviceId = std::to_string(i);
            std::string unitName = "Unit" + std::to_string(j);
 
            std::stringstream query;
            query << "INSERT INTO units (device_id, unit_id, unit_name) VALUES ('"
                << deviceId << "', '"   // ²åÈëÉ豸ID£¬È·±£ÊÇ×Ö·û´®
                << unitId << "', '"     // ²åÈëµ¥ÔªID£¬È·±£ÊÇ×Ö·û´®
                << unitName << "');";
 
            if (!m_pDB->executeQuery(query.str())) {
                std::cerr << "Failed to insert unit: " << unitId << std::endl;
            }
        }
    }
 
    /*
    // ³õʼ»¯Ëæ»úÊýÉú³ÉÆ÷
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> deviceDis(1, 3);
    std::uniform_int_distribution<> unitDis(1, 3);
    std::uniform_int_distribution<> errorCodeDis(1, 100);
    std::uniform_int_distribution<> severityDis(0, 3);
    std::vector<std::string> descriptions = { "Overheat", "Sensor failure", "Power outage" };
 
    // Ê±¼äÏà¹Ø
    auto now = std::chrono::system_clock::now();
    auto start_time = std::chrono::system_clock::to_time_t(now);
    auto end_time = std::chrono::system_clock::to_time_t(now + std::chrono::minutes(10));
 
    std::tm start_tm = {};
    std::tm end_tm = {};
    localtime_s(&start_tm, &start_time);
    localtime_s(&end_tm, &end_time);
 
    // ²åÈëÄ£ÄâÊý¾Ý
    for (int i = 0; i < 10; ++i) {
        int deviceId = deviceDis(gen);          // Ëæ»úÉ豸ID
        int unitId = unitDis(gen);              // Ëæ»úµ¥ÔªID
        int errorCode = errorCodeDis(gen);      // Ëæ»ú´íÎóÂë
        int severityLevel = severityDis(gen);   // Ëæ»úÉú³É±¨¾¯µÈ¼¶
        std::string description = descriptions[errorCodeDis(gen) % descriptions.size()];  // Ëæ»ú±¨¾¯ÃèÊö
 
        std::stringstream query;
        query << "INSERT INTO alarms (id, severity_level, device_id, unit_id, description, start_time, end_time) "
            << "VALUES (" << errorCode << ", " << severityLevel << ", " << deviceId << ", " << unitId << ", '" << description << "', "
            << "'" << std::put_time(&start_tm, "%Y-%m-%d %H:%M:%S") << "', "
            << "'" << std::put_time(&end_tm, "%Y-%m-%d %H:%M:%S") << "');";
 
        if (!m_pDB->executeQuery(query.str())) {
            std::cerr << "Failed to insert alarm data." << std::endl;
        }
    }
    */
}
 
// Ìí¼Ó±¨¾¯ÐÅÏ¢
bool AlarmManager::addAlarm(const AlarmData& alarmData, int& alarmEventId) {
    if (!m_pDB) {
        return false;
    }
 
    #if 0
        // ¿ªÊ¼ÊÂÎñ
        m_pDB->executeQuery("BEGIN TRANSACTION;");
    
        // ¹¹½¨²åÈë²éѯ
        std::ostringstream query;
        query << "INSERT INTO alarms (id, severity_level, device_id, unit_id, description, start_time, end_time) VALUES ("
            << alarmData.nId << ", "              // ´íÎóÂë
            << alarmData.nSeverityLevel << ", "   // ±¨¾¯µÈ¼¶
            << alarmData.nDeviceId << ", "        // É豸ID
            << alarmData.nUnitId << ", '"         // µ¥ÔªID
            << alarmData.strDescription << "', '" // ÃèÊö
            << alarmData.strStartTime << "', '"   // ¿ªÊ¼Ê±¼ä
            << alarmData.strEndTime << "')";      // ½áÊøÊ±¼ä
    
        // Ê¹ÓÃËø±£»¤¶àḬ̈߳²È«
        std::lock_guard<std::mutex> lock(m_mutex);
    
        // Ö´ÐвåÈë²éѯ
        bool result = m_pDB->executeQuery(query.str());
        if (result) {
            alarmEventId = getLastInsertId();
            m_alarmCache[alarmEventId] = alarmData;
        }
    
        // Ìá½»ÊÂÎñ
        m_pDB->executeQuery("COMMIT;");
    
        return result;
    #else
        for (AlarmDataMap::const_iterator it = m_mapCache.begin(); it != m_mapCache.end(); ++it) {
            const AlarmData& alarm = it->second;
            if (alarm.nId == alarmData.nId &&
                alarm.nDeviceId == alarmData.nDeviceId &&
                alarm.nUnitId == alarmData.nUnitId) {
 
                alarmEventId = it->first;
                return false;
            }
        }
 
        // ¹¹½¨²åÈë²éѯ²¢Ê¹ÓàRETURNING »ñÈ¡²åÈëºóµÄ alarm_event_id
        std::ostringstream query;
        query << "INSERT INTO alarms (id, severity_level, device_id, unit_id, description, start_time, end_time) "
            << "VALUES (" << alarmData.nId << ", " << alarmData.nSeverityLevel << ", " << alarmData.nDeviceId << ", "
            << alarmData.nUnitId << ", '" << alarmData.strDescription << "', '" << alarmData.strStartTime << "', '"
            << alarmData.strEndTime << "') RETURNING alarm_event_id;";
    
        // Ê¹ÓÃËø±£»¤¶àḬ̈߳²È«
        std::lock_guard<std::mutex> lock(m_mutex);
    
        // Ö´Ðвéѯ²¢»ñÈ¡½á¹û
        auto results = m_pDB->fetchResults(query.str());
        if (!results.empty() && !results[0].empty()) {
            try {
                // ÌáÈ¡²¢×ª»» alarm_event_id
                alarmEventId = std::stoi(results[0][0]);
                // ½«²åÈëµÄ±¨¾¯Êý¾ÝÌí¼Óµ½»º´æ
                m_mapCache[alarmEventId] = alarmData;
                return true;
            }
            catch (const std::exception& e) {
                std::cerr << "Error parsing alarm_event_id: " << e.what() << std::endl;
                return false;
            }
        }
    
        return false;
    #endif
}
 
// ²éѯËùÓб¨¾¯Êý¾Ý
std::vector<AlarmData> AlarmManager::getAllAlarms() {
    if (!m_pDB) {
        return {};
    }
 
    // ²éѯËùÓб¨¾¯Êý¾Ý£¨°üÀ¨É豸Ãû³ÆºÍµ¥ÔªÃû³Æ£©
    const std::string query = R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u ON a.device_id = u.device_id AND a.unit_id = u.unit_id
    )";
 
    auto results = m_pDB->fetchResults(query);
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);              // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);   // ±¨¾¯µÈ¼¶
        alarmData.nDeviceId = std::stoi(row[2]);        // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);          // µ¥ÔªID
        alarmData.strDeviceName = row[4];               // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                 // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];              // ÃèÊö
        alarmData.strStartTime = row[7];                // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                  // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// ¸ù¾Ý±¨¾¯ID²éѯ±¨¾¯
std::vector<AlarmData> AlarmManager::getAlarmsById(const std::string& id) {
    if (!m_pDB) {
        return {};
    }
 
    std::ostringstream query;
    query << R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        WHERE a.id = ')" << id << "'";
 
    auto results = m_pDB->fetchResults(query.str());
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);              // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);   // ±¨¾¯µÈ¼¶
        alarmData.nDeviceId = std::stoi(row[2]);        // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);          // µ¥ÔªID
        alarmData.strDeviceName = row[4];               // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                 // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];              // ÃèÊö
        alarmData.strStartTime = row[7];                // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                  // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// ¸ù¾ÝÃèÊö²éѯ±¨¾¯
std::vector<AlarmData> AlarmManager::getAlarmsByDescription(const std::string& description) {
    if (!m_pDB) {
        return {};
    }
 
    std::ostringstream query;
    query << R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        WHERE a.description LIKE '%)" << description << R"(%')";
 
    auto results = m_pDB->fetchResults(query.str());
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);              // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);   // ±¨¾¯µÈ¼¶
        alarmData.nDeviceId = std::stoi(row[2]);        // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);          // µ¥ÔªID
        alarmData.strDeviceName = row[4];               // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                 // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];              // ÃèÊö
        alarmData.strStartTime = row[7];                // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                  // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// ¸ù¾Ýʱ¼ä·¶Î§²éѯ±¨¾¯
std::vector<AlarmData> AlarmManager::getAlarmsByTimeRange(const std::string& startTime, const std::string& endTime) {
    if (!m_pDB) {
        return {};
    }
 
    std::ostringstream query;
    query << R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        WHERE 1=1)";
 
    if (!startTime.empty()) {
        query << " AND a.start_time >= '" << startTime << "'";
    }
    if (!endTime.empty()) {
        query << " AND a.end_time <= '" << endTime << "'";
    }
 
    auto results = m_pDB->fetchResults(query.str());
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);              // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);   // ±¨¾¯µÈ¼¶
        alarmData.nDeviceId = std::stoi(row[2]);        // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);          // µ¥ÔªID
        alarmData.strDeviceName = row[4];               // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                 // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];              // ÃèÊö
        alarmData.strStartTime = row[7];                // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                  // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// ¸ù¾ÝID¡¢¿ªÊ¼Ê±¼äºÍ½áÊøÊ±¼ä²éѯ±¨¾¯
std::vector<AlarmData> AlarmManager::getAlarmsByIdAndTimeRange(const std::string& id, const std::string& startTime, const std::string& endTime) {
    if (!m_pDB) {
        return {};
    }
 
    std::ostringstream query;
    query << R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        WHERE a.id = ')" << id << "'";
 
    if (!startTime.empty()) {
        query << " AND a.start_time >= '" << startTime << "'";
    }
    if (!endTime.empty()) {
        query << " AND a.end_time <= '" << endTime << "'";
    }
 
    auto results = m_pDB->fetchResults(query.str());
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);              // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);   // ±¨¾¯µÈ¼¶
        alarmData.nDeviceId = std::stoi(row[2]);        // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);          // µ¥ÔªID
        alarmData.strDeviceName = row[4];               // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                 // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];              // ÃèÊö
        alarmData.strStartTime = row[7];                // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                  // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// ·ÖÒ³²éѯ±¨¾¯Êý¾Ý
std::vector<AlarmData> AlarmManager::getAlarms(int startPosition, int count) {
    if (!m_pDB) {
        return {};
    }
 
    std::ostringstream query;
    query << R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        LIMIT )" << count << " OFFSET " << startPosition;
 
    auto results = m_pDB->fetchResults(query.str());
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);              // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);   // ±¨¾¯µÈ¼¶
        alarmData.nDeviceId = std::stoi(row[2]);        // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);          // µ¥ÔªID
        alarmData.strDeviceName = row[4];               // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                 // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];              // ÃèÊö
        alarmData.strStartTime = row[7];                // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                  // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// É¸Ñ¡±¨¾¯Êý¾Ý
std::vector<AlarmData> AlarmManager::getFilteredAlarms(const std::string& keyword, const std::string& startTime, const std::string& endTime, int pageNumber, int pageSize) {
    if (!m_pDB) {
        return {};
    }
 
    std::ostringstream query;
    query << R"(
        SELECT a.id, a.severity_level, a.device_id, a.unit_id, d.device_name, u.unit_name, a.description, a.start_time, a.end_time
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u   ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        WHERE 1=1)";
 
    // Í³Ò»¹Ø¼ü×ÖÄ£ºý²éѯ
    if (!keyword.empty()) {
        query << " AND ("
            << "a.id LIKE '%" << keyword << "%' OR "
            << "a.severity_level LIKE '%" << keyword << "%' OR "
            << "d.device_name LIKE '%" << keyword << "%' OR "
            << "u.unit_name LIKE '%" << keyword << "%' OR "
            << "a.description LIKE '%" << keyword << "%')";
    }
 
    // Ê±¼äÌõ¼þ
    if (!startTime.empty()) {
        query << " AND a.start_time >= '" << startTime << "'";
    }
    if (!endTime.empty()) {
        query << " AND a.end_time <= '" << endTime << "'";
    }
 
    // ·ÖÒ³ÉèÖÃ
    int nOffset = (pageNumber - 1) * pageSize;
    query << " ORDER BY a.start_time DESC LIMIT " << pageSize << " OFFSET " << nOffset;
 
    // ²éѯ
    auto results = m_pDB->fetchResults(query.str());
 
    // ±éÀú²éѯ½á¹û£¬Ìî³ä AlarmData ½á¹¹Ìå
    std::vector<AlarmData> alarms;
    for (const auto& row : results) {
        AlarmData alarmData;
        alarmData.nId = std::stoi(row[0]);             // ´íÎóÂë
        alarmData.nSeverityLevel = std::stoi(row[1]);  // ±¨¾¯µÈ¼¶ (×Ö·û´®)
        alarmData.nDeviceId = std::stoi(row[2]);       // É豸ID
        alarmData.nUnitId = std::stoi(row[3]);         // µ¥ÔªID
        alarmData.strDeviceName = row[4];              // É豸Ãû³Æ
        alarmData.strUnitName = row[5];                // µ¥ÔªÃû³Æ
        alarmData.strDescription = row[6];             // ÃèÊö
        alarmData.strStartTime = row[7];               // ¿ªÊ¼Ê±¼ä
        alarmData.strEndTime = row[8];                 // ½áÊøÊ±¼ä
 
        alarms.push_back(alarmData);
    }
 
    return alarms;
}
 
// »ñÈ¡·ûºÏÌõ¼þµÄ±¨¾¯×ÜÊý
int AlarmManager::getTotalAlarmCount(const std::string& keyword, const std::string& startTime, const std::string& endTime) {
    if (!m_pDB) {
        return 0;
    }
 
    std::ostringstream query;
    query << R"(
        SELECT COUNT(*)
        FROM alarms a
        JOIN devices d ON a.device_id = d.device_id
        JOIN units u   ON a.device_id = u.device_id AND a.unit_id = u.unit_id
        WHERE 1=1)";
 
    // Í³Ò»¹Ø¼ü×ÖÄ£ºý²éѯ
    if (!keyword.empty()) {
        query << " AND ("
            << "a.id LIKE '%" << keyword << "%' OR "
            << "a.severity_level LIKE '%" << keyword << "%' OR "
            << "d.device_name LIKE '%" << keyword << "%' OR "
            << "u.unit_name LIKE '%" << keyword << "%' OR "
            << "a.description LIKE '%" << keyword << "%')";
    }
 
    // Ê±¼äÌõ¼þ
    if (!startTime.empty()) {
        query << " AND a.start_time >= '" << startTime << "'";
    }
    if (!endTime.empty()) {
        query << " AND a.end_time <= '" << endTime << "'";
    }
 
    auto results = m_pDB->fetchResults(query.str());
    return (!results.empty() && !results[0].empty()) ? std::stoi(results[0][0]) : 0;
}
 
// ¸üб¨¾¯µÄ½áÊøÊ±¼ä
bool AlarmManager::updateAlarmEndTime(
    const std::string& id,
    const std::string& severityLevel,
    const std::string& deviceId,
    const std::string& unitId,
    const std::string& description,
    const std::string& startTime,
    const std::string& newEndTime) {
 
    if (!m_pDB) {
        return false;
    }
 
    // ¸üб¨¾¯½áÊøÊ±¼ä
    std::ostringstream updateQuery;
    updateQuery << "UPDATE alarms SET end_time = '" << newEndTime << "'"
        << " WHERE id = '" << id << "'"
        << " AND severity_level = '" << severityLevel << "'"
        << " AND device_id = '" << deviceId << "'"
        << " AND unit_id = '" << unitId << "'"
        << " AND description = '" << description << "'"
        << " AND start_time = '" << startTime << "'";
 
    return m_pDB->executeQuery(updateQuery.str());
}
 
// ÇåÀí¾É±¨¾¯Êý¾Ý
void AlarmManager::cleanOldAlarms(int daysToKeep, const std::string& deviceId, const std::string& unitId) {
    if (!m_pDB) {
        return;
    }
 
    std::ostringstream query;
    query << "DELETE FROM alarms WHERE end_time < datetime('now', '-" << daysToKeep << " days')";
 
    if (!deviceId.empty()) {
        query << " AND device_id = '" << deviceId << "'";
    }
    if (!unitId.empty()) {
        query << " AND unit_id = '" << unitId << "'";
    }
 
    m_pDB->executeQuery(query.str());
}
 
// Í¨¹ýÉ豸ID»ñÈ¡É豸Ãû³Æ
std::string AlarmManager::getDeviceNameById(int deviceId) {
    if (!m_pDB) {
        return "";
    }
 
    std::ostringstream query;
    query << "SELECT device_name FROM devices WHERE device_id = " << deviceId;
 
    auto result = m_pDB->fetchResults(query.str());
    if (result.empty()) {
        return "";
    }
 
    return result[0][0];  // ·µ»Ø²éѯµ½µÄÉ豸Ãû³Æ
}
 
// Í¨¹ýÉ豸IDºÍµ¥ÔªID»ñÈ¡µ¥ÔªÃû³Æ
std::string AlarmManager::getUnitNameById(int deviceId, int unitId) {
    if (!m_pDB) {
        return "";
    }
 
    std::ostringstream query;
    query << "SELECT unit_name FROM units WHERE device_id = " << deviceId
        << " AND unit_id = " << unitId;
 
    auto result = m_pDB->fetchResults(query.str());
    if (result.empty()) {
        return "";
    }
 
    return result[0][0];  // ·µ»Ø²éѯµ½µÄµ¥ÔªÃû³Æ
}
 
// »ñÈ¡×î½ü²åÈëµÄ alarm_event_id
int AlarmManager::getLastInsertId() {
    std::string query = "SELECT last_insert_rowid();";
    auto results = m_pDB->fetchResults(query);
 
    if (results.empty() || results[0].empty()) {
        return -1;
    }
 
    // ´Ó²éѯ½á¹ûÖлñÈ¡×îºó²åÈëµÄ ID
    int lastInsertId = std::stoi(results[0][0]);
    return lastInsertId;
}
 
// Í¨¹ý alarm_event_id ½â³ý±¨¾¯£¨¸üнáÊøÊ±¼ä£©
bool AlarmManager::clearAlarmByEventId(int alarmEventId, const std::string& endTime) {
    if (!m_pDB) {
        return false;
    }
 
    bool result = true;
    auto it = m_mapCache.find(alarmEventId);
    if (it != m_mapCache.end()) {
        std::lock_guard<std::mutex> lock(m_mutex);
 
        std::ostringstream query;
        query << "UPDATE alarms SET end_time = '" << endTime << "' WHERE alarm_event_id = " << alarmEventId << ";";
        bool result = m_pDB->executeQuery(query.str());
        if (result) {
            m_mapCache.erase(it);
        }
    }
 
    return result;
}
 
// Í¨¹ý¶à¸öÊôÐÔ²éÕÒ²¢½â³ý±¨¾¯£¨¸üнáÊøÊ±¼ä£©
bool AlarmManager::clearAlarmByAttributes(int nId, int nDeviceId, int nUnitId, const std::string& endTime) {
    if (!m_pDB) {
        return false;
    }
 
    std::lock_guard<std::mutex> lock(m_mutex);
 
    // ÏÈÔÚ»º´æÖвéÕÒÆ¥ÅäµÄ alarm_event_id
    int alarmEventId = -1;
    for (AlarmDataMap::const_iterator it = m_mapCache.begin(); it != m_mapCache.end(); ++it) {
        const AlarmData& alarm = it->second;
        if (alarm.nId == nId &&
            alarm.nDeviceId == nDeviceId &&
            alarm.nUnitId == nUnitId) {
 
            alarmEventId = it->first;
            break;
        }
    }
 
    // Èç¹ûûÕÒµ½Æ¥ÅäµÄ¼Ç¼£¬ÔòÖ±½Ó·µ»Ø false
    if (alarmEventId == -1) {
        return false;
    }
 
    // ¹¹½¨ SQL Óï¾ä£¬Ê¹ÓÃÕÒµ½µÄ alarm_event_id À´¸üнáÊøÊ±¼ä
    std::ostringstream query;
    query << "UPDATE alarms SET end_time = '" << endTime << "' WHERE alarm_event_id = " << alarmEventId << ";";
    bool result = m_pDB->executeQuery(query.str());
    if (result) {
        m_mapCache.erase(alarmEventId);
    }
 
    return result;
}
 
// ¶ÁÈ¡±¨¾¯Îļþ
bool AlarmManager::readAlarmFile(const std::string& filename) {
    std::ifstream file(filename, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Error opening file!" << std::endl;
        return false;
    }
 
    auto getline_cross = [](std::ifstream& f, std::string& out) -> bool {
        out.clear();
        char ch;
        while (f.get(ch)) {
            if (ch == '\r') {
                // ´¦Àí \r\n »ò µ¥¶À \r
                if (f.peek() == '\n') f.get();
                break;
            }
            else if (ch == '\n') {
                break;
            }
            out.push_back(ch);
        }
        return !out.empty() || !f.eof();
    };
 
    std::string line;
    bool first_line = true;
 
    while (getline_cross(file, line)) {
        if (first_line) {
            first_line = false;
            continue;
        }
 
        std::stringstream ss(line);
        std::string cell;
        AlarmInfo alarm;
 
        try {
            if (!std::getline(ss, cell, ',')) throw std::runtime_error("Missing field: No");
            if (!std::getline(ss, alarm.strUnitID, ',')) throw std::runtime_error("Missing field: UnitID");
            if (!std::getline(ss, alarm.strUnitNo, ',')) throw std::runtime_error("Missing field: UnitNo");
            if (!std::getline(ss, cell, ',')) throw std::runtime_error("Missing field: AlarmLevel");
            alarm.nAlarmLevel = std::stoi(cell);
            if (!std::getline(ss, cell, ',')) throw std::runtime_error("Missing field: AlarmCode");
            alarm.nAlarmCode = std::stoi(cell);
            if (!std::getline(ss, cell, ',')) throw std::runtime_error("Missing field: AlarmID");
            alarm.nAlarmID = std::stoi(cell);
            if (!std::getline(ss, alarm.strAlarmText, ',')) throw std::runtime_error("Missing field: AlarmText");
            if (!std::getline(ss, alarm.strDescription, ',')) throw std::runtime_error("Missing field: Description");
 
            if (m_mapAlarm.find(alarm.nAlarmID) == m_mapAlarm.end()) {
                m_mapAlarm[alarm.nAlarmID] = alarm;
            }
            else {
                std::cerr << "Duplicate AlarmID: " << alarm.nAlarmID << std::endl;
            }
        }
        catch (const std::exception& e) {
            std::cerr << "Error parsing line: " << line << " - " << e.what() << std::endl;
            continue;
        }
    }
 
    file.close();
    return true;
}
 
// ½«±¨¾¯Êý¾Ý±£´æµ½Îļþ
bool AlarmManager::saveAlarmFile(const std::string& filename) {
    std::ofstream file(filename);
 
    if (!file.is_open()) {
        std::cerr << "´ò¿ªÎļþдÈëʧ°Ü!" << std::endl;
        return false;
    }
 
    // Ð´Èë±êÌâÐÐ
    file << "No,UNIT ID,UNIT NO,Alarm Level,Alarm Code,AlarmID,Alarm Text,Description\n";
 
    // Ð´È뱨¾¯Êý¾Ý
    int nIndex = 1;
    for (const auto& pair : m_mapAlarm) {
        const AlarmInfo& alarm = pair.second;
        file << nIndex++ << ","
            << alarm.strUnitID << ","
            << alarm.strUnitNo << ","
            << alarm.nAlarmLevel << ","
            << alarm.nAlarmCode << ","
            << alarm.nAlarmID << ","
            << alarm.strAlarmText << ","
            << alarm.strDescription << "\n";
    }
 
    file.close();
    return true;
}
 
// Í¨¹ý AlarmID ²éѯ¶ÔÓ¦µÄ±¨¾¯ÐÅÏ¢
const AlarmInfo* AlarmManager::getAlarmInfoByID(int nAlarmID) const {
    auto it = m_mapAlarm.find(nAlarmID);
    if (it != m_mapAlarm.end()) {
        return &(it->second);
    }
    else {
        std::cerr << "δÕÒµ½ AlarmID: " << nAlarmID << std::endl;
        return nullptr;
    }
}
 
// Í¨¹ý¶à¸ö AlarmID ²éѯ¶ÔÓ¦µÄ±¨¾¯ÐÅÏ¢
std::vector<AlarmInfo> AlarmManager::getAlarmsInfoByIDs(const std::vector<int>& alarmIDs) const {
    std::vector<AlarmInfo> alarms;
 
    for (int alarmID : alarmIDs) {
        auto it = m_mapAlarm.find(alarmID);
        if (it != m_mapAlarm.end()) {
            alarms.push_back(it->second);
        } 
        else {
            std::cerr << "δÕÒµ½ AlarmID: " << alarmID << std::endl;
        }
    }
 
    return alarms;
}