|
|
package com.lostfound.dao;
|
|
|
|
|
|
import com.lostfound.model.Item;
|
|
|
import com.lostfound.model.User;
|
|
|
|
|
|
import java.util.*;
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
public class InMemoryDAO {
|
|
|
private static final Map<String, User> users = new ConcurrentHashMap<>();
|
|
|
private static final Map<String, Item> items = new ConcurrentHashMap<>();
|
|
|
private static final AtomicInteger itemIdGen = new AtomicInteger(1);
|
|
|
|
|
|
static {
|
|
|
// 预置一个管理员账号:admin / 123456
|
|
|
users.put("admin", new User("admin", "管理员", "123456", "admin"));
|
|
|
}
|
|
|
|
|
|
public static void addUser(User user) {
|
|
|
users.put(user.getId(), user);
|
|
|
}
|
|
|
|
|
|
public static User getUser(String id) {
|
|
|
return users.get(id);
|
|
|
}
|
|
|
|
|
|
public static void addItem(Item item) {
|
|
|
item.setId("I" + itemIdGen.getAndIncrement());
|
|
|
items.put(item.getId(), item);
|
|
|
}
|
|
|
|
|
|
public static Item getItem(String id) {
|
|
|
return items.get(id);
|
|
|
}
|
|
|
|
|
|
public static List<Item> getAllItems() {
|
|
|
return new ArrayList<>(items.values());
|
|
|
}
|
|
|
|
|
|
public static List<Item> searchItems(String keyword, String category, String location) {
|
|
|
return items.values().stream()
|
|
|
.filter(item -> (keyword == null || keyword.isEmpty() ||
|
|
|
item.getDescription().toLowerCase().contains(keyword.toLowerCase()) ||
|
|
|
item.getCategory().toLowerCase().contains(keyword.toLowerCase())))
|
|
|
.filter(item -> category == null || category.isEmpty() || item.getCategory().equals(category))
|
|
|
.filter(item -> location == null || location.isEmpty() || item.getLocation().equals(location))
|
|
|
.collect(Collectors.toList());
|
|
|
}
|
|
|
|
|
|
public static void markAsMatched(String itemId) {
|
|
|
Item item = items.get(itemId);
|
|
|
if (item != null) {
|
|
|
item.setMatched(true);
|
|
|
// 给发布者加积分
|
|
|
User owner = users.get(item.getUserId());
|
|
|
if (owner != null) {
|
|
|
owner.setPoints(owner.getPoints() + 10);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
} |