<template>
  <div class="page-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>网页管理</span>
          <div>
            <el-select v-model="siteId" placeholder="选择站点" filterable style="width: 220px; margin-right: 12px" @change="fetchList">
              <el-option v-for="s in sites" :key="s.id" :label="s.name" :value="s.id" />
            </el-select>
            <el-button type="primary" :disabled="!siteId" @click="openDialog()">新增网页</el-button>
          </div>
        </div>
      </template>

      <el-table :data="list" v-loading="loading" stripe>
        <el-table-column label="ID" width="240">
          <template #default="{ row }">{{ row.id }}</template>
        </el-table-column>
        <el-table-column prop="slug" label="Slug" width="120" />
        <el-table-column prop="title" label="标题" width="160" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.type === 'homepage'" type="success" size="small">首页</el-tag>
            <el-tag v-else size="small">页面</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180" />
        <el-table-column label="操作" fixed="right" width="160">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openDialog(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="editId ? '编辑网页' : '新增网页'" width="560px" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="Slug" prop="slug">
          <el-input v-model="form.slug" placeholder="如 about、index" :disabled="!!editId" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="页面标题" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="类型">
            <el-option label="普通页面" value="page" />
            <el-option label="首页" value="homepage" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="8" placeholder="HTML 或 JSON" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSites } from '../../api/admin'
import { getPages, createPage, updatePage, deletePage } from '../../api/admin'

const siteId = ref('')
const sites = ref([])
const list = ref([])
const loading = ref(false)

const fetchSites = async () => {
  try {
    const res = await getSites()
    sites.value = res.list || []
    if (sites.value.length && !siteId.value) {
      const q = new URLSearchParams(window.location.search)
      siteId.value = q.get('site_id') || sites.value[0].id
    }
  } catch (e) {
    ElMessage.error(e.message)
  }
}

const fetchList = async () => {
  if (!siteId.value) {
    list.value = []
    return
  }
  loading.value = true
  try {
    const res = await getPages({ site_id: siteId.value })
    list.value = res.list || []
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    loading.value = false
  }
}

watch(siteId, fetchList)

const dialogVisible = ref(false)
const editId = ref('')
const submitting = ref(false)
const formRef = ref(null)
const form = reactive({ site_id: '', slug: '', title: '', type: 'page', content: '' })
const rules = {
  slug: [{ required: true, message: '请输入 slug', trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
}

const openDialog = (row) => {
  form.site_id = siteId.value
  editId.value = row ? row.id : ''
  form.slug = row ? row.slug : ''
  form.title = row ? row.title : ''
  form.type = row ? row.type || 'page' : 'page'
  form.content = row ? row.content || '' : ''
  dialogVisible.value = true
}

const resetForm = () => {
  form.slug = ''
  form.title = ''
  form.type = 'page'
  form.content = ''
  editId.value = ''
}

const submitForm = async () => {
  await formRef.value?.validate()
  submitting.value = true
  try {
    if (editId.value) {
      await updatePage(editId.value, { slug: form.slug, title: form.title, type: form.type, content: form.content })
      ElMessage.success('更新成功')
    } else {
      await createPage({ ...form, site_id: siteId.value })
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定删除该网页？', '提示', { type: 'warning' })
  try {
    await deletePage(row.id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  }
}

onMounted(() => {
  fetchSites().then(() => fetchList())
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
