<template>
  <div class="download-page">
    <div v-if="loading" class="state-msg">加载中…</div>
    <div v-else-if="loadError" class="state-msg">{{ loadError }}</div>
    <div v-else class="sections">
      <div v-for="section in sections" :key="section.key" class="section-card">
        <h2 class="section-title">{{ section.label }}</h2>

        <template v-if="section.info">
          <div class="version-info">
            <span class="version-name">{{ section.info.versionName }}</span>
            <span class="version-code">（{{ section.info.versionCode }}）</span>
          </div>
          <div v-if="section.info.changeLog" class="change-log">{{ section.info.changeLog }}</div>

          <div class="actions">
            <a
              v-if="section.key === 'android' && section.info.downloadUrl"
              class="btn btn-primary"
              :href="section.info.downloadUrl"
            >立即安装</a>
            <span
              v-else-if="section.key === 'android' && section.info.available === false"
              class="btn btn-disabled"
            >无法下载</span>

            <a
              v-if="section.key !== 'android' && section.info.storeUrl"
              class="btn btn-primary"
              :href="section.info.storeUrl"
              target="_blank"
              rel="noopener"
            >去应用商店安装</a>

            <a
              v-if="section.key === 'android' && matchedStoreUrl"
              class="btn btn-secondary"
              :href="matchedStoreUrl"
              target="_blank"
              rel="noopener"
            >去{{ matchedStoreLabel }}安装</a>
          </div>

          <div
            v-if="section.key === 'android' && !matchedStoreUrl && otherStoreLinks.length"
            class="other-links"
          >
            <span class="other-links-label">其他应用商店：</span>
            <a
              v-for="link in otherStoreLinks"
              :key="link.type"
              class="other-link"
              :href="link.url"
              target="_blank"
              rel="noopener"
            >{{ link.label }}</a>
          </div>

          <div v-if="section.key === 'android' && olderHistory.length" class="history">
            <button class="history-toggle" @click="historyOpen = !historyOpen">
              历史版本（{{ olderHistory.length }}）{{ historyOpen ? '收起' : '展开' }}
            </button>
            <div v-if="historyOpen" class="history-list">
              <div v-for="item in olderHistory" :key="item.versionCode" class="history-item">
                <div class="history-item-info">
                  <span class="version-name">{{ item.versionName }}</span>
                  <span class="version-code">（{{ item.versionCode }}）</span>
                  <span v-if="item.publishedAt" class="history-date">{{ formatDate(item.publishedAt) }}</span>
                </div>
                <a v-if="item.downloadUrl" class="btn btn-secondary btn-small" :href="item.downloadUrl">下载</a>
                <span v-else class="btn btn-disabled btn-small">无法下载</span>
              </div>
            </div>
          </div>
        </template>

        <div v-else class="empty">当前应用无可用安装包</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { fetchDownloadPageInfo, type DownloadPageAppInfo, type DownloadPageInfo } from '@/api/update'

const route = useRoute()
const appKey = String(route.params.appKey ?? '')

const loading = ref(true)
const loadError = ref('')
const data = ref<DownloadPageInfo | null>(null)

const STORE_LABELS: Record<string, string> = {
  HUAWEI: '华为应用市场',
  HONOR: '荣耀应用市场',
  MI: '小米应用商店',
  OPPO: 'OPPO 软件商店',
  VIVO: 'vivo 应用商店',
  GOOGLE_PLAY: 'Google Play',
}

type PlatformKind = 'android' | 'ios' | 'harmony' | 'other'

function detectPlatform(): PlatformKind {
  const ua = navigator.userAgent || ''
  if (/harmonyos/i.test(ua)) return 'harmony'
  if (/android/i.test(ua)) return 'android'
  if (/iphone|ipad|ipod/i.test(ua)) return 'ios'
  return 'other'
}

function detectVendor(): string | null {
  const ua = navigator.userAgent || ''
  if (/\bvivo\b/i.test(ua)) return 'VIVO'
  if (/honor/i.test(ua)) return 'HONOR'
  if (/huawei/i.test(ua)) return 'HUAWEI'
  if (/xiaomi|redmi|poco/i.test(ua)) return 'MI'
  if (/\boppo\b/i.test(ua)) return 'OPPO'
  return null
}

const platform = ref<PlatformKind>(detectPlatform())
const vendor = ref<string | null>(detectVendor())

interface Section {
  key: 'android' | 'ios' | 'harmony'
  label: string
  info: DownloadPageAppInfo | null
}

const sections = computed<Section[]>(() => {
  if (!data.value) return []
  if (platform.value === 'android') {
    return [{ key: 'android', label: 'Android', info: data.value.android }]
  }
  if (platform.value === 'ios') {
    return [{ key: 'ios', label: 'iOS', info: data.value.ios }]
  }
  if (platform.value === 'harmony') {
    return [{ key: 'harmony', label: 'HarmonyOS', info: data.value.harmony }]
  }
  return [
    { key: 'android', label: 'Android', info: data.value.android },
    { key: 'ios', label: 'iOS', info: data.value.ios },
    { key: 'harmony', label: 'HarmonyOS', info: data.value.harmony },
  ]
})

const matchedStoreUrl = computed(() => {
  const links = data.value?.android?.storeLinks
  if (!links || !vendor.value) return ''
  return links[vendor.value] ?? ''
})

const matchedStoreLabel = computed(() => (vendor.value ? STORE_LABELS[vendor.value] ?? vendor.value : ''))

const otherStoreLinks = computed(() => {
  const links = data.value?.android?.storeLinks
  if (!links) return []
  return Object.entries(links).map(([type, url]) => ({
    type,
    url,
    label: STORE_LABELS[type] ?? type,
  }))
})

const historyOpen = ref(false)

const olderHistory = computed(() => {
  const history = data.value?.android?.history
  if (!history) return []
  return history.filter((item) => !item.current)
})

function formatDate(iso: string): string {
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return ''
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

onMounted(async () => {
  if (!appKey) {
    loadError.value = '缺少应用标识'
    loading.value = false
    return
  }
  try {
    const res = await fetchDownloadPageInfo(appKey)
    data.value = res.data.data
  } catch {
    loadError.value = '加载失败，请稍后重试'
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.download-page {
  min-height: 100vh;
  padding: 24px 16px;
  background: #f5f6f8;
  box-sizing: border-box;
}

.state-msg {
  text-align: center;
  color: #888;
  padding: 60px 0;
}

.sections {
  max-width: 480px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.section-title {
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 600;
}

.version-info {
  font-size: 15px;
  margin-bottom: 8px;
}

.version-code {
  color: #999;
}

.change-log {
  color: #666;
  font-size: 13px;
  white-space: pre-wrap;
  margin-bottom: 16px;
}

.actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.btn {
  display: inline-block;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  text-decoration: none;
  text-align: center;
}

.btn-primary {
  background: #409eff;
  color: #fff;
}

.btn-secondary {
  background: #f0f2f5;
  color: #333;
}

.btn-disabled {
  background: #f0f2f5;
  color: #bbb;
  cursor: not-allowed;
}

.other-links {
  margin-top: 12px;
  font-size: 13px;
  color: #666;
}

.other-links-label {
  margin-right: 6px;
}

.other-link {
  margin-right: 10px;
  color: #409eff;
  text-decoration: none;
}

.empty {
  color: #999;
  font-size: 14px;
}

.history {
  margin-top: 16px;
  border-top: 1px solid #eee;
  padding-top: 12px;
}

.history-toggle {
  background: none;
  border: none;
  color: #409eff;
  font-size: 13px;
  cursor: pointer;
  padding: 0;
}

.history-list {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  font-size: 13px;
}

.history-item-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.history-date {
  color: #999;
  font-size: 12px;
}

.btn-small {
  padding: 6px 14px;
  font-size: 13px;
  flex-shrink: 0;
}
</style>
