<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  getRecommendList,
  createRecommend,
  updateRecommend,
  deleteRecommend,
  enableRecommend,
  disableRecommend,
  type GroupCourseRecommend,
} from '@/api/groupCourseRecommend'
import { getCourseList, type GroupCourse } from '@/api/groupCourse'
import AppLayout from '@/components/AppLayout.vue'
import { useToast } from '@/composables/useToast'
import { useAuthStore } from '@/stores/auth'

const toast = useToast()
const authStore = useAuthStore()

const recommends = ref<GroupCourseRecommend[]>([])
const courses = ref<GroupCourse[]>([])
const loading = ref(false)
const showModal = ref(false)
const isEdit = ref(false)
const editId = ref<number | null>(null)
const saveLoading = ref(false)

const form = ref({
  courseId: undefined as number | undefined,
  recommendTitle: '',
  recommendContent: '',
  recommendReason: '',
  priority: 0,
  isActive: true,
})

function resetForm() {
  form.value = {
    courseId: undefined,
    recommendTitle: '',
    recommendContent: '',
    recommendReason: '',
    priority: 0,
    isActive: true,
  }
}

async function fetchRecommends() {
  loading.value = true
  try {
    const data = await getRecommendList()
    recommends.value = data
  } catch {
    recommends.value = []
  } finally {
    loading.value = false
  }
}

async function fetchCourses() {
  try {
    const data = await getCourseList()
    courses.value = data
  } catch {
    courses.value = []
  }
}

function handleCreate() {
  isEdit.value = false
  editId.value = null
  resetForm()
  showModal.value = true
}

function handleEdit(item: GroupCourseRecommend) {
  isEdit.value = true
  editId.value = item.id
  form.value = {
    courseId: item.courseId,
    recommendTitle: item.recommendTitle,
    recommendContent: item.recommendContent,
    recommendReason: item.recommendReason,
    priority: item.priority,
    isActive: item.isActive,
  }
  showModal.value = true
}

async function handleSave() {
  if (!form.value.courseId) {
    toast.error('请选择团课')
    return
  }
  saveLoading.value = true
  try {
    if (isEdit.value && editId.value) {
      await updateRecommend(editId.value, form.value)
      toast.success('更新成功')
    } else {
      await createRecommend(form.value)
      toast.success('创建成功')
    }
    showModal.value = false
    fetchRecommends()
  } catch (e: any) {
    toast.error(e?.response?.data?.message || '操作失败')
  } finally {
    saveLoading.value = false
  }
}

async function handleDelete(id: number) {
  if (!confirm('确定要删除该推荐吗？')) return
  try {
    await deleteRecommend(id)
    toast.success('删除成功')
    fetchRecommends()
  } catch (e: any) {
    toast.error(e?.response?.data?.message || '删除失败')
  }
}

async function handleToggle(item: GroupCourseRecommend) {
  try {
    if (item.isActive) {
      await disableRecommend(item.id)
    } else {
      await enableRecommend(item.id)
    }
    fetchRecommends()
  } catch (e: any) {
    toast.error(e?.response?.data?.message || '操作失败')
  }
}

function getCourseName(courseId: number) {
  const c = courses.value.find((x) => x.id === courseId)
  return c?.courseName || `课程ID: ${courseId}`
}

function formatTime(t: string) {
  if (!t) return '--'
  return new Date(t).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchRecommends()
  fetchCourses()
})
</script>

<template>
  <AppLayout>
    <div class="toolbar">
      <button class="btn btn-primary" v-if="authStore.hasPermission('business:groupCourseRecommend:create')" @click="handleCreate">
        <i class="fas fa-plus"></i> 新建推荐
      </button>
    </div>

    <div class="table-wrapper">
      <div class="table-header">
        <h3>推荐团课列表 (共 {{ recommends.length }} 条)</h3>
      </div>

      <!-- skeleton table -->
      <table v-if="loading">
        <thead>
          <tr>
            <th>ID</th><th>团课</th><th>推荐标题</th><th>推荐内容</th>
            <th>推荐理由</th><th>优先级</th><th>状态</th><th>更新时间</th><th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="i in 5" :key="'sk-' + i">
            <td v-for="j in 9" :key="j">
              <span class="sk-td skeleton"></span>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- real table -->
      <table v-else>
        <thead>
          <tr>
            <th>ID</th><th>团课</th><th>推荐标题</th><th>推荐内容</th>
            <th>推荐理由</th><th>优先级</th><th>状态</th><th>更新时间</th><th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in recommends" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ getCourseName(item.courseId) }}</td>
            <td>{{ item.recommendTitle }}</td>
            <td class="text-ellipsis">{{ item.recommendContent }}</td>
            <td>{{ item.recommendReason }}</td>
            <td>{{ item.priority }}</td>
            <td>
              <span
                class="status-badge"
                :class="item.isActive ? 'green' : ''"
                :style="{ cursor: authStore.hasPermission('business:groupCourseRecommend:edit') ? 'pointer' : 'default' }"
                @click="authStore.hasPermission('business:groupCourseRecommend:edit') && handleToggle(item)"
              >{{ item.isActive ? '启用' : '禁用' }}</span>
            </td>
            <td>{{ formatTime(item.updatedAt) }}</td>
            <td class="actions">
              <button class="btn-sm" v-if="authStore.hasPermission('business:groupCourseRecommend:edit')" @click="handleEdit(item)">编辑</button>
              <button class="btn-sm danger" v-if="authStore.hasPermission('business:groupCourseRecommend:delete')" @click="handleDelete(item.id)">删除</button>
            </td>
          </tr>
          <tr v-if="recommends.length === 0">
            <td colspan="9" class="empty">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- modal -->
    <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
      <div class="modal">
        <h3>{{ isEdit ? '编辑推荐' : '新建推荐' }}</h3>
        <div class="form-group">
          <label>选择团课 <span class="required">*</span></label>
          <select v-model.number="form.courseId">
            <option :value="undefined" disabled>请选择团课</option>
            <option v-for="c in courses" :key="c.id" :value="c.id">
              {{ c.courseName }} (ID: {{ c.id }})
            </option>
          </select>
        </div>
        <div class="form-group">
          <label>推荐标题</label>
          <input v-model="form.recommendTitle" placeholder="请输入推荐标题" />
        </div>
        <div class="form-group">
          <label>推荐内容</label>
          <textarea v-model="form.recommendContent" placeholder="请输入推荐内容" rows="3"></textarea>
        </div>
        <div class="form-group">
          <label>推荐理由</label>
          <input v-model="form.recommendReason" placeholder="请输入推荐理由" />
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>优先级</label>
            <input v-model.number="form.priority" type="number" placeholder="数字越大优先级越高" />
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model="form.isActive">
              <option :value="true">启用</option>
              <option :value="false">禁用</option>
            </select>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn btn-outline" @click="showModal = false">取消</button>
          <button class="btn btn-primary" @click="handleSave" :disabled="saveLoading">
            <i v-if="saveLoading" class="fas fa-spinner fa-spin"></i>
            {{ saveLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<style scoped>
.toolbar { margin-bottom: 20px; }

.btn {
  padding: 9px 20px; border-radius: 40px; border: 1px solid #e2e8f0;
  background: white; font-weight: 500; font-size: 13px; color: #1e293b;
  display: inline-flex; align-items: center; gap: 8px; cursor: pointer; transition: 0.15s;
}

.btn-primary {
  background: #4f7cff; border-color: #4f7cff; color: white;
  box-shadow: 0 4px 10px rgba(79,124,255,0.25);
}

.btn-primary:hover:not(:disabled) { background: #3f6ae0; }
.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
.btn-outline:hover { background: #f0f5ff; }

.table-wrapper {
  background: white; border-radius: 20px; border: 1px solid #edf2f9;
  padding: 20px 24px 8px 24px;
}

.table-header {
  display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;
}

.table-header h3 { font-weight: 600; font-size: 16px; color: #0b1a33; }

table { width: 100%; border-collapse: collapse; font-size: 14px; }

th {
  text-align: left; padding: 12px 8px 12px 0;
  font-weight: 600; color: #4e627c; border-bottom: 1px solid #eef2f8;
}

td {
  padding: 14px 8px 14px 0; border-bottom: 1px solid #f1f5fa; color: #1e2f44;
}

tr:last-child td { border-bottom: none; }

td.empty { text-align: center; padding: 40px; color: #8b9ab0; }

.text-ellipsis { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

/* ---- skeleton ---- */
.skeleton {
  background: linear-gradient(90deg, #eef2f8 25%, #e0e7f0 50%, #eef2f8 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 6px;
}

.sk-td { display: block; height: 16px; width: 80%; }

@keyframes shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(6px); }
  to { opacity: 1; transform: translateY(0); }
}

tr { animation: fadeIn 0.35s ease; }

/* ---- badge ---- */
.status-badge {
  padding: 4px 12px; border-radius: 40px; font-size: 12px;
  font-weight: 500; display: inline-block;
  background: #e6f0ff; color: #4f7cff;
}

.status-badge.green { background: #e0f5ec; color: #0b8b5e; }

.actions { white-space: nowrap; }

.btn-sm {
  padding: 5px 12px; border-radius: 20px; border: 1px solid #e2e8f0;
  background: white; font-size: 12px; cursor: pointer; margin-right: 6px; transition: 0.15s;
}

.btn-sm:hover { background: #f0f5ff; }
.btn-sm.danger { color: #ef4444; border-color: #fecaca; }
.btn-sm.danger:hover { background: #fef2f2; }

.modal-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.3);
  display: flex; align-items: center; justify-content: center; z-index: 200;
  animation: fadeIn 0.15s ease;
}

.modal {
  background: white; border-radius: 20px; padding: 28px;
  width: 560px; max-width: 92vw; max-height: 85vh; overflow-y: auto;
  box-shadow: 0 12px 40px rgba(0,0,0,0.12);
  animation: fadeIn 0.2s ease;
}

.modal h3 { font-size: 18px; font-weight: 600; color: #0b1a33; margin-bottom: 20px; }

.form-group { margin-bottom: 14px; }
.form-group label {
  display: block; font-size: 13px; font-weight: 600; color: #1e293b; margin-bottom: 4px;
}
.form-group .required { color: #ef4444; }

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%; padding: 9px 12px; border-radius: 10px;
  border: 1px solid #e2e8f0; font-size: 14px; outline: none;
  transition: 0.15s; background: #f8fafd; font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  border-color: #4f7cff; box-shadow: 0 0 0 3px rgba(79,124,255,0.12);
}

.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }

.modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; }
</style>