<template>
  <div class="course-list">
    <!-- 搜索栏 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="课程名称">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
          <el-option label="未上线" :value="0" />
          <el-option label="已上线" :value="1" />
          <el-option label="已下架" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增课程
      </el-button>
    </div>

    <!-- 课程表格 -->
    <el-table
      v-loading="loading"
      :data="courseList"
      border
      stripe
    >
      <el-table-column prop="name" label="课程名称" min-width="200" />
      <el-table-column label="封面" width="100">
        <template #default="{ row }">
          <el-image
            v-if="row.coverImage"
            :src="FILE_DOWNLOAD_URL + row.coverImage"
            style="width: 60px; height: 60px"
            fit="cover"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="teacher" label="授课老师" width="120" />
      <el-table-column prop="duration" label="时长(分钟)" width="120" />
      <el-table-column prop="learnCount" label="学习人数" width="100" />
      <el-table-column prop="viewCount" label="浏览次数" width="100" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === 0" type="info">未上线</el-tag>
          <el-tag v-else-if="row.status === 1" type="success">已上线</el-tag>
          <el-tag v-else-if="row.status === 2" type="danger">已下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="80" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="success"
            size="small"
            link
            @click="handleUpdateStatus(row, 1)"
          >
            上线
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="warning"
            size="small"
            link
            @click="handleUpdateStatus(row, 2)"
          >
            下架
          </el-button>
          <el-button type="danger" size="small" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="total > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination"
      @size-change="handlePageChange"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';
import { courseApi } from '@/apis/study';
import { FILE_DOWNLOAD_URL } from '@/config';
import type { Course, PageParam } from '@/types';

defineOptions({
  name: 'CourseList'
});

const emit = defineEmits<{
  add: [];
  edit: [course: Course];
}>();

const loading = ref(false);
const courseList = ref<Course[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const searchForm = reactive({
  name: '',
  status: undefined as number | undefined
});

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

// 加载课程列表
async function loadCourses() {
  loading.value = true;
  try {
    const res = await courseApi.getCoursePage({page: currentPage.value, size: pageSize.value}, searchForm);
    if (res.success && res.pageDomain) {
      courseList.value = res.pageDomain.dataList || [];
      total.value = res.pageDomain.pageParam.totalElements || 0;
    }
  } catch (error) {
    console.error('加载课程列表失败:', error);
    ElMessage.error('加载课程列表失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  currentPage.value = 1;
  loadCourses();
}

// 重置
function handleReset() {
  searchForm.name = '';
  searchForm.status = undefined;
  currentPage.value = 1;
  loadCourses();
}

// 新增
function handleAdd() {
  emit('add');
}

// 编辑
function handleEdit(course: Course) {
  emit('edit', course);
}

// 更新状态
async function handleUpdateStatus(course: Course, status: number) {
  const statusText = status === 1 ? '上线' : '下架';
  try {
    await ElMessageBox.confirm(`确定要${statusText}该课程吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await courseApi.updateCourseStatus(course.courseID!, status);
    if (res.success) {
      ElMessage.success(`${statusText}成功`);
      loadCourses();
    } else {
      ElMessage.error(`${statusText}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新状态失败:', error);
      ElMessage.error(`${statusText}失败`);
    }
  }
}

// 删除
async function handleDelete(course: Course) {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await courseApi.deleteCourse(course.courseID!);
    if (res.success) {
      ElMessage.success('删除成功');
      loadCourses();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

// 分页变化
function handlePageChange() {
  loadCourses();
}

defineExpose({
  loadCourses
});
</script>

<style lang="scss" scoped>
.course-list {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

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