2、ui
LibrarayPresentation
package org.app
package ui
import org.app.models.UserModel
import org.app.service.{BookService, UserService}
import scala.io.StdIn
import scala.io.StdIn.readLine
class LibrarayPresentation {
private val BookService = new BookService()
private val UserService = new UserService()
// 显示游客的菜单
def showVisitorMenu(): Unit = {
var running = true
while (running) {
println("欢迎来到我的图书管理系统, 请选择")
println("1. 查看所有图书")
println("2. 查询图书")
println("3. 登录")
println("4. 离开")
// 获取用户的操作
val choice = StdIn.readLine().trim
choice match {
case "1" =>
// 调用业务逻辑层的方法
val results = BookService.searchBooks("")
if (results.nonEmpty) {
results.foreach(println)
} else {
println("没有找到图书")
}
case "2" =>
// 提示用户输入查询关键字
val query = readLine("请输入查询关键字(书名,作者):").trim
// 根据关键字去查询图书列表,找到满足条件的书
val results = BookService.searchBooks(query)
// 显示出来
if (results.nonEmpty) {
println("=======查询图书的结果:=======")
results.foreach(println)
} else {
println("没有找到图书")
}
case "3" =>
println("请输入用户名:")
val username = StdIn.readLine().trim
println("请输入密码:")
val password = StdIn.readLine().trim
// 调用Service的方法,进行登录
val userOpt = UserService.authenticateUser(username, password)
if (userOpt.isEmpty) {
println("用户名或密码错误")
} else {
println("登录成功")
// 登录成功,显示登录用户的菜单
val user = userOpt.get
user.role match {
case "管理员" => showAdminMenu(user)
case "普通用户" => showUserMenu(user)
}
}
case "4" =>
running = false
println("感谢你的使用,下次再见")
case _ => println("无效的选择")
}
}
}
// 显示管理员的菜单
def showAdminMenu(user: UserModel): Unit = {
var running = true
while (running) {
println(s"欢迎管理员:${user.username},来到我的图书管理系统, 请选择")
println("1. 添加图书")
println("2. 查询图书")
println("4. 退出")
// 获取用户的操作
val choice = StdIn.readLine().trim
choice match {
case "1" => println("添加图书")
case "2" => println("查询图书")
case "4" => running = false
case _ => println("无效的选择")
}
}
}
// 显示登录用户的菜单
def showUserMenu(user: UserModel): Unit = {
var running = true
while (running) {
println(s"欢迎用户:${user.username},来到我的图书管理系统, 请选择")
println("1. 借阅图书")
println("2. 查询图书")
println("4. 退出")
// 获取用户的操作
val choice = StdIn.readLine().trim
choice match {
case "1" =>
// UI: 提示用户输入图书的ID。校验:判断是不是整数
try {
val id = readLine("请输入图书的ID:").toInt
BookService.borrowBook(user.username, id)
} catch {
case e: Exception =>
println(e)
println("输入的图书ID无效")
}
// service:
// dao
// (1) 读入图书借阅记录
// (2) 写入图书借阅记录
// model
// 借阅记录(用户名,书名,id)
case "2" => println("查询图书")
case "4" => running = false
case _ => println("无效的选择")
}
}
}
def showMenu(): Unit = {
showVisitorMenu()
}
}