<template>
  <div>
    <el-container>
      <!-- 侧边栏 -->
      <el-aside style="width: 200px; min-height: 100vh; background-color: rgb(254, 64, 74)">
        <div style="height: 60px; display: flex; align-items: center; justify-content: center;">
          <img src="./photo/GH.jpg" alt="Logo" style="width: 100%; height: auto;">
        </div>
        <el-menu class="custom-menu" style="width: 200px; background-color: #fe8f8f;" popper-append-to-body>
          <el-row>
            <el-col :span="12">
              <el-menu class="custom-menu" style="width: 200px; background-color: #fe8f8f;" popper-append-to-body>
                <el-submenu index="1">
                  <template slot="title">
                    <i class="el-icon-location"></i>
                    <span>导航栏</span>
                  </template>
                  <el-menu-item-group>
                    <el-menu-item index="2">
                      <router-link to="/home#section1">首页</router-link>
                    </el-menu-item>
                    <el-menu-item index="4">
                      <router-link to="/borrow">借阅系统</router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
              </el-menu>
            </el-col>
          </el-row>
        </el-menu>
      </el-aside>

      <el-container>
        <!-- 头部 -->
        <el-header style="font-family: 楷体; text-align: center; font-weight: bold; background-color: rgb(254, 64, 74); color: white; font-size: 50px;">
          红色精神图书管理系统
        </el-header>

        <!-- 主内容 -->
        <el-main>
          <!-- 查询表单 -->
          <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="margin-bottom: 20px;">
            <el-form-item label="书名">
              <el-input v-model="queryForm.name" placeholder="书名"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button type="default" @click="resetQuery" style="margin-left: 10px;">复原</el-button>
            </el-form-item>
          </el-form>

          <!-- 我的借阅 -->
          <el-button type="primary" style="margin-top: 20px;" @click="handleMyBorrowed">我的借阅</el-button>

          <!-- 书籍列表 -->
          <el-table
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%; margin-top: 20px;"
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="name" label="书名" width="180"></el-table-column>
            <el-table-column prop="publisher" label="出版社" width="180"></el-table-column>
            <el-table-column prop="author" label="作者" width="180"></el-table-column>
            <el-table-column label="数量" prop="quantity" width="100"></el-table-column>
            <el-table-column label="存入时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.storeTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button size="mini" @click="handleBorrow(row)" :disabled="row.quantity <= 0">借阅</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              style="text-align: right; margin-top: 20px;"
          >
          </el-pagination>

          <!-- 我的借阅记录 -->
          <el-dialog title="我的借阅记录" :visible.sync="myBorrowedVisible">
            <el-table :data="myBorrowedData" style="width: 100%">
              <el-table-column prop="bookId" label="书籍编号" width="100"></el-table-column>
              <el-table-column prop="borrowTime" label="借阅时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.borrowTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="returnTime" label="归还时间" width="180">
                <template #default="{ row }">
                  {{ row.returnTime ? formatDateTime(row.returnTime) : "未归还" }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button
                      size="mini"
                      @click="handleBorrow(row)"
                      :disabled="row.quantity <= 0 || isAlreadyBorrowed(row.id)"
                  >
                    借阅
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      queryForm: {
        name: '', // 查询条件，对于书名
      },
      tableData: [], // 图书的表格数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示记录数
      selectedRows: [], // 勾选的表格行（保留，以防备用）
      myBorrowedVisible: false, // “我的借阅记录”弹窗状态
      myBorrowedData: [], // 我的借阅记录数据
      userId: 1, // 假设已登录用户的 ID 为 1，这里你可能需要动态获取
    };
  },
  methods: {
    // 查询书籍的方法
    async handleQuery() {
      try {
        const response = await axios.get('http://localhost:8080/books', {
          params: {
            page: this.currentPage, // 当前页码
            pageSize: this.pageSize, // 每页显示条数
            name: this.queryForm.name, // 可以按书名搜索
          },
        });
        if (response.data.code === 1) {
          this.tableData = response.data.data.rows; // 填充表格数据
        } else {
          this.$message.error(response.data.msg || '查询失败');
        }
      } catch (error) {
        this.$message.error('查询失败，请稍后重试！');
        console.error(error);
      }
    },

    // 清空搜索条件、刷新表格
    resetQuery() {
      this.queryForm.name = ''; // 重置书名搜索栏
      this.handleQuery();
    },

    // 借阅书籍
    async handleBorrow(row) {
      if (row.quantity <= 0) {
        this.$message.error('书籍库存不足，无法借阅！');
        return;
      }
      try {
        const response = await axios.post(
            `http://localhost:8080/borrow/borrow/${row.id}`,
            null, // POST body 为空
            {
              params: { userId: this.userId }, // userId 放在查询参数中
            }
        );
        if (response.data.code === 1) {
          this.$message.success('借阅成功！');
          this.handleQuery(); // 借阅成功后刷新书籍列表
        } else {
          this.$message.error(response.data.msg || '借阅失败！');
        }
      } catch (error) {
        this.$message.error('借阅失败，请稍后重试！');
        console.error(error);
      }
    },

    isAlreadyBorrowed(bookId) {
      // 遍历用户的借阅记录，判断书籍是否已借
      return (
          this.myBorrowedData &&
          this.myBorrowedData.some((borrowed) => borrowed.bookId === bookId && !borrowed.returnTime)
      );
    },

    // 归还书籍
    async handleReturn(row) {
      if (!row.bookId) {
        this.$message.error('书籍信息有误，无法归还！');
        return;
      }
      try {
        const response = await axios.post(
            `http://localhost:8080/borrow/return/${row.bookId}`,
            null, // POST body 为空
            {
              params: { userId: this.userId }, // userId 放在查询参数中
            }
        );
        if (response.data.code === 1) {
          this.$message.success('归还成功！');
          this.handleMyBorrowed(); // 归还成功后刷新借阅记录
        } else {
          this.$message.error(response.data.msg || '归还失败！');
        }
      } catch (error) {
        this.$message.error('归还失败，请稍后重试！');
        console.error(error);
      }
    },

    // 查看我的借阅记录
    async handleMyBorrowed() {
      try {
        const response = await axios.get(
            'http://localhost:8080/borrow/history',
            {
              params: { userId: this.userId }, // userId 放在查询参数中
            }
        );
        if (response.data.code === 1) {
          this.myBorrowedData = response.data.data; // 更新弹窗表格的数据
          this.myBorrowedVisible = true; // 打开“我的借阅”弹窗
        } else {
          this.$message.error(response.data.msg || '获取借阅记录失败！');
        }
      } catch (error) {
        this.$message.error('获取借阅记录失败，请稍后重试！');
        console.error(error);
      }
    },

    // 切换页大小
    handleSizeChange(val) {
      this.pageSize = val; // 更新每页显示条数
      this.handleQuery(); // 刷新查询
    },

    // 切换当前页
    handlePageChange(val) {
      this.currentPage = val; // 更新当前页码
      this.handleQuery(); // 刷新查询
    },

    // 时间格式化函数
    formatDateTime(value) {
      if (!value) return '无数据';
      return new Date(value).toLocaleString('zh-CN', { hour12: false }); // 格式化时间
    },
  },
  mounted() {
    this.handleQuery(); // 初始化加载书籍数据
  },
};
</script>

<style scoped>
.custom-menu.el-menu-item span,
.custom-menu.el-menu-item {
  color: white !important;
  font-weight: bold;
}
.el-menu-item:hover {
  background-color: yellow !important;
  color: red !important;
}
.el-table .el-table__body-wrapper {
  margin-top: 10px;
}
.el-table .el-table__row {
  margin: 10px 0;
}
</style>根据下面的接口，帮我完善vue文件，实现归还功能
package com.wwq.bookproject.controller;

import com.wwq.bookproject.pojo.Borrow;
import com.wwq.bookproject.pojo.Result;
import com.wwq.bookproject.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/borrow")
public class BorrowController {

    @Autowired
    private BorrowService borrowService;

    // 借书接口
    @PostMapping("/borrow/{bookId}")
    public Result borrowBook(@RequestParam Long userId, @PathVariable Integer bookId) {
        // 检查是否已借阅但未归还
        List<Borrow> existingBorrows = borrowService.getUnreturnedBorrowsByUserIdAndBookId(userId, bookId);
        if (!existingBorrows.isEmpty()) {
            return Result.error("你已借阅该书籍，无法重复借阅！");
        }
        borrowService.borrowBook(userId, bookId);
        return Result.success("借阅成功");
    }

    // 还书接口
    @PostMapping("/return/{bookId}")
    public Result returnBook(@RequestParam Long userId, @PathVariable Integer bookId) {
        borrowService.returnBook(userId, bookId);
        return Result.success("归还成功");
    }

    // 查询用户的借阅记录
    @GetMapping("/history")
    public Result getBorrowHistory(@RequestParam Long userId) {
        List<Borrow> borrowedBooks = borrowService.findBorrowedBooks(userId);
        return Result.success(borrowedBooks);
    }
}