<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="100" />
        <el-table-column label="前台路径" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">{{ row.route_path || '/' + (row.slug || '') }}</template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="140" />
        <el-table-column label="模式" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.content_mode === 'builder'" type="warning" size="small">积木</el-tag>
            <el-tag v-else type="info" size="small">HTML</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布" width="70">
          <template #default="{ row }">
            <el-tag v-if="row.published === false" type="danger" size="small">否</el-tag>
            <el-tag v-else type="success" size="small">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="90">
          <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="form.content_mode === 'builder' || form.content_mode === 'html' ? '1080px' : '720px'"
      top="4vh"
      @close="resetForm"
    >
      <el-alert
        v-if="form.content_mode === 'builder'"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 16px"
        title="积木模式：左侧编辑、右侧实时预览；⋮⋮ 可拖拽排序；链接可「选择链接」。"
      />
      <el-alert
        v-if="form.content_mode === 'html'"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 16px"
        title="HTML 模式：左侧源码、右侧预览（沙箱内不执行脚本，与线上可能略有差异）。"
      />
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="Slug" prop="slug">
          <el-input v-model="form.slug" placeholder="如 about、index（index 为首页数据，一般不单独走路由）" :disabled="!!editId" />
        </el-form-item>
        <el-form-item label="前台路径">
          <el-input v-model="form.route_path" placeholder="留空则自动为 /{slug}，可填如 /download 或 /about/us" />
        </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="内容模式">
          <el-radio-group v-model="form.content_mode">
            <el-radio-button value="builder">积木（可视化拖拽）</el-radio-button>
            <el-radio-button value="html">HTML 源码</el-radio-button>
          </el-radio-group>
          <el-button type="primary" link style="margin-left: 12px" @click="insertBuilderTemplate">插入积木模板</el-button>
        </el-form-item>
        <el-form-item label="发布到前台">
          <el-switch v-model="form.published" />
        </el-form-item>
        <el-form-item v-if="form.content_mode === 'html'" label="内容" prop="content" class="html-form-item">
          <div class="html-split">
            <div class="html-editor">
              <el-input v-model="form.content" type="textarea" :rows="18" placeholder="直接编写 HTML" />
            </div>
            <div class="html-preview-wrap">
              <div class="html-preview-title">实时预览</div>
              <iframe
                class="html-preview-iframe"
                title="html-preview"
                sandbox=""
                :srcdoc="htmlPreviewSrcdoc"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item v-else label="页面积木" class="builder-form-item page-builder-wrap">
          <PageBuilderEditor v-model="form.content" :site-id="siteId" />
        </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, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSites } from '../../api/admin'
import { getPages, createPage, updatePage, deletePage } from '../../api/admin'
import PageBuilderEditor from '../../components/PageBuilderEditor.vue'

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 builderTemplate = () =>
  JSON.stringify(
    {
      version: 1,
      blocks: [
        {
          id: 'h1',
          type: 'heading',
          props: { text: '页面标题', level: 2 },
          animation: { enter: 'fadeIn', delay_ms: 0, duration_ms: 600 }
        },
        {
          id: 't1',
          type: 'text',
          props: { text: '在此编辑说明文字，可在后台修改 JSON 调整模块与动画。' },
          animation: { enter: 'slideUp', delay_ms: 100, duration_ms: 500 }
        },
        {
          id: 'links',
          type: 'link_list',
          props: {
            items: [
              { label: '回首页', url: '/' },
              { label: '示例外链', url: '#', target: '_blank' }
            ]
          }
        },
        {
          id: 'btn',
          type: 'button',
          props: { text: '主要按钮', url: '#', variant: 'primary' }
        },
        { id: 'sp', type: 'spacer', props: { height: 24 } },
        {
          id: 'sec',
          type: 'section',
          props: { padding: '24px 0', maxWidth: '720px' },
          children: [
            {
              id: 'sub',
              type: 'text',
              props: { html: '<p>区块内可嵌套子模块（<strong>section → children</strong>）。</p>' }
            }
          ]
        }
      ]
    },
    null,
    2
  )

const form = reactive({
  site_id: '',
  slug: '',
  title: '',
  type: 'page',
  content: '',
  content_mode: 'builder',
  route_path: '',
  published: true
})

/** HTML 预览 iframe（沙箱禁用脚本，避免编辑时执行恶意片段） */
const htmlPreviewSrcdoc = computed(() => {
  const raw = form.content || ''
  const body = raw.trim() ? raw : '<p style="color:#999">暂无内容</p>'
  return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{font-family:system-ui,sans-serif;padding:12px;margin:0;background:#fff;color:#222;line-height:1.5;}</style></head><body>${body}</body></html>`
})

function insertBuilderTemplate() {
  form.content_mode = 'builder'
  if (!form.content?.trim()) {
    form.content = builderTemplate()
  } else {
    ElMessageBox.confirm('将用模板覆盖当前内容？', '提示', { type: 'warning' })
      .then(() => {
        form.content = builderTemplate()
      })
      .catch(() => {})
  }
}
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 || '' : ''
  form.content_mode = row?.content_mode || 'builder'
  form.route_path = row?.route_path || ''
  form.published = row?.published !== false
  dialogVisible.value = true
}

const resetForm = () => {
  form.slug = ''
  form.title = ''
  form.type = 'page'
  form.content = ''
  form.content_mode = 'builder'
  form.route_path = ''
  form.published = true
  editId.value = ''
}

const submitForm = async () => {
  await formRef.value?.validate()
  submitting.value = true
  try {
    const payload = {
      slug: form.slug,
      title: form.title,
      type: form.type,
      content: form.content,
      content_mode: form.content_mode,
      route_path: form.route_path || undefined,
      published: form.published
    }
    if (editId.value) {
      await updatePage(editId.value, payload)
      ElMessage.success('更新成功')
    } else {
      await createPage({ ...payload, 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;
}
.builder-form-item :deep(.el-form-item__content) {
  display: block;
  margin-left: 0 !important;
}
.page-builder-wrap {
  max-width: 100%;
}
.html-form-item :deep(.el-form-item__content) {
  display: block;
  margin-left: 0 !important;
}
.html-split {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  width: 100%;
}
.html-editor {
  flex: 1 1 400px;
  min-width: 280px;
}
.html-preview-wrap {
  flex: 0 1 420px;
  width: 100%;
  max-width: 480px;
  display: flex;
  flex-direction: column;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  background: #fafafa;
}
.html-preview-title {
  padding: 8px 12px;
  font-size: 13px;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
}
.html-preview-iframe {
  width: 100%;
  min-height: 360px;
  height: 420px;
  border: none;
  background: #fff;
}
</style>
