<template>
  <div>
    <h2 style="margin-bottom: 24px">符号化产物管理</h2>

    <!-- App selector bar -->
    <div class="app-selector-bar">
      <span class="selector-label">选择应用</span>
      <el-select
        :model-value="appKey"
        placeholder="请选择应用"
        style="width:220px"
        :loading="loadingApps"
        @change="setApp"
      >
        <el-option v-for="a in apps" :key="a.appKey" :label="a.name" :value="a.appKey" />
      </el-select>
    </div>
    <el-empty v-if="gateStatus === 'no-app'" description="请选择一个应用" style="margin-top:80px" />
    <div v-else-if="gateStatus === 'loading'" v-loading="true" style="min-height:200px" />
    <div v-else-if="gateStatus === 'not-enabled'" style="margin-top:60px;text-align:center">
      <el-empty description="当前应用未开通崩溃收集服务">
        <el-button type="primary" @click="applyDialogVisible = true">申请开通</el-button>
      </el-empty>
    </div>
    <template v-else>

    <el-card shadow="never">
      <template #header>
        <div class="toolbar toolbar-space-between">
          <span>已上传的符号化产物</span>
          <el-button @click="loadData" :loading="loading">刷新</el-button>
        </div>
      </template>

      <el-table :data="sourcemaps" v-loading="loading" border stripe>
        <el-table-column prop="platform" label="平台" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="platformTagType(row.platform)">{{ row.platform }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="artifactType" label="产物类型" width="150" />
        <el-table-column prop="appVersion" label="应用版本" width="120" />
        <el-table-column prop="moduleId" label="模块" width="120">
          <template #default="{ row }">{{ row.moduleId || '—' }}</template>
        </el-table-column>
        <el-table-column prop="moduleVersion" label="模块版本" width="120">
          <template #default="{ row }">{{ row.moduleVersion || '—' }}</template>
        </el-table-column>
        <el-table-column prop="buildId" label="Build ID" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="buildid-text">{{ row.buildId ?? '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="uploadedAt" label="上传时间" width="170">
          <template #default="{ row }">{{ formatTime(row.uploadedAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-popconfirm
              title="确认删除该符号化产物？"
              confirm-button-text="删除"
              cancel-button-text="取消"
              confirm-button-type="danger"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="!loading && sourcemaps.length === 0" description="暂无符号化产物" />
    </el-card>

    <el-card shadow="never" style="margin-top: 16px">
      <template #header>使用说明</template>
      <div class="usage-guide">
        <h4>Android (ProGuard Mapping)</h4>
        <p>使用 Gradle 插件自动上传：</p>
        <pre class="code-block">apply plugin: 'com.xuqm.bugcollect'

// 构建时自动上传 mapping.txt
./gradlew assembleRelease</pre>

        <h4>React Native (JS Sourcemap)</h4>
        <p>使用 Metro 插件自动上传：</p>
        <pre class="code-block">// metro.config.js
const { withBugCollect } = require('@xuqm/rn-bugcollect/metro')

module.exports = withBugCollect({
  // ... your metro config
})

// 构建时自动上传
npx react-native bundle --platform android --dev false</pre>

        <h4>手动上传</h4>
        <p>使用 curl 命令手动上传：</p>
        <pre class="code-block">curl -X POST "https://your-api.com/bugcollect/v1/artifacts/upload" \
  -H "Authorization: Bearer $XUQM_API_TOKEN" \
  -F "artifactType=R8_MAPPING" \
  -F "appKey=your-app-key" \
  -F "platform=android" \
  -F "appVersion=1.0.0" \
  -F "buildId=your-build-id" \
  -F "artifactHash=sha256-of-mapping" \
  -F "file=@mapping.txt"</pre>
      </div>
    </el-card>
    </template>

    <el-dialog v-model="applyDialogVisible" title="申请开通崩溃收集" width="400px" :close-on-click-modal="false">
      <el-input v-model="applyReason" type="textarea" placeholder="请说明申请原因（选填）" :rows="3" />
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="applyLoading" @click="submitActivation">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { bugCollectApi, type BugCollectSourcemap } from '@/api/bugcollect'
import { useBugCollectApp } from '@/composables/useBugCollectApp'
import { formatTime } from '@/utils/bugCollect'

const { apps, loadingApps, appKey, setApp, gateStatus, applyDialogVisible, applyReason, applyLoading, submitActivation } = useBugCollectApp()

const sourcemaps = ref<BugCollectSourcemap[]>([])
const loading = ref(false)

function platformTagType(platform: string): '' | 'success' | 'warning' | 'info' | 'danger' {
  const map: Record<string, '' | 'success' | 'warning' | 'info' | 'danger'> = {
    android: 'success',
    ios: '',
    harmony: 'warning',
  }
  return map[platform?.toLowerCase()] ?? 'info'
}

async function loadData() {
  if (!appKey.value || gateStatus.value !== 'enabled') return
  loading.value = true
  try {
    const res = await bugCollectApi.sourcemaps.list(appKey.value)
    sourcemaps.value = res.data.data ?? []
  } catch {
    ElMessage.error('加载 Sourcemap 列表失败')
    sourcemaps.value = []
  } finally {
    loading.value = false
  }
}

async function handleDelete(id: number) {
  try {
    await bugCollectApi.sourcemaps.delete(id)
    ElMessage.success('已删除')
    sourcemaps.value = sourcemaps.value.filter(s => s.id !== id)
  } catch {
    ElMessage.error('删除失败')
  }
}

watch(gateStatus, (s) => { if (s === 'enabled') loadData() })
onMounted(loadData)
</script>

<style scoped>
.app-selector-bar { display:flex; align-items:center; gap:12px; margin-bottom:20px; }
.selector-label { font-size:14px; color:#606266; }
.toolbar-space-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.buildid-text {
  font-family: monospace;
  font-size: 12px;
  color: #606266;
}
.usage-guide h4 {
  margin: 16px 0 8px;
  font-size: 14px;
  font-weight: 600;
}
.usage-guide p {
  margin: 4px 0;
  font-size: 13px;
  color: #606266;
}
.code-block {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 12px;
  font-size: 12px;
  line-height: 1.5;
  overflow-x: auto;
  margin: 8px 0 16px;
}
</style>
