package mongo import ( "context" "fwh-toolbox-server/database" "fwh-toolbox-server/domain" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) const ( CollectionName_StatisticsShutdown = "StatisticsShutdown" ) // 从数据库获取Shutdown统计数据 func GetStatisticsShutdown(date string) (*domain.ShutdownStatisticsItem, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() collection := database.GetCollection(CollectionName_StatisticsShutdown) filter := bson.M{} // 条件 if date != "" { filter["date"] = date } var item domain.ShutdownStatisticsItem err := collection.FindOne(ctx, filter).Decode(&item) if err != nil { return nil, err } return &item, nil } // 从数据库获取最新Shutdown统计数据 func GetLatestStatisticsShutdown() (*domain.ShutdownStatisticsItem, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() collection := database.GetCollection(CollectionName_StatisticsShutdown) // 按 date 字段倒序排序(最新日期在最前) opts := options.FindOne().SetSort(bson.D{{Key: "date", Value: -1}}) var result domain.ShutdownStatisticsItem err := collection.FindOne(ctx, bson.D{}, opts).Decode(&result) if err != nil { return nil, err } return &result, nil } // 从数据库获取指定时间范围内的Shutdown统计数据 func GetStatisticsShutdownByDateRange(startDate, endDate string) ([]domain.ShutdownStatisticsItem, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() collection := database.GetCollection(CollectionName_StatisticsShutdown) var results []domain.ShutdownStatisticsItem findOptions := options.Find().SetSort(bson.D{{Key: "date", Value: 1}}) filter := bson.M{ "date": bson.M{ "$gte": startDate, // 起始日期 >= startDate "$lte": endDate, // 结束日期 <= endDate }, } cursor, err := collection.Find(ctx, filter, findOptions) // 按日期升序 if err != nil { return nil, err } defer cursor.Close(ctx) if err = cursor.All(ctx, &results); err != nil { return nil, err } return results, nil } // 插入或更新一条Shutdown统计数据到数据库 func InsertStatisticsShutdown(data domain.ShutdownStatisticsItem) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() collection := database.GetCollection(CollectionName_StatisticsShutdown) // 创建日期字段唯一索引 collection.Indexes().CreateOne(ctx, mongo.IndexModel{ Keys: bson.M{"date": 1}, Options: options.Index().SetUnique(true), }) filter := bson.M{"date": data.Date} update := bson.M{"$set": bson.M{ "status": data.Status, "count": data.Count, "siteMap": data.SiteMap, }} opts := options.Update().SetUpsert(true) _, err := collection.UpdateOne(ctx, filter, update, opts) if err != nil { return err } return nil }