<template>
  <div class="homepage-edit">
    <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="fetchData">
              <el-option v-for="s in sites" :key="s.id" :label="s.name" :value="s.id" />
            </el-select>
            <el-button type="primary" :loading="saving" :disabled="!siteId" @click="handleSave">保存</el-button>
            <el-button type="success" :loading="downloading" :disabled="!siteId" @click="handleDownload">下载首页 HTML</el-button>
          </div>
        </div>
      </template>

      <el-form v-if="siteId" ref="formRef" :model="form" label-width="120px" class="homepage-form">
        <el-divider content-position="left">导航与标题</el-divider>
        <el-form-item label="Logo 文案">
          <el-input v-model="form.logo_text" placeholder="宇恒一号" />
        </el-form-item>
        <el-form-item label="主标题">
          <el-input v-model="form.title" placeholder="宇恒一号" />
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="form.subtitle" placeholder="可选，前台大标题区已精简" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="支持换行，会显示在首页" />
        </el-form-item>

        <el-form-item label="导航链接">
          <div
            v-for="(link, i) in form.nav_links"
            :key="i"
            style="display: flex; gap: 8px; margin-bottom: 8px; align-items: center; flex-wrap: wrap"
          >
            <el-input v-model="link.label" placeholder="显示文字" style="width: 120px" />
            <el-input v-model="link.url" placeholder="路径或外链，可点「选择链接」" style="flex: 1; min-width: 160px" />
            <el-button type="primary" link @click="openLinkPicker({ type: 'nav', index: i })">选择链接</el-button>
            <el-link
              v-if="previewReady(link.url)"
              type="primary"
              :href="previewHref(link.url)"
              target="_blank"
              rel="noopener noreferrer"
            >试跳</el-link>
            <el-button link type="danger" @click="form.nav_links.splice(i, 1)">删除</el-button>
          </div>
          <el-button link type="primary" @click="form.nav_links.push({ label: '', url: '#' })">+ 添加链接</el-button>
        </el-form-item>

        <el-divider content-position="left">侧栏下载（Windows / 安卓直链）</el-divider>
        <p class="builder-tip" style="margin: -6px 0 12px">
          填写同域可下载的静态地址（需将安装包放到站点 <code>promotion/downloads/</code> 并部署）。前台为「Windows 版下载」「安卓版下载」直连，不跳转整页。
        </p>
        <el-form-item label="Windows 安装包">
          <el-input v-model="form.download_windows_url" placeholder="/promotion/downloads/yuheng-windows.zip" />
        </el-form-item>
        <el-form-item label="安卓安装包">
          <el-input v-model="form.download_android_url" placeholder="/promotion/downloads/yuheng-android.apk" />
        </el-form-item>

        <el-divider content-position="left">直播（前台 /live）</el-divider>
        <p class="builder-tip" style="margin: -6px 0 12px">
          <strong>本站 WebRTC 直播</strong>仅在左侧菜单「视频直播开播」由已登录管理员推流，前台首页左上角画中画与「直播」页播放。
          <strong>外部直播间</strong>：下方地址用于前台「进入外部直播间」跳转；可留空。
        </p>
        <el-form-item label="直播间标题">
          <el-input v-model="form.live_room_title" placeholder="视频直播" style="max-width: 320px" />
        </el-form-item>
        <el-form-item label="直播间地址">
          <el-input
            v-model="form.live_room_url"
            type="textarea"
            :rows="2"
            placeholder="https://live.example.com/xxx"
          />
        </el-form-item>

        <el-divider content-position="left">旧版字段（前台 Vue 已不使用轨道路由）</el-divider>
        <el-form-item label="下载按钮文案">
          <el-input v-model="form.download_text" placeholder="下载" />
        </el-form-item>
        <el-form-item label="下载按钮链接">
          <div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap; width: 100%">
            <el-input v-model="form.download_url" placeholder="#" style="flex: 1; min-width: 200px" />
            <el-button type="primary" link @click="openLinkPicker({ type: 'download' })">选择链接</el-button>
          </div>
        </el-form-item>
        <el-form-item label="平台轨道（可选）">
          <div v-for="(p, i) in form.platforms" :key="i" style="display: flex; gap: 8px; margin-bottom: 8px; align-items: center">
            <el-input v-model="p.name" placeholder="名称" style="width: 140px" />
            <el-input v-model="p.url" placeholder="链接" style="flex: 1; min-width: 140px" />
            <el-button type="primary" link @click="openLinkPicker({ type: 'platform', index: i })">选择链接</el-button>
            <el-button link type="danger" @click="form.platforms.splice(i, 1)">删除</el-button>
          </div>
          <el-button link type="primary" @click="form.platforms.push({ name: '', url: '#' })">+ 添加</el-button>
        </el-form-item>

        <el-divider content-position="left">版本与徽章（前台已隐藏主视觉条，可留空）</el-divider>
        <el-form-item label="版本">
          <el-input v-model="form.version" placeholder="可留空" style="width: 200px" />
        </el-form-item>
        <el-form-item label="发布说明">
          <el-input v-model="form.launch_year" placeholder="发布日期：以官网为准" style="width: 200px" />
        </el-form-item>
        <el-form-item label="徽章文案">
          <el-input v-model="form.badge_text" placeholder="完全免费" style="width: 200px" />
        </el-form-item>

        <el-divider content-position="left">特性卡片</el-divider>
        <el-form-item label="特性">
          <div v-for="(f, i) in form.features" :key="i" style="margin-bottom: 12px; padding: 12px; border: 1px solid #eee; border-radius: 8px">
            <el-input v-model="f.title" placeholder="标题" style="margin-bottom: 8px" />
            <el-input v-model="f.desc" type="textarea" :rows="2" placeholder="描述" />
            <el-button link type="danger" size="small" @click="form.features.splice(i, 1)">删除</el-button>
          </div>
          <el-button link type="primary" @click="form.features.push({ title: '', desc: '' })">+ 添加特性</el-button>
        </el-form-item>

        <el-form-item label="页脚文案">
          <el-input v-model="form.footer_text" placeholder="© 2024 宇恒一号 · 成都宇信达智能科技有限公司" />
        </el-form-item>

        <el-divider content-position="left">首页下方扩展区（可视化积木，可拖拽排序）</el-divider>
        <p class="builder-tip">
          与「网页管理 → 积木」相同：从左侧手柄拖拽调整模块顺序。保存后内容显示在落地页主体模块<strong>之后</strong>、页脚之前。留空则不显示扩展区。
        </p>
        <el-form-item label="扩展积木" class="builder-form-item homepage-builder-wrap">
          <PageBuilderEditor v-model="form.body_builder" :site-id="siteId" />
        </el-form-item>
      </el-form>

      <el-empty v-else description="请先选择站点" />
    </el-card>

    <LinkPickerDialog
      v-model="linkPickerVisible"
      :site-id="siteId"
      @select="onLinkPicked"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getSites, getOfficialSite, getHomepage, updateHomepage } from '../../api/admin'
import { useAuthStore } from '../../stores/auth'
import LinkPickerDialog from '../../components/LinkPickerDialog.vue'
import PageBuilderEditor from '../../components/PageBuilderEditor.vue'

const siteId = ref('')
const sites = ref([])
const saving = ref(false)
const downloading = ref(false)
const formRef = ref(null)
const linkPickerVisible = ref(false)
/** @type {import('vue').Ref<{ type: 'nav' | 'download' | 'platform'; index?: number }>} */
const linkPickTarget = ref({ type: 'download' })

const defaultForm = () => ({
  logo_text: '宇恒一号',
  nav_links: [
    { label: '产品简介', url: '#intro' },
    { label: '产品视频', url: '#videos' },
    { label: '联系我们', url: '#contact' }
  ],
  title: '宇恒一号',
  subtitle: '',
  description: '跨越星际的智能伙伴 · 探索无限可能\n引领您进入前所未有的数字宇宙',
  download_text: '下载',
  download_url: '#',
  download_windows_url: '/promotion/downloads/yuheng-windows.zip',
  download_android_url: '/promotion/downloads/yuheng-android.apk',
  platforms: [],
  version: '',
  launch_year: '发布日期：以官网为准',
  badge_text: '完全免费',
  features: [
    { title: '星际导航', desc: '先进的 AI 导航系统，精准定位您的需求，引领探索之旅' },
    { title: '量子同步', desc: '跨维度数据同步技术，您的数据在多宇宙中保持一致' },
    { title: '星际防护', desc: '来自未来的安全加密协议，守护您的数字资产安全' }
  ],
  footer_text: '© 2024 宇恒一号 · 成都宇信达智能科技有限公司',
  body_builder: '',
  live_room_url: '',
  live_room_title: '视频直播'
})

const form = reactive(defaultForm())

const fetchSites = async () => {
  try {
    const sitesRes = await getSites()
    sites.value = sitesRes.list || []
    let officialSiteId = ''
    try {
      const officialRes = await getOfficialSite()
      officialSiteId = officialRes.site_id || ''
    } catch (_) {
      // 兼容旧后端未提供 official-site 接口时仍可正常选站
    }
    const q = new URLSearchParams(window.location.search)
    if (q.get('site_id') && sites.value.some((s) => s.id === q.get('site_id'))) {
      siteId.value = q.get('site_id')
    } else if (officialSiteId && sites.value.some((s) => s.id === officialSiteId)) {
      siteId.value = officialSiteId
    } else if (sites.value.length) {
      siteId.value = sites.value[0].id
    }
  } catch (e) {
    ElMessage.error(e.message)
  }
}

const fetchData = async () => {
  if (!siteId.value) return
  try {
    const data = await getHomepage(siteId.value)
    const base = defaultForm()
    Object.assign(form, {
      ...base,
      ...data,
      nav_links: Array.isArray(data.nav_links) && data.nav_links.length ? data.nav_links : base.nav_links,
      platforms: Array.isArray(data.platforms) ? data.platforms : base.platforms,
      features: Array.isArray(data.features) && data.features.length ? data.features : base.features,
      download_windows_url: data.download_windows_url || base.download_windows_url,
      download_android_url: data.download_android_url || base.download_android_url,
      live_room_url: typeof data.live_room_url === 'string' ? data.live_room_url : base.live_room_url,
      live_room_title: (typeof data.live_room_title === 'string' && data.live_room_title.trim())
        ? data.live_room_title.trim()
        : base.live_room_title
    })
  } catch (e) {
    ElMessage.error(e.message)
  }
}

watch(siteId, fetchData)

const handleSave = async () => {
  saving.value = true
  try {
    await updateHomepage(siteId.value, form)
    ElMessage.success('保存成功')
  } catch (e) {
    ElMessage.error(e.response?.data?.error || e.message)
  } finally {
    saving.value = false
  }
}

const authStore = useAuthStore()
const handleDownload = async () => {
  downloading.value = true
  try {
    const token = authStore.getToken()
    const url = `/api/admin/sites/${siteId.value}/homepage/download`
    const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } })
    if (!res.ok) throw new Error('下载失败')
    const blob = await res.blob()
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'index.html'
    a.click()
    URL.revokeObjectURL(a.href)
    ElMessage.success('已下载 index.html')
  } catch (e) {
    ElMessage.error(e.message || '下载失败')
  } finally {
    downloading.value = false
  }
}

function openLinkPicker(target) {
  linkPickTarget.value = target
  linkPickerVisible.value = true
}

function onLinkPicked(url) {
  const t = linkPickTarget.value
  if (t.type === 'nav' && typeof t.index === 'number') {
    form.nav_links[t.index].url = url
  } else if (t.type === 'download') {
    form.download_url = url
  } else if (t.type === 'platform' && typeof t.index === 'number') {
    form.platforms[t.index].url = url
  }
  ElMessage.success('已填入链接')
}

function previewReady(url) {
  const u = (url || '').trim()
  return Boolean(u && u !== '#')
}

/** 后台试跳：相对路径用当前浏览器域名拼接 */
function previewHref(url) {
  const u = (url || '').trim()
  if (/^https?:\/\//i.test(u)) return u
  if (u.startsWith('/')) return `${window.location.origin}${u}`
  return u
}

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

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.homepage-form {
  max-width: 720px;
}
.builder-tip {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  margin: 0 0 12px;
  max-width: 900px;
}
.homepage-builder-wrap {
  max-width: 1000px;
}
.homepage-builder-wrap :deep(.el-form-item__content) {
  display: block;
  margin-left: 0 !important;
}
.builder-form-item :deep(.el-form-item__content) {
  display: block;
  margin-left: 0 !important;
}
</style>
