<template>
  <div class="appmgr-page">
    <el-card shadow="never" class="tabs-card">
      <div class="app-tabs">
        <div v-for="t in tabs" :key="t.key" class="app-tab" :class="{active:activeTab===t.key}" @click="switchTab(t.key)">
          <span>{{ t.icon }}</span> {{ t.label }}
        </div>
      </div>
    </el-card>

    <!-- Tab1: APP基础配置 -->
    <div v-show="activeTab==='basic'">
      <el-card shadow="never">
        <h3 class="section-title">📱 APP基础配置</h3>
        <el-form label-width="140px" style="max-width:600px">
          <el-divider content-position="left">启动图</el-divider>
          <el-form-item label="启动图">
            <el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="r=>cfg.splash_image=r.data.url" accept="image/*">
              <el-image v-if="cfg.splash_image" :src="cfg.splash_image" style="width:80px;height:120px;border-radius:6px;object-fit:cover;border:1px solid #eee" />
              <el-button v-else size="small"><el-icon><Plus /></el-icon>上传图片</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="启动图跳转链接">
            <el-input v-model="cfg.splash_link" placeholder="点击启动图跳转的URL" />
          </el-form-item>

          <el-divider content-position="left">开屏广告</el-divider>
          <el-form-item label="开屏广告图">
            <el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="r=>cfg.ad_image=r.data.url" accept="image/*">
              <el-image v-if="cfg.ad_image" :src="cfg.ad_image" style="width:80px;height:120px;border-radius:6px;object-fit:cover;border:1px solid #eee" />
              <el-button v-else size="small"><el-icon><Plus /></el-icon>上传图片</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="广告跳转链接">
            <el-input v-model="cfg.ad_link" placeholder="点击广告跳转的URL" />
          </el-form-item>
          <el-form-item label="广告展示时长">
            <el-input-number v-model="cfg.ad_duration" :min="1" :max="60" style="width:160px" /><span style="margin-left:8px">秒</span>
          </el-form-item>

          <el-divider content-position="left">底部导航</el-divider>
          <el-form-item label="导航配置（JSON）">
            <el-input v-model="cfg.tabbar_config" type="textarea" :rows="6" style="width:100%" placeholder='[{"icon":"home","label":"首页","page":"/pages/index/index"},{"icon":"category","label":"分类","page":"/pages/category/index"}]' />
            <span style="font-size:12px;color:#999;margin-top:4px;display:block">底部Tab导航JSON配置，页面路径根据你的小程序/APP路由填写</span>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="saveConfig" :loading="cfgSaving">💾 保存基础配置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- Tab2: 版本管理 -->
    <div v-show="activeTab==='versions'">
      <div class="action-bar">
        <el-button type="primary" @click="openVersion()"><el-icon><Plus /></el-icon>新增版本</el-button>
      </div>
      <el-card shadow="never">
        <el-table :data="versionList" border v-loading="verLoad" style="width:100%">
          <el-table-column prop="name" label="版本名" width="120" />
          <el-table-column prop="version_code" label="版本号" width="80" align="center" />
          <el-table-column label="平台" width="80" align="center">
            <template #default="{row}"><el-tag size="small">{{ row.platform==='all'?'全部':row.platform==='android'?'安卓':'iOS' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="更新日志" min-width="200">
            <template #default="{row}"><div style="max-height:60px;overflow:hidden;text-overflow:ellipsis;font-size:13px;color:#666">{{ row.changelog||'-' }}</div></template>
          </el-table-column>
          <el-table-column label="下载链接" min-width="160">
            <template #default="{row}"><a :href="row.download_url" target="_blank" style="color:#409eff;font-size:12px">{{ row.download_url||'-' }}</a></template>
          </el-table-column>
          <el-table-column label="强制更新" width="80" align="center">
            <template #default="{row}"><el-tag :type="row.force_update===1?'danger':'info'" size="small">{{ row.force_update===1?'强制':'可选' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="状态" width="70" align="center">
            <template #default="{row}"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'发布':'草稿' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="创建时间" width="160" align="center">
            <template #default="{row}">{{ row.created_at||'-' }}</template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{row}">
              <el-button size="small" @click="openVersion(row)">编辑</el-button>
              <el-popconfirm title="删除？" @confirm="delVersion(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrap">
          <el-pagination v-model:page-size="verPS" v-model:current-page="verP" :total="verTotal" layout="total,prev,pager,next" @current-change="fetchVersions" />
        </div>
      </el-card>
    </div>

    <!-- Tab3: 终端开关 -->
    <div v-show="activeTab==='switch'">
      <el-card shadow="never">
        <h3 class="section-title">🔘 APP入口开关</h3>
        <el-form label-width="180px" style="max-width:500px">
          <el-form-item label="APP登录入口开关">
            <el-switch v-model="appSwitch.enabled" active-value="1" inactive-value="0" />
            <span style="margin-left:10px;font-size:12px;color:#999">关闭后用户无法通过APP登录/注册</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAppSwitch" :loading="switchSaving">保存开关设置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 版本管理弹窗 -->
    <el-dialog v-model="verVis" :title="verEdit?'编辑版本':'新增版本'" width="550px">
      <el-form :model="verForm" label-width="100px">
        <el-form-item label="版本名" required><el-input v-model="verForm.name" placeholder="如：v1.2.0" /></el-form-item>
        <el-form-item label="版本号"><el-input-number v-model="verForm.version_code" :min="1" style="width:200px" /><span style="margin-left:8px;color:#999;font-size:12px">递增数字</span></el-form-item>
        <el-form-item label="平台">
          <el-select v-model="verForm.platform" style="width:200px">
            <el-option label="全部" value="all" />
            <el-option label="安卓" value="android" />
            <el-option label="iOS" value="ios" />
          </el-select>
        </el-form-item>
        <el-form-item label="更新日志"><el-input v-model="verForm.changelog" type="textarea" :rows="3" maxlength="500" /></el-form-item>
        <el-form-item label="下载链接" required><el-input v-model="verForm.download_url" placeholder="https://..." /></el-form-item>
        <el-form-item label="强制更新"><el-switch v-model="verForm.force_update" :active-value="1" :inactive-value="0" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="verVis=false">取消</el-button><el-button type="primary" @click="saveVersion">保存</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })
const uploadUrl = '/api/admin/upload/image'
const uh = { Authorization: 'Bearer ' + localStorage.getItem('admin_token') }

const tabs = [
  { key:'basic', icon:'⚙️', label:'APP基础配置' },
  { key:'versions', icon:'📦', label:'版本管理' },
  { key:'switch', icon:'🔘', label:'终端开关' },
]
const activeTab = ref('basic')

function switchTab(k) {
  activeTab.value = k
  if (k === 'basic') fetchConfig()
  else if (k === 'versions') fetchVersions()
  else if (k === 'switch') fetchAppSwitch()
}

// ===== APP基础配置 =====
const cfg = reactive({
  splash_image:'', splash_link:'',
  ad_image:'', ad_link:'', ad_duration:5,
  tabbar_config:''
})
const cfgSaving = ref(false)

async function fetchConfig() {
  try {
    const r = await API.get('/app/config')
    const d = r.data.data||{}
    cfg.splash_image = d.splash_image||''
    cfg.splash_link = d.splash_link||''
    cfg.ad_image = d.ad_image||''
    cfg.ad_link = d.ad_link||''
    cfg.ad_duration = parseInt(d.ad_duration)||5
    cfg.tabbar_config = d.tabbar_config||''
  } catch { /* 默认值 */ }
}

async function saveConfig() {
  cfgSaving.value = true
  try {
    await API.put('/app/config', { ...cfg })
    ElMessage.success('基础配置已保存')
  } catch { ElMessage.error('保存失败') }
  finally { cfgSaving.value = false }
}

// ===== 版本管理 =====
const versionList = ref([]); const verLoad = ref(false)
const verP = ref(1); const verPS = ref(10); const verTotal = ref(0)
const verVis = ref(false); const verEdit = ref(null)
const verForm = reactive({
  name:'', version_code:1, platform:'all', changelog:'', download_url:'', force_update:0
})

async function fetchVersions() {
  verLoad.value = true
  try {
    const r = await API.get('/app/versions', { params:{ page:verP.value, pageSize:verPS.value } })
    const d = r.data.data||{}
    versionList.value = d.list||[]; verTotal.value = d.total||0
  } catch { versionList.value = []; verTotal.value = 0 }
  finally { verLoad.value = false }
}

function openVersion(row) {
  verEdit.value = row?.id||null
  if(row) {
    verForm.name = row.name; verForm.version_code = row.version_code
    verForm.platform = row.platform||'all'; verForm.changelog = row.changelog||''
    verForm.download_url = row.download_url; verForm.force_update = row.force_update||0
  } else {
    verForm.name = ''; verForm.version_code = 1; verForm.platform = 'all'
    verForm.changelog = ''; verForm.download_url = ''; verForm.force_update = 0
  }
  verVis.value = true
}

async function saveVersion() {
  if(!verForm.name) return ElMessage.warning('请填写版本名')
  if(!verForm.download_url) return ElMessage.warning('请填写下载链接')
  try {
    if(verEdit.value) await API.put('/app/versions/'+verEdit.value, verForm)
    else await API.post('/app/versions', verForm)
    ElMessage.success('保存成功'); verVis.value=false; fetchVersions()
  } catch { ElMessage.error('保存失败') }
}

async function delVersion(id) {
  try { await API.delete('/app/versions/'+id); ElMessage.success('已删除'); fetchVersions() } catch {}
}

// ===== 终端开关 =====
const appSwitch = reactive({ enabled:'1' })
const switchSaving = ref(false)

async function fetchAppSwitch() {
  try {
    const r = await API.get('/app/config')
    appSwitch.enabled = r.data.data?.app_entry_enabled||'1'
  } catch {}
}

async function saveAppSwitch() {
  switchSaving.value = true
  try {
    await API.put('/app/config', { app_entry_enabled: appSwitch.enabled })
    ElMessage.success('开关设置已保存')
  } catch { ElMessage.error('保存失败') }
  finally { switchSaving.value = false }
}

onMounted(() => { fetchConfig() })
</script>

<style scoped>
.appmgr-page { max-width: 1400px; }
.tabs-card { margin-bottom:16px; padding:4px 0; }
.app-tabs { display:flex; gap:4px; }
.app-tab { display:flex; align-items:center; gap:6px; padding:10px 18px; border-radius:8px; cursor:pointer; font-size:14px; transition:all .2s; }
.app-tab:hover { background:#f5f7fa; }
.app-tab.active { background:#ecf5ff; color:#409eff; font-weight:600; }
.action-bar { margin-bottom:16px; }
.pagination-wrap { display:flex; justify-content:flex-end; padding:16px 0 0; }
.section-title { font-size:16px; font-weight:600; color:#333; margin:0 0 20px 0; padding-bottom:12px; border-bottom:2px solid #409eff; display:inline-block; }
</style>
