<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="handleReturn(row)"
                      :disabled="row.returnTime"
                  >
                    归还
                  </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
    };
  },
  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('查询失败，请稍后重试！');
      }
    },

    resetQuery() {
      this.queryForm.name = '';
      this.handleQuery();
    },

    async handleBorrow(row) {
      try {
        const response = await axios.post(
            `http://localhost:8080/borrow/borrow/${row.id}`,
            null,
            {
              params: { userId: this.userId },
            }
        );
        if (response.data.code === 1) {
          this.$message.success('借阅成功！');
          this.handleQuery();
        } else {
          this.$message.error(response.data.msg || '借阅失败！');
        }
      } catch (error) {
        this.$message.error('借阅失败，请稍后重试！');
      }
    },

    async handleReturn(row) {
      try {
        const response = await axios.post(
            `http://localhost:8080/borrow/return/${row.bookId}`,
            null,
            {
              params: { userId: this.userId },
            }
        );
        if (response.data.code === 1) {
          this.$message.success('归还成功！');
          this.handleMyBorrowed(); // 刷新借阅记录
          this.handleQuery(); // 刷新书籍列表
        } else {
          this.$message.error(response.data.msg || '归还失败！');
        }
      } catch (error) {
        this.$message.error('归还失败，请稍后重试！');
      }
    },

    async handleMyBorrowed() {
      try {
        const response = await axios.get('http://localhost:8080/borrow/history', {
          params: { userId: this.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('获取借阅记录失败，请稍后重试！');
      }
    },

    formatDateTime(value) {
      if (!value) return '无数据';
      return new Date(value).toLocaleString('zh-CN', { hour12: false });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.handleQuery();
    },

    handlePageChange(val) {
      this.currentPage = val;
      this.handleQuery();
    },
  },
  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>
显示归还失败请重试