<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" style="max-width: 720px">
        <el-divider content-position="left">导航与标题</el-divider>
        <el-form-item label="Logo 文案">
          <el-input v-model="form.logo_text" placeholder="YUHENG ONE" />
        </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="INTERSTELLAR EXPLORER EDITION" />
        </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">
            <el-input v-model="link.label" placeholder="Label" style="width: 120px" />
            <el-input v-model="link.url" placeholder="URL" style="flex: 1" />
            <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">下载按钮</el-divider>
        <el-form-item label="按钮文案">
          <el-input v-model="form.download_text" placeholder="START EXPLORING" />
        </el-form-item>
        <el-form-item label="按钮链接">
          <el-input v-model="form.download_url" placeholder="#" style="flex: 1" />
          <el-button type="primary" link @click="openFilePicker('download')">选择可下载文件</el-button>
        </el-form-item>

        <el-divider content-position="left">平台（轨道）</el-divider>
        <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="如 WINDOWS" style="width: 140px" />
            <el-input v-model="p.url" placeholder="链接" style="flex: 1" />
            <el-button type="primary" link @click="openFilePicker('platform', 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="VERSION 3.2.1" style="width: 200px" />
        </el-form-item>
        <el-form-item label="发射年份">
          <el-input v-model="form.launch_year" placeholder="LAUNCH: 2024" style="width: 200px" />
        </el-form-item>
        <el-form-item label="徽章文案">
          <el-input v-model="form.badge_text" placeholder="FREE ACCESS" 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 YUHENG ONE" />
        </el-form-item>
      </el-form>

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

    <el-dialog v-model="filePickerVisible" title="选择可下载文件" width="640px">
      <el-table
        v-loading="fileListLoading"
        :data="downloadableFiles"
        highlight-current-row
        @current-change="onSelectFile"
      >
        <el-table-column property="name" label="文件名" min-width="180" />
        <el-table-column property="file_path" label="路径" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" link @click="confirmSelectFile(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="!fileListLoading && downloadableFiles.length === 0" description="暂无可下载文件，请在文件管理中上传并勾选“允许下载”" />
    </el-dialog>
  </div>
</template>

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

const siteId = ref('')
const sites = ref([])
const saving = ref(false)
const downloading = ref(false)
const formRef = ref(null)
const filePickerVisible = ref(false)
const fileListLoading = ref(false)
const downloadableFiles = ref([])
const filePickerTarget = ref({ type: 'download' }) // { type: 'download' } | { type: 'platform', index: number }

const defaultForm = () => ({
  logo_text: 'YUHENG ONE',
  nav_links: [{ label: 'MISSION', url: '#' }, { label: 'DOWNLOAD', url: '#' }, { label: 'CONTACT', url: '#' }],
  title: '宇恒一号',
  subtitle: 'INTERSTELLAR EXPLORER EDITION',
  description: '跨越星际的智能伙伴 · 探索无限可能\n引领您进入前所未有的数字宇宙',
  download_text: 'START EXPLORING',
  download_url: '#',
  platforms: [
    { name: 'WINDOWS', url: '#' },
    { name: 'MACOS', url: '#' },
    { name: 'LINUX', url: '#' },
    { name: 'IOS', url: '#' },
    { name: 'ANDROID', url: '#' }
  ],
  version: 'VERSION 3.2.1',
  launch_year: 'LAUNCH: 2024',
  badge_text: 'FREE ACCESS',
  features: [
    { title: '星际导航', desc: '先进的AI导航系统，精准定位您的需求，引领探索之旅' },
    { title: '量子同步', desc: '跨维度数据同步技术，您的数据在多宇宙中保持一致' },
    { title: '星际防护', desc: '来自未来的安全加密协议，守护您的数字资产安全' }
  ],
  footer_text: '© 2024 YUHENG ONE // STELLAR EXPLORATION INITIATIVE'
})

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)
    Object.assign(form, {
      ...defaultForm(),
      ...data,
      nav_links: Array.isArray(data.nav_links) && data.nav_links.length ? data.nav_links : defaultForm().nav_links,
      platforms: Array.isArray(data.platforms) && data.platforms.length ? data.platforms : defaultForm().platforms,
      features: Array.isArray(data.features) && data.features.length ? data.features : defaultForm().features
    })
  } 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 openFilePicker(type, index) {
  filePickerTarget.value = type === 'platform' ? { type: 'platform', index } : { type: 'download' }
  filePickerVisible.value = true
  fetchDownloadableFiles()
}

async function fetchDownloadableFiles() {
  if (!siteId.value) return
  fileListLoading.value = true
  try {
    const res = await getDownloadableAssets(siteId.value)
    downloadableFiles.value = res.list || []
  } catch (e) {
    ElMessage.error(e.message)
    downloadableFiles.value = []
  } finally {
    fileListLoading.value = false
  }
}

function buildDownloadUrl(asset) {
  return `/api/web/sites/${siteId.value}/assets/${asset.id}/download`
}

function confirmSelectFile(asset) {
  const url = buildDownloadUrl(asset)
  if (filePickerTarget.value.type === 'download') {
    form.download_url = url
  } else {
    form.platforms[filePickerTarget.value.index].url = url
  }
  filePickerVisible.value = false
  ElMessage.success('已选择：' + asset.name)
}

function onSelectFile(row) {
  if (row) confirmSelectFile(row)
}

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

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