<template>
  <div class="course-recommend-management">
    <el-card>
      <template #header>
        <div class="card-title">
          <span>团课推荐管理</span>
          <div class="header-actions">
            <el-button size="small" @click="resetSort">恢复默认排序</el-button>
            <el-button type="primary" @click="handleAdd">新增推荐</el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="sortedData"
        style="width: 100%"
        @sort-change="onSortChange"
      >
        <el-table-column prop="id" label="ID" width="100" sortable="custom" />
        <el-table-column prop="courseName" label="团课名称" min-width="160" show-overflow-tooltip sortable="custom">
          <template #default="{ row }">
            {{ courseMap[row.courseId] || `课程 #${row.courseId}` }}
          </template>
        </el-table-column>
        <el-table-column prop="recommendTitle" label="推荐标题" min-width="160" show-overflow-tooltip />
        <el-table-column prop="priority" label="优先级" width="100" sortable="custom">
          <template #default="{ row }">
            <el-tag
              :type="row.priority >= 5 ? 'danger' : row.priority >= 3 ? 'warning' : 'info'"
              effect="dark"
              style="font-weight: 500; font-size: 14px;"
            >
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.isActive ? 'success' : 'danger'"
              effect="dark"
              style="font-weight: 500; font-size: 14px;"
            >
              {{ row.isActive ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recommendReason" label="推荐理由" min-width="180" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="170" sortable="custom">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              v-if="row.isActive"
              type="warning"
              link
              size="small"
              @click="handleToggleActive(row)"
            >
              停用
            </el-button>
            <el-button
              v-else
              type="success"
              link
              size="small"
              @click="handleToggleActive(row)"
            >
              启用
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="modalVisible"
      :title="modalTitle"
      width="550px"
    >
      <el-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="关联团课" prop="courseId">
          <el-select
            v-model="formState.courseId"
            filterable
            placeholder="请选择团课"
            style="width: 100%"
          >
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :value="course.id!"
              :label="course.courseName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推荐标题" prop="recommendTitle">
          <el-input v-model="formState.recommendTitle" placeholder="请输入推荐标题" />
        </el-form-item>
        <el-form-item label="推荐内容">
          <el-input
            v-model="formState.recommendContent"
            type="textarea"
            :rows="3"
            placeholder="请输入推荐内容"
          />
        </el-form-item>
        <el-form-item label="推荐理由">
          <el-input
            v-model="formState.recommendReason"
            type="textarea"
            :rows="2"
            placeholder="请输入推荐理由"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="formState.priority" :min="0" :max="20" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="handleModalOk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { groupCourseRecommendApi, groupCourseApi, type GroupCourseRecommend, type GroupCourse } from '@/api/groupCourse.api'

const loading = ref(false)
const dataSource = ref<GroupCourseRecommend[]>([])
const courseMap = ref<Record<number, string>>({})
const courseList = ref<GroupCourse[]>([])
const sortState = ref<{ prop: string; order: 'ascending' | 'descending' | null }>({ prop: 'priority', order: 'descending' })

const sortedData = computed(() => {
  const list = [...dataSource.value]
  const { prop, order } = sortState.value
  if (!order) return list
  const dir = order === 'ascending' ? 1 : -1
  const getName = (courseId: number) => courseMap.value[courseId] || ''
  switch (prop) {
    case 'id':
      return list.sort((a, b) => ((a.id || 0) - (b.id || 0)) * dir)
    case 'priority':
      return list.sort((a, b) => ((a.priority || 0) - (b.priority || 0)) * dir)
    case 'courseName':
      return list.sort((a, b) => getName(a.courseId).localeCompare(getName(b.courseId), 'zh') * dir)
    case 'createdAt':
      return list.sort((a, b) => (a.createdAt || '').localeCompare(b.createdAt || '') * dir)
    default:
      return list
  }
})

const onSortChange = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
  sortState.value = { prop, order }
}

const tableRef = ref()
const resetSort = () => {
  tableRef.value?.clearSort()
  sortState.value = { prop: 'priority', order: 'descending' }
  // Re-apply default sort arrows on the table
  tableRef.value?.sort('priority', 'descending')
}

const formatTime = (time?: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit',
  })
}

const modalVisible = ref(false)
const modalTitle = ref('')
const formRef = ref()
const formState = reactive<GroupCourseRecommend>({
  courseId: 0,
  recommendTitle: '',
  recommendContent: '',
  recommendReason: '',
  priority: 0,
  isActive: true,
})

const formRules = {
  courseId: [{ required: true, message: '请选择团课', trigger: 'change' }],
  recommendTitle: [
    { required: true, message: '请输入推荐标题', trigger: 'blur' },
    { max: 200, message: '标题长度不能超过200个字符', trigger: 'blur' },
  ],
  priority: [{ required: true, message: '请设置优先级', trigger: 'blur' }],
}

const fetchData = async () => {
  loading.value = true
  try {
    const [recommends, courses] = await Promise.all([
      groupCourseRecommendApi.getAll(),
      groupCourseApi.getAll(),
    ])
    dataSource.value = recommends
    courseList.value = courses
    // Build courseId -> courseName map
    const map: Record<number, string> = {}
    courses.forEach((c) => {
      if (c.id != null) map[c.id] = c.courseName
    })
    courseMap.value = map
  } catch {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  modalTitle.value = '新增推荐'
  Object.assign(formState, {
    id: undefined,
    courseId: 0,
    recommendTitle: '',
    recommendContent: '',
    recommendReason: '',
    priority: 0,
    isActive: true,
  })
  modalVisible.value = true
}

const handleEdit = (row: GroupCourseRecommend) => {
  modalTitle.value = '编辑推荐'
  Object.assign(formState, { ...row })
  modalVisible.value = true
}

const handleToggleActive = async (row: GroupCourseRecommend) => {
  try {
    const actionText = row.isActive ? '停用' : '启用'
    await ElMessageBox.confirm(`确定要${actionText}该推荐吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    if (row.isActive) {
      await groupCourseRecommendApi.disable(row.id!)
    } else {
      await groupCourseRecommendApi.enable(row.id!)
    }
    ElMessage.success(`${actionText}成功`)
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: GroupCourseRecommend) => {
  try {
    await ElMessageBox.confirm('确定要删除该推荐吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await groupCourseRecommendApi.delete(row.id!)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleModalOk = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (formState.id) {
      await groupCourseRecommendApi.update(formState.id, formState)
    } else {
      await groupCourseRecommendApi.create(formState)
    }
    ElMessage.success('操作成功')
    modalVisible.value = false
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => fetchData())
</script>

<style scoped lang="css">
.course-recommend-management .card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-recommend-management .header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
