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

    <!-- 操作按钮 -->
    <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 || row.status === 2"
            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 } 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 params: Course = {
      courseID: course.courseID!,
      status: status
    };
    const res = await courseApi.updateCourseStatus(params);
    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 {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .form-item {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .form-label {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }

    .form-input,
    .form-select {
      height: 32px;
      padding: 0 12px;
      font-size: 14px;
      color: #606266;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fff;
      transition: border-color 0.2s;
      outline: none;
      min-width: 200px;

      &:hover {
        border-color: #c0c4cc;
      }

      &:focus {
        border-color: #409eff;
      }

      &::placeholder {
        color: #c0c4cc;
      }
    }

    .form-select {
      cursor: pointer;
      appearance: none;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1024 1024'%3E%3Cpath fill='%23606266' d='M831.872 340.864 512 652.672 192.128 340.864a30.592 30.592 0 0 0-42.752 0 29.12 29.12 0 0 0 0 41.6L489.664 714.24a32 32 0 0 0 44.672 0l340.288-331.712a29.12 29.12 0 0 0 0-41.728 30.592 30.592 0 0 0-42.752 0z'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 8px center;
      background-size: 14px;
      padding-right: 30px;
    }
  }
}

.toolbar {
  margin-bottom: 20px;
}

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