<template>
  <div class="admin-cms-page">
    <section class="admin-page-hero">
      <div><span class="admin-eyebrow">SITE SECTIONS</span><h2>页面模块</h2><p>控制每个页面每块内容的标题、副标题、JSON 内容、排序和启用状态。</p></div>
      <button class="primary-button admin-primary-action" type="button" @click="openForm()">新增模块</button>
    </section>
    <AdminTablePage eyebrow="CMS" title="页面模块列表" description="模块内容以 JSON 承载，后续可接入可视化编辑器。" :columns="columns" :rows="rows" :loading="loading" :status-options="statusOptions" @refresh="load" @edit="openForm" @primary="openForm()" />
    <section class="admin-edit-panel">
      <div><span class="admin-eyebrow">EDITOR</span><h3>{{ form.id ? '编辑模块' : '新增模块' }}</h3></div>
      <form @submit.prevent="save">
        <label><span>页面编码</span><input v-model="form.page_code" class="form-input" /></label>
        <label><span>模块标识</span><input v-model="form.section_key" class="form-input" /></label>
        <label><span>标题</span><input v-model="form.title" class="form-input" /></label>
        <label><span>副标题</span><input v-model="form.subtitle" class="form-input" /></label>
        <label><span>排序</span><input v-model.number="form.sort" class="form-input" type="number" /></label>
        <label><span>状态</span><select v-model.number="form.status" class="form-input"><option :value="1">启用</option><option :value="0">禁用</option></select></label>
        <label class="full"><span>内容 JSON</span><textarea v-model="contentJson" class="form-input" rows="6"></textarea></label>
        <button class="primary-button" type="submit">保存模块</button>
      </form>
    </section>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import AdminTablePage from './AdminTablePage.vue'
import { getAdminSiteSections, saveAdminSiteSection } from '@/api/request/site'
const columns = [{ key: 'page_code', label: '页面' }, { key: 'section_key', label: '模块标识', type: 'tag' }, { key: 'title', label: '标题' }, { key: 'subtitle', label: '副标题' }, { key: 'status', label: '状态', type: 'tag', map: { 1: '启用', 0: '禁用' } }, { key: 'sort', label: '排序' }]
const statusOptions = [{ label: '启用', value: '1' }, { label: '禁用', value: '0' }]
const rows = ref([])
const loading = ref(false)
const contentJson = ref('{\n  "layout": "editorial"\n}')
const form = reactive({ id: 0, page_code: 'home', section_key: '', title: '', subtitle: '', content: {}, status: 1, sort: 0 })
const openForm = (row = {}) => { Object.assign(form, { id: 0, page_code: 'home', section_key: '', title: '', subtitle: '', content: {}, status: 1, sort: 0 }, row); contentJson.value = JSON.stringify(form.content || {}, null, 2) }
const load = async () => { loading.value = true; rows.value = await getAdminSiteSections().catch(() => []); loading.value = false }
const save = async () => { form.content = JSON.parse(contentJson.value || '{}'); const saved = await saveAdminSiteSection({ ...form }); openForm(saved); await load() }
onMounted(load)
</script>
