-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataManager.cpp
More file actions
1757 lines (1589 loc) · 48.9 KB
/
Copy pathDataManager.cpp
File metadata and controls
1757 lines (1589 loc) · 48.9 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
/**
* @file DataManager.cpp
* @brief 数据管理器类实现
*
* 实现DataManager类的所有成员函数,包括数据初始化、读写操作和查询功能。
*/
#include "DataManager.h"
#include "Admin.h"
#include "Reader.h"
#include "StudentReader.h"
#include "TeacherReader.h"
#include "ExternalReader.h"
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QDebug>
#include <QCoreApplication>
#include <QFileInfo>
#include <algorithm>
/**
* @brief DataManager单例对象的静态指针
*/
DataManager *DataManager::instance = nullptr;
/**
* @brief 获取DataManager单例对象
* @return DataManager单例指针
*
* 采用懒汉式单例模式,第一次调用时创建实例。
*/
DataManager *DataManager::getInstance()
{
if (instance == nullptr)
{
instance = new DataManager();
}
return instance;
}
/**
* @brief 私有构造函数
*
* 初始化数据文件路径,创建数据目录(如果不存在),
* 并加载所有数据文件。
*/
DataManager::DataManager()
{
// 设置数据文件保存路径
// 优先使用应用程序目录下的data子目录
QString appDir = QCoreApplication::applicationDirPath();
QString dataDir = appDir + "/data";
// 检查应用程序目录下是否存在data目录,如果不存在,尝试使用项目根目录
QDir appDataDir(dataDir);
if (!appDataDir.exists())
{
// 尝试使用应用程序目录的上一级目录(项目根目录)
QDir parentDir(appDir);
if (parentDir.cdUp())
{
dataDir = parentDir.path() + "/data";
}
}
// 设置各数据文件路径
userFilePath = dataDir + "/users.txt";
bookFilePath = dataDir + "/books.txt";
borrowRecordFilePath = dataDir + "/borrow_records.txt";
reservationFilePath = dataDir + "/reservations.txt";
messageFilePath = dataDir + "/messages.txt";
// 检查并创建数据目录
QDir dir(dataDir);
if (!dir.exists())
{
dir.mkpath(dataDir);
}
// 读取所有数据文件
initUser();
initBook();
initBorrowRecord();
initReservation();
initMessage();
// 根据借阅记录重新计算所有读者信用分(必须在initMessage之后调用)
recalculateCreditScores();
}
/**
* @brief 析构函数
*
* 析构时自动保存所有数据到文件,并释放用户对象的内存。
*/
DataManager::~DataManager()
{
// 保存所有数据
writeUser();
writeBook();
writeBorrowRecord();
writeReservation();
// 释放users中动态分配的内存
for (auto user : users)
{
delete user;
}
}
// ========== 用户管理 ==========
/**
* @brief 根据ID查找用户(模糊匹配)
* @param id 用户ID关键字
* @return 匹配的用户指针列表
*/
std::vector<::User *> DataManager::findUsersById(const QString &id)
{
std::vector<::User *> results;
for (::User *user : users)
{
if (user->getID().contains(id, Qt::CaseInsensitive))
{
results.push_back(user);
}
}
return results;
}
/**
* @brief 根据姓名查找用户(模糊匹配)
* @param name 用户姓名关键字
* @return 匹配的用户指针列表
*/
std::vector<::User *> DataManager::findUsersByName(const QString &name)
{
std::vector<::User *> results;
for (::User *user : users)
{
if (user->getName().contains(name, Qt::CaseInsensitive))
{
results.push_back(user);
}
}
return results;
}
/**
* @brief 根据ID精确查找用户
* @param id 用户ID
* @return 匹配的用户指针(未找到返回nullptr)
*/
::User *DataManager::findUserById(const QString &id)
{
for (::User *user : users)
{
if (user->getID() == id)
{
return user;
}
}
return nullptr;
}
/**
* @brief 根据ID和姓名同时查找用户(均为模糊匹配)
* @param id 用户ID关键字
* @param name 用户姓名关键字
* @return 匹配的用户指针列表
*/
std::vector<::User *> DataManager::searchUsers(const QString &id, const QString &name)
{
std::vector<::User *> results;
for (::User *user : users)
{
bool match = true;
// ID模糊匹配
if (!id.isEmpty())
{
if (!user->getID().contains(id, Qt::CaseInsensitive))
{
match = false;
}
}
// 姓名模糊匹配
if (!name.isEmpty())
{
if (!user->getName().contains(name, Qt::CaseInsensitive))
{
match = false;
}
}
if (match)
{
results.push_back(user);
}
}
return results;
}
/**
* @brief 添加用户并保存到文件
* @param user 用户指针
*/
void DataManager::addUser(::User *user)
{
users.push_back(user);
writeUser();
}
/**
* @brief 根据ID和姓名同时删除用户并保存到文件
* @param id 用户ID
* @param name 用户姓名
* @return 删除成功返回true,失败返回false
*/
bool DataManager::deleteUser(const QString &id, const QString &name)
{
for (auto it = users.begin(); it != users.end(); ++it)
{
// ID和姓名都需要匹配
if ((*it)->getID() == id && (*it)->getName() == name)
{
delete *it;
users.erase(it);
writeUser();
return true;
}
}
return false;
}
/**
* @brief 根据ID和姓名同时修改用户信息并保存到文件
* @param id 用户ID
* @param name 用户姓名
* @param newUser 新用户信息
* @return 修改成功返回true,失败返回false
*/
bool DataManager::updateUser(const QString &id, const QString &name, ::User *newUser)
{
for (auto it = users.begin(); it != users.end(); ++it)
{
// ID和姓名都需要匹配
if ((*it)->getID() == id && (*it)->getName() == name)
{
delete *it;
*it = newUser;
writeUser();
return true;
}
}
return false;
}
/**
* @brief 清除所有用户并保存到文件
*/
void DataManager::clearAllUsers()
{
for (auto user : users)
{
delete user;
}
users.clear();
writeUser();
}
// ========== 数据清除 ==========
/**
* @brief 清空预约记录
*/
void DataManager::clearAllReservations()
{
reservations.clear();
writeReservation();
}
/**
* @brief 清空借书记录
*/
void DataManager::clearAllBorrowRecords()
{
borrowRecords.clear();
writeBorrowRecord();
}
/**
* @brief 清空消息记录
*/
void DataManager::clearAllMessages()
{
for (auto user : users)
{
user->clearMessages();
}
writeMessage();
}
/**
* @brief 获取所有用户
* @return 用户指针列表引用
*/
std::vector<::User *> &DataManager::getUsers()
{
return users;
}
/**
* @brief 获取用户数量
* @return 用户总数
*/
int DataManager::getUserCount() const
{
return users.size();
}
/**
* @brief 初始化读取用户数据
*
* 从users.txt文件中读取用户信息,包括ID、类型、角色、姓名、密码、电话、邮箱、
* 信用分、之前信用分和限制终止日期。
* 对于读者类型用户,根据role字段创建对应的子类(StudentReader/TeacherReader/ExternalReader),
* 并额外初始化信用分和借阅策略相关信息。
* 兼容旧数据格式:缺少role字段时默认创建StudentReader。
*/
void DataManager::initUser()
{
// 处理用户自身属性users.txt
QFile file(userFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
}
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine().trimmed();
if (line.isEmpty())
continue;
// 使用竖线作为分隔符,避免字段内容包含空格时错位
QStringList fields = line.split("|");
if (fields.size() < 6)
{
continue;
}
QString id = fields[0];
int type = fields[1].toInt();
int role = 1; // 默认角色为学生读者(兼容旧数据)
QString name;
QString password;
QString phone;
QString email;
int creditScore = 100; // 默认信用分100
int prevCreditScore = 100; // 默认之前的信用分等于当前信用分
QDateTime banUntil;
bool depositPaid = false; // 押金缴纳状态(仅校外读者)
// 新格式:ID|type|role|name|password|phone|email|creditScore|prevCreditScore|banUntil|depositPaid
// 旧格式:ID|type|name|password|phone|email|creditScore|prevCreditScore|banUntil
// 通过判断fields[2]是否为数字来区分新旧格式
if (fields.size() >= 10)
{
// 新格式,包含role字段
role = fields[2].toInt();
name = fields[3];
password = fields[4];
phone = fields[5];
email = fields[6];
if (!fields[7].isEmpty())
{
creditScore = fields[7].toInt();
}
if (!fields[8].isEmpty())
{
prevCreditScore = fields[8].toInt();
}
if (!fields[9].isEmpty())
{
banUntil = QDateTime::fromString(fields[9], "yyyy-MM-dd HH:mm:ss");
}
// (读取押金状态):第11个字段为depositPaid(兼容旧数据默认false)
if (fields.size() >= 11 && !fields[10].isEmpty())
{
depositPaid = (fields[10].toInt() == 1);
}
}
else
{
// 旧格式,不含role字段
name = fields[2];
password = fields[3];
phone = fields[4];
email = fields[5];
if (fields.size() >= 7 && !fields[6].isEmpty())
{
creditScore = fields[6].toInt();
}
if (fields.size() >= 8 && !fields[7].isEmpty())
{
prevCreditScore = fields[7].toInt();
}
if (fields.size() >= 9 && !fields[8].isEmpty())
{
banUntil = QDateTime::fromString(fields[8], "yyyy-MM-dd HH:mm:ss");
}
}
::User *user = nullptr;
if (type == 1)
{
user = new ::Admin(id, name, password, phone, email);
}
else
{
// 根据role创建对应的读者子类
if (role == 2)
{
user = new ::TeacherReader(id, name, password, phone, email);
}
else if (role == 3)
{
user = new ::ExternalReader(id, name, password, phone, email);
}
else
{
// role == 1 或旧数据默认创建学生读者
user = new ::StudentReader(id, name, password, phone, email);
}
if (user)
{
::Reader *reader = dynamic_cast<::Reader *>(user);
if (reader)
{
reader->setCreditScore(creditScore);
reader->setPrevCreditScore(prevCreditScore);
reader->setBanUntil(banUntil);
}
// (设置押金状态):校外读者从文件读取押金缴纳状态
::ExternalReader *extReader = dynamic_cast<::ExternalReader *>(user);
if (extReader)
{
extReader->setDepositPaid(depositPaid);
}
}
}
users.push_back(user);
}
file.close();
}
/**
* @brief 获取信用分所在的区间
* @param score 信用分
* @return 区间编号(0-5)
*
* 信用分区间划分:
* - 90-100分:返回0
* - 80-89分:返回1
* - 70-79分:返回2
* - 60-69分:返回3
* - 50-59分:返回4
* - 0-49分:返回5
*/
int getCreditTier(int score)
{
if (score < 50)
return 5;
if (score < 60)
return 4;
if (score < 70)
return 3;
if (score < 80)
return 2;
if (score < 90)
return 1;
return 0;
}
/**
* @brief 重新计算所有读者信用分
*
* 执行两步操作:
* 1. 处理逾期扣分:遍历所有借阅记录,对未归还且逾期的记录扣除信用分,
* 并发送扣分消息给读者。限制期间不扣分,但继续记录已扣分数。
* 2. 检查信用分变化:检查读者信用分是否从高区间跌落到低区间,
* 如果是则触发限制,并发送限制消息给读者。
*
* 信用分限制规则:
* - 90-100分:无限制
* - 80-89分:限制1天
* - 70-79分:限制3天
* - 60-69分:限制1周
* - 50-59分:限制2周
* - 0-49分:限制1个月
*/
void DataManager::recalculateCreditScores()
{
QDateTime now = QDateTime::currentDateTime();
// 第一步:处理逾期扣分
for (auto &record : borrowRecords)
{
QString readerId = record.getReaderID();
int overdueDays = record.calculateOverdueDays();
int deductedScore = record.getDeductedScore();
int needDeduct = overdueDays - deductedScore;
::User *user = findUserById(readerId);
if (!user || user->getType() != 2)
continue;
::Reader *reader = dynamic_cast<::Reader *>(user);
if (!reader)
continue;
// 从读者策略获取每日罚款金额
double finePerDay = reader->getFinePerDay();
record.setFineAmount(record.calculateFine(finePerDay));
bool isBanned = reader->isBanned();
// 先更新 deductedScore(不管是否在限制期间,都要记录已扣分数)
if (overdueDays > deductedScore)
{
record.setDeductedScore(overdueDays);
}
// 只有"不在限制期间、逾期、需要扣分"的记录才扣分
if (!isBanned && overdueDays > 0 && needDeduct > 0)
{
// 根据读者策略获取每日信用分扣减
int deductPerDay = reader->getCreditDeductPerDay();
int actualDeduct = needDeduct * deductPerDay;
int currentScore = reader->getCreditScore();
int newScore = qMax(currentScore - actualDeduct, 0);
reader->setCreditScore(newScore);
// 发送扣分消息给读者
QString bookTitle = "未知";
Book *book = findBookByISBN(record.getISBN());
if (book)
{
bookTitle = book->getTitle();
}
QString msgContent = QString("您借阅的图书《%1》(ISBN:%2)已逾期%3天,扣除%4分信用分,当前信用分:%5")
.arg(bookTitle)
.arg(record.getISBN())
.arg(overdueDays)
.arg(actualDeduct)
.arg(newScore);
Message msg(readerId, reader->getName(), msgContent);
reader->addMessage(msg);
}
}
// 第二步:检查信用分变化,触发限制
for (auto user : users)
{
if (user->getType() != 2)
continue;
::Reader *reader = dynamic_cast<::Reader *>(user);
if (!reader)
continue;
int creditScore = reader->getCreditScore();
int prevCreditScore = reader->getPrevCreditScore();
bool isBanned = reader->isBanned();
// 清除过期的限制状态
if (!isBanned && reader->getBanUntil().isValid())
{
reader->setBanUntil(QDateTime());
}
int currentTier = getCreditTier(creditScore);
int prevTier = getCreditTier(prevCreditScore);
// 只有从更高区间下跌到更低区间时才触发限制
if (currentTier > prevTier)
{
QDateTime banUntil;
if (creditScore < 50)
{
banUntil = now.addDays(30);
}
else if (creditScore < 60)
{
banUntil = now.addDays(14);
}
else if (creditScore < 70)
{
banUntil = now.addDays(7);
}
else if (creditScore < 80)
{
banUntil = now.addDays(3);
}
else if (creditScore < 90)
{
banUntil = now.addDays(1);
}
if (banUntil.isValid())
{
reader->setBanUntil(banUntil);
// 发送限制消息给读者
QString limitDays;
if (creditScore < 50)
{
limitDays = "1个月";
}
else if (creditScore < 60)
{
limitDays = "2周";
}
else if (creditScore < 70)
{
limitDays = "1周";
}
else if (creditScore < 80)
{
limitDays = "3天";
}
else if (creditScore < 90)
{
limitDays = "1天";
}
QString msgContent = QString("由于您的信用分降至%1分,已被限制预约、借书和续借%2。限制期间您仍可正常还书。")
.arg(creditScore)
.arg(limitDays);
Message msg(reader->getID(), reader->getName(), msgContent);
reader->addMessage(msg);
}
}
// 不管怎样,更新 prevCreditScore 为当前 creditScore
reader->setPrevCreditScore(creditScore);
}
writeUser();
writeBorrowRecord();
writeMessage(); // 写入消息,包含扣分通知
}
/**
* @brief 写入用户数据到文件
*
* 将所有用户信息写入users.txt文件,包括ID、类型、角色、姓名、密码、电话、邮箱、
* 信用分、之前信用分和限制终止日期。
* 新格式:ID|type|role|name|password|phone|email|creditScore|prevCreditScore|banUntil
* 管理员角色字段固定为0。
*/
void DataManager::writeUser()
{
QFile file(userFilePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
return;
}
QTextStream out(&file);
for (auto user : users)
{
int creditScore = 100;
int prevCreditScore = 100;
int role = 0; // 管理员角色为0
QString banUntilStr = "";
int depositPaid = 0; // 押金缴纳状态(0=未缴纳,1=已缴纳,仅校外读者)
if (user->getType() == 2) // 读者
{
::Reader *reader = dynamic_cast<::Reader *>(user);
if (reader)
{
creditScore = reader->getCreditScore();
prevCreditScore = reader->getPrevCreditScore();
role = static_cast<int>(reader->getRole());
if (reader->getBanUntil().isValid())
{
banUntilStr = reader->getBanUntil().toString("yyyy-MM-dd HH:mm:ss");
}
// (校外读者押金状态):写入depositPaid字段
::ExternalReader *extReader = dynamic_cast<::ExternalReader *>(reader);
if (extReader && extReader->isDepositPaid())
{
depositPaid = 1;
}
}
}
QString line = QString("%1|%2|%3|%4|%5|%6|%7|%8|%9|%10|%11")
.arg(user->getID())
.arg(user->getType())
.arg(role)
.arg(user->getName())
.arg(user->getPassword())
.arg(user->getPhone())
.arg(user->getEmail())
.arg(creditScore)
.arg(prevCreditScore)
.arg(banUntilStr)
.arg(depositPaid);
out << line << "\n";
}
file.close();
}
/**
* @brief 初始化读取图书数据
*
* 从books.txt文件中读取图书信息,包括ISBN、书名、作者、分类、
* 库存、入库时间、借阅次数、当前借出数量和预约人数。
*/
void DataManager::initBook()
{
QFile file(bookFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
}
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine().trimmed();
if (line.isEmpty())
continue;
QStringList fields = line.split("|");
if (fields.size() != 10)
continue;
QString isbn = fields[0];
QString title = fields[1];
QString author = fields[2];
QString category = fields[3];
int stock = fields[4].toInt();
QDateTime inStockTime = QDateTime::fromString(fields[5], "yyyy-MM-dd HH:mm:ss");
int borrowCount = fields[6].toInt();
int overdueReturnCount = fields[7].toInt();
int currentBorrowed = fields[8].toInt();
int reservationCount = fields[9].toInt();
books.push_back(Book(isbn, title, author, category, stock, inStockTime, borrowCount, currentBorrowed, reservationCount, overdueReturnCount));
}
file.close();
}
/**
* @brief 写入图书数据到文件
*
* 将所有图书信息写入books.txt文件,包括ISBN、书名、作者、分类、
* 库存、入库时间、借阅次数、当前借出数量和预约人数。
*/
void DataManager::writeBook()
{
QFile file(bookFilePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
return;
}
QTextStream out(&file);
for (auto &book : books)
{
QString line = book.getISBN() + "|" + book.getTitle() + "|" + book.getAuthor() + "|" + book.getCategory() + "|" + QString::number(book.getStock()) + "|" + book.getInStockTime().toString("yyyy-MM-dd HH:mm:ss") + "|" + QString::number(book.getBorrowCount()) + "|" + QString::number(book.getOverdueReturnCount()) + "|" + QString::number(book.getCurrentBorrowed()) + "|" + QString::number(book.getReservationCount());
out << line << "\n";
}
file.close();
}
/**
* @brief 根据ISBN查找图书(精确匹配)
* @param isbn 图书ISBN编号
* @return 匹配的图书指针(未找到返回nullptr)
*/
Book *DataManager::findBookByISBN(const QString &isbn)
{
for (auto &book : books)
{
if (book.getISBN() == isbn)
{
return &book;
}
}
return nullptr;
}
/**
* @brief 根据书名查找图书(模糊匹配)
* @param title 书名关键字
* @return 匹配的图书列表
*/
std::vector<Book> DataManager::findBooksByTitle(const QString &title)
{
std::vector<Book> results;
for (auto &book : books)
{
if (book.getTitle().contains(title, Qt::CaseInsensitive))
{
results.push_back(book);
}
}
return results;
}
/**
* @brief 根据作者查找图书(模糊匹配)
* @param author 作者关键字
* @return 匹配的图书列表
*/
std::vector<Book> DataManager::findBooksByAuthor(const QString &author)
{
std::vector<Book> results;
for (auto &book : books)
{
if (book.getAuthor().contains(author, Qt::CaseInsensitive))
{
results.push_back(book);
}
}
return results;
}
/**
* @brief 根据分类查找图书(模糊匹配)
* @param category 分类关键字
* @return 匹配的图书列表
*/
std::vector<Book> DataManager::findBooksByCategory(const QString &category)
{
std::vector<Book> results;
for (auto &book : books)
{
if (book.getCategory().contains(category, Qt::CaseInsensitive))
{
results.push_back(book);
}
}
return results;
}
/**
* @brief 多条件搜索图书
* @param isbn ISBN关键字(模糊匹配)
* @param title 书名关键字(模糊匹配)
* @param author 作者关键字(模糊匹配)
* @param category 分类关键字(模糊匹配)
* @return 匹配的图书指针列表
*
* 支持按ISBN、书名、作者、分类的组合条件搜索,
* 所有条件都是模糊匹配,只有同时满足所有条件的图书才会被返回。
*/
std::vector<const Book *> DataManager::searchBooks(const QString &isbn, const QString &title,
const QString &author, const QString &category)
{
std::vector<const Book *> results;
for (const auto &book : books)
{
bool match = true;
if (!isbn.isEmpty() && !book.getISBN().contains(isbn, Qt::CaseInsensitive))
{
match = false;
}
if (!title.isEmpty() && !book.getTitle().contains(title, Qt::CaseInsensitive))
{
match = false;
}
if (!author.isEmpty() && !book.getAuthor().contains(author, Qt::CaseInsensitive))
{
match = false;
}
if (!category.isEmpty() && !book.getCategory().contains(category, Qt::CaseInsensitive))
{
match = false;
}
if (match)
{
results.push_back(&book); // 返回指针,指向原对象
}
}
return results;
}
/**
* @brief 添加图书并保存到文件
* @param book 要添加的图书
* @return 返回值:0=成功新增,1=库存已增加,-1=ISBN冲突(其他信息不匹配)
*
* 如果ISBN已存在且其他信息(书名、作者、分类)也相同,则增加库存;
* 如果ISBN已存在但其他信息不匹配,则返回错误;
* 如果ISBN不存在,则新增图书。
*/
int DataManager::addBook(const Book &book)
{
// 先按ISBN精确查找
Book *existingBook = findBookByISBN(book.getISBN());
if (existingBook != nullptr)
{
// ISBN已存在,检查其他三个条件是否也相同
if (existingBook->getTitle() == book.getTitle() &&
existingBook->getAuthor() == book.getAuthor() &&
existingBook->getCategory() == book.getCategory())
{
// 四个条件都相同,更新库存量和入库时间
int oldStock = existingBook->getStock();
existingBook->setStock(existingBook->getStock() + book.getStock());
existingBook->setInStockTime(QDateTime::currentDateTime());
writeBook();
// 如果库存增加了,通知预约成功的读者
if (book.getStock() > 0)
{
notifyReservations(book.getISBN());
}
return 1; // 库存已增加
}
else
{
// ISBN相同但其他条件不同,冲突
return -1; // ISBN冲突
}
}
// ISBN不存在,直接添加新书
books.push_back(book);
writeBook();
return 0; // 成功新增
}
/**
* @brief 根据ISBN删除图书并保存到文件
* @param isbn 图书ISBN编号
* @param decreaseStock 要减少的库存数量
* @return 返回值:0=成功删除记录,1=库存已减少,-1=ISBN不存在,-2=存在预约或借出无法删除
*
* 如果decreaseStock >= 当前库存,则删除整条记录;
* 如果decreaseStock < 当前库存,则减少库存;
* 如果存在预约或借出,则无法删除。
*/
int DataManager::deleteBook(const QString &isbn, int decreaseStock)
{
for (auto it = books.begin(); it != books.end(); ++it)
{
if (it->getISBN() == isbn)
{
// 检查是否有预约或借出
if (it->getReservationCount() > 0 || it->getCurrentBorrowed() > 0)
{
return -2; // 存在预约或借出,无法删除
}
int currentStock = it->getStock();
if (decreaseStock >= currentStock)
{
// 删除整条记录
books.erase(it);
writeBook();
return 0; // 成功删除记录
}
else
{
// 减少库存
it->setStock(currentStock - decreaseStock);
writeBook();
return 1; // 库存已减少
}
}
}
return -1; // ISBN不存在