<script setup>
import {onMounted, ref} from 'vue';
import {ElButton, ElForm, ElFormItem, ElInput, ElMessage, ElPagination, ElTable, ElTableColumn} from 'element-plus';
import axios from "axios";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import Course from "@views/course-management/Course.vue";

const router = useRouter();
const store = useStore();
const token = store.getters['authentication/token']

const searchTitle = ref('');
const searchAuthor = ref('');
const searchDescription = ref('');
const sortOrder = ref('');

const allCoursesData = ref([]);
const coursesData = ref([]);

const currentPage = ref(1);
const pageSize = ref(10);
const coursesCount = ref(0);
const firstTimeLoad = ref(true);

const selections = ref([]);
const loadCourses = async () => {
  if (firstTimeLoad.value || allCoursesData.value.length < (currentPage.value * pageSize) && (currentPage.value * pageSize) <= coursesCount) {
    let params = {
      token: token,
      start: allCoursesData.value.length,
      end: allCoursesData.value.length + pageSize.value * 2
    }
    try {
      const response = await axios.get('/api/courses', {params})
      const data = response.data
      coursesCount.value = data.courseCount;
      allCoursesData.value.push(...data.courseList);
    } catch (e) {
      console.log(e)
    }
    firstTimeLoad.value = false;
  }
  coursesData.value = allCoursesData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
};

onMounted(() => {
  loadCourses();
})

const handleSearch = () => {
  // 搜索逻辑
};

const handleReset = () => {
  searchTitle.value = '';
  searchAuthor.value = '';
  searchDescription.value = '';
  sortOrder.value = '';
};

const handleEditButton = () => {
  selections.value.forEach(selection => {
    router.push({name: 'Course', params: {id: selection.id}})
  })
};

const handleDeleteButton = () => {
  // 删除逻辑
};

const handleSelectionChange = (newSelections) => {
  selections.value = newSelections
}

const handleEditInTable = (index) => {
  router.push({name: 'Course', query: {mode: 'edit', id: coursesData.value[index].id}})
};

const handleDeleteInTable = async (index) => {
  try {
    await axios.delete(`/api/courses/${coursesData.value[index].id}`, {params: {token: token,}})
    coursesData.value.splice(index, 1);
    allCoursesData.value.splice(index, 1);
    coursesCount.value--;
  } catch (e) {
    ElMessage.error('删除失败')
    console.error(e)
  }
};
</script>

<template>
  <div class="container">
    <div class="search-container">
      <el-form inline>
        <el-form-item label="课程名称">
          <el-input v-model="searchTitle" placeholder="请输入课程名称"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="sortOrder" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchAuthor" placeholder="请输入作者"/>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="searchDescription" placeholder="请输入简介"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-container">
      <el-button type="success" @click="router.push('/courses/edit?mode=create')">新增</el-button>
      <el-button type="warning" @click="handleEditButton">修改</el-button>
      <el-button type="danger" @click="handleDeleteButton">删除</el-button>
      <el-button type="info">导出</el-button>
    </div>

    <el-table :data="coursesData" style="width: 100%;"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="课程名称" align="center"></el-table-column>
      <el-table-column prop="author" label="作者" align="center"></el-table-column>
      <el-table-column prop="description" label="课程简介" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button @click="handleEditInTable(scope.$index)" type="text">修改</el-button>
          <el-button @click="handleDeleteInTable(scope.$index)" type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          @size-change="pageSize = $event;loadCourses()"
          @current-change="currentPage = $event;loadCourses()"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="coursesCount"
          :page-sizes="[10, 20, 50, 100]"
      >
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 20px;
}

.button-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>