<template>
  <div class="download-page">
    <div v-loading="loading" class="card">
      <template v-if="data">
        <div class="app-info">
          <img v-if="data.icon_url" :src="data.icon_url" class="icon" alt="" />
          <div v-else class="icon-placeholder">
            <el-icon :size="48"><Download /></el-icon>
          </div>
          <h1>{{ data.name }}</h1>
          <p v-if="data.description" class="desc">{{ data.description }}</p>
        </div>

        <div v-if="selectedVersion" class="version-info">
          <h3>最新版本 {{ selectedVersion.version_code }}</h3>
          <p v-if="selectedVersion.release_notes" class="release-notes">
            {{ selectedVersion.release_notes }}
          </p>
          <div class="meta">
            <span v-if="selectedVersion.platform" class="platform">
              {{ platformLabel(selectedVersion.platform) }}
            </span>
            <span v-if="selectedVersion.file_size" class="size">
              {{ formatSize(selectedVersion.file_size) }}
            </span>
          </div>
          <el-button
            type="primary"
            size="large"
            :icon="Download"
            @click="handleDownload"
            class="download-btn"
          >
            立即下载
          </el-button>
        </div>
        <div v-else class="no-version">
          <el-empty description="暂无可用版本" />
        </div>
      </template>
      <template v-else-if="!loading && error">
        <el-result icon="error" title="未找到" sub-title="该分发不存在或已被删除" />
      </template>
    </div>

    <!-- 底部平台切换栏（微信风格） -->
    <footer v-if="data && platformTabs.length > 0" class="platform-footer">
      <div class="platform-icons">
        <button
          v-for="tab in platformTabs"
          :key="tab.key"
          type="button"
          class="platform-icon-btn"
          :class="{ active: activeTab === tab.key }"
          @click="selectPlatformTab(tab.key)"
        >
          <span class="platform-icon-circle">
            <el-icon :size="28"><component :is="platformIcon(tab.key)" /></el-icon>
          </span>
          <span class="platform-icon-label">{{ tab.label }}</span>
        </button>
      </div>
    </footer>

    <el-dialog
      v-model="wechatTipVisible"
      title="请在外部浏览器中打开"
      width="340px"
      align-center
      :close-on-click-modal="true"
    >
      <div class="wechat-tip-content">
        <div class="wechat-step">
          <span class="step-text"><span class="step-num">1.</span>点击右上角三个点</span>
          <img src="/wx_three_point.png" alt="三个点" class="step-img" />
        </div>
        <div class="wechat-step">
          <span class="step-text"><span class="step-num">2.</span>选择在浏览器中打开</span>
          <img src="/wx_out_browser.png" alt="在浏览器中打开" class="step-img" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Download, Iphone, Monitor, Cellphone } from '@element-plus/icons-vue'
import type { Component } from 'vue'
import { getDistributionPublic, DistributionPublicResponse, type LatestVersionInfoPublic } from '../../api/clientDistributions'

const route = useRoute()
const router = useRouter()
const shareId = computed(() => String(route.params.id ?? ''))
const isWeChat = /MicroMessenger/i.test(navigator.userAgent)
const data = ref<DistributionPublicResponse | null>(null)
const loading = ref(true)
const error = ref(false)
const wechatTipVisible = ref(false)

/** 多平台时默认选中安卓（有则优先 android_phone / android / android_tablet） */
function pickDefaultPlatformTab(tabs: { key: string }[]): string {
  const keys = tabs.map((t) => t.key)
  for (const k of ['android_phone', 'android', 'android_tablet'] as const) {
    if (keys.includes(k)) return k
  }
  return keys[0] ?? ''
}

/** URL ?platform= 与接口 key 对齐 */
function normalizePlatformQuery(raw: unknown): string {
  const v = Array.isArray(raw) ? raw[0] : raw
  return typeof v === 'string' ? v.trim() : ''
}

const PLATFORM_LABELS: Record<string, string> = {
  android: 'Android',
  android_phone: '安卓',
  android_tablet: '安卓平板',
  ios: 'iOS',
  ipados: 'iPadOS',
  windows: 'Windows',
  macos: 'macOS',
  harmonyos_pc: '鸿蒙电脑',
  harmonyos_pad: '鸿蒙平板',
  harmonyos_phone: '鸿蒙',
}
const platformLabel = (value: string) => (value ? PLATFORM_LABELS[value] || value : '')

/** 平台对应底部圆形图标（微信风格） */
function platformIcon(platformKey: string): Component {
  const iconMap: Record<string, Component> = {
    android: Cellphone,
    android_phone: Cellphone,
    android_tablet: Cellphone,
    ios: Iphone,
    ipados: Iphone,
    windows: Monitor,
    macos: Monitor,
    harmonyos_pc: Monitor,
    harmonyos_pad: Cellphone,
    harmonyos_phone: Cellphone
  }
  return iconMap[platformKey] || Download
}

/** Tab 显示顺序 */
const PLATFORM_ORDER = ['windows', 'macos', 'android', 'android_phone', 'android_tablet', 'ios', 'ipados', 'harmonyos_pc', 'harmonyos_pad', 'harmonyos_phone']

const platformTabs = computed<{ key: string; label: string }[]>(() => {
  const byPlatform = data.value?.latest_versions_by_platform
  if (!byPlatform || !Object.keys(byPlatform).length) return []
  const keys = Object.keys(byPlatform).sort(
    (a, b) => PLATFORM_ORDER.indexOf(a) - PLATFORM_ORDER.indexOf(b) || a.localeCompare(b)
  )
  return keys.map((key) => ({ key, label: platformLabel(key) || key }))
})

const activeTab = ref('')

/** 点击底部平台 tab：同步地址栏 ?platform=，保留其它查询参数 */
function selectPlatformTab(key: string) {
  const q = normalizePlatformQuery(route.query.platform)
  if (activeTab.value === key && q === key) return
  activeTab.value = key
  router.replace({
    path: route.path,
    query: { ...route.query, platform: key }
  })
}

/** 当前选中的版本：有 Tab 时用选中平台，否则用全局 latest_version */
const selectedVersion = computed<LatestVersionInfoPublic | undefined>(() => {
  const d = data.value
  if (!d) return undefined
  const byPlatform = d.latest_versions_by_platform
  if (byPlatform && activeTab.value && byPlatform[activeTab.value]) {
    return byPlatform[activeTab.value]
  }
  return d.latest_version
})

watch(
  () => [data.value, platformTabs.value, route.query.platform] as const,
  (newVal, oldVal) => {
    const d = newVal[0]
    const tabs = newVal[1]
    const qPlatform = newVal[2]
    if (tabs.length === 0) return

    const byPlatform = d?.latest_versions_by_platform
    const requested = normalizePlatformQuery(qPlatform)
    const valid = requested && byPlatform?.[requested] ? requested : ''

    if (!activeTab.value) {
      activeTab.value = valid || pickDefaultPlatformTab(tabs)
      return
    }

    if (oldVal === undefined) return

    const oldQ = normalizePlatformQuery(oldVal[2])
    if (oldQ === requested) return

    if (valid) {
      activeTab.value = valid
    } else if (!requested && oldQ !== '') {
      activeTab.value = pickDefaultPlatformTab(tabs)
    }
  },
  { immediate: true }
)

const formatSize = (bytes: number) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

const handleDownload = () => {
  const v = selectedVersion.value
  if (!v?.download_url) return
  if (isWeChat) {
    wechatTipVisible.value = true
  } else {
    window.open(v.download_url, '_blank')
  }
}

onMounted(async () => {
  if (!shareId.value) {
    loading.value = false
    error.value = true
    return
  }
  try {
    const res = await getDistributionPublic(shareId.value)
    data.value = res.data as DistributionPublicResponse
  } catch {
    data.value = null
    error.value = true
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.download-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  background: #f8f9fa;
  padding: 24px 20px 140px;
  color: #1a1a1a;
}
.wechat-tip-content {
  padding: 8px 0;
}
.wechat-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  font-size: 15px;
}
.wechat-step:last-child {
  margin-bottom: 0;
}
.step-text {
  margin-bottom: 8px;
}
.step-num {
  font-weight: 600;
}
.step-img {
  width: 120px;
  height: auto;
  margin-top: 8px;
  border-radius: 8px;
}
.card {
  background: #fff;
  border-radius: 12px;
  padding: 40px 32px;
  max-width: 520px;
  width: 100%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  color: #1a1a1a;
}
.app-info {
  text-align: center;
  margin-bottom: 28px;
}
.icon {
  width: 80px;
  height: 80px;
  border-radius: 16px;
  object-fit: cover;
}
.icon-placeholder {
  width: 80px;
  height: 80px;
  margin: 0 auto 16px;
  background: #f0f0f0;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}
.app-info h1 {
  margin: 0 0 8px 0;
  font-size: 26px;
  font-weight: 600;
  color: #1a1a1a;
}
.desc {
  color: #606266;
  font-size: 14px;
  margin: 0;
}
.version-info {
  text-align: center;
}
.version-info h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  color: #1a1a1a;
}
.release-notes {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 16px 0;
  white-space: pre-wrap;
  text-align: left;
}
.meta {
  margin-bottom: 24px;
  font-size: 13px;
  color: #909399;
}
.platform {
  margin-right: 12px;
}
.download-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  background: #07c160;
  color: #fff;
  border: none;
}
.download-btn:hover {
  background: #06ad56;
  color: #fff;
}
.no-version {
  padding: 40px 0;
}
.no-version :deep(.el-empty__description) {
  color: #909399;
}
.card :deep(.el-result__title) {
  color: #1a1a1a;
}
.card :deep(.el-result__subtitle) {
  color: #606266;
}
.card :deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
}
.card :deep(.el-loading-spinner .path) {
  stroke: #07c160;
}

/* 底部平台切换栏（白底协调） */
.platform-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px 16px 24px;
  background: #fff;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);
}
.platform-icons {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px 24px;
  max-width: 560px;
  margin: 0 auto;
}
.platform-icon-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: none;
  border: none;
  color: #606266;
  cursor: pointer;
  padding: 0;
  transition: color 0.2s ease;
}
.platform-icon-btn:hover {
  color: #07c160;
}
.platform-icon-circle {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  transition: background 0.2s ease, color 0.2s ease;
}
.platform-icon-btn:hover .platform-icon-circle {
  background: #e8e8e8;
}
.platform-icon-btn.active .platform-icon-circle {
  background: #e8f5e9;
  color: #07c160;
}
.platform-icon-btn.active {
  color: #07c160;
}
.platform-icon-btn.active .platform-icon-circle :deep(.el-icon) {
  color: #07c160;
}
.platform-icon-label {
  font-size: 12px;
}
</style>
