<template>
  <div class="mapping-container">
    <div class="header">
      <div class="title-group">
        <el-button @click="$router.push('/dashboard/client-distributions')" :icon="ArrowLeft" circle />
        <h2 v-if="distribution">{{ distribution.name }}</h2>
      </div>
    </div>

    <div v-loading="loading" class="content">
      <template v-if="distribution">
        <div class="versions-section">
          <div class="toolbar">
            <el-button type="primary" :icon="Plus" @click="openCreateVersion">新建版本</el-button>
            <el-button type="default" @click="openUpdateFilesDialog">管理自动更新软件</el-button>
            <el-select
              v-model="versionPlatformFilter"
              placeholder="平台"
              clearable
              style="width: 120px; margin-left: 12px;"
              @change="onVersionFilterChange"
            >
              <el-option label="全部" value="" />
              <el-option label="Android" value="android" />
              <el-option label="安卓手机" value="android_phone" />
              <el-option label="安卓平板" value="android_tablet" />
              <el-option label="iOS" value="ios" />
              <el-option label="iPadOS" value="ipados" />
              <el-option label="Windows" value="windows" />
              <el-option label="macOS" value="macos" />
              <el-option label="鸿蒙电脑" value="harmonyos_pc" />
              <el-option label="鸿蒙平板" value="harmonyos_pad" />
              <el-option label="鸿蒙手机" value="harmonyos_phone" />
            </el-select>
            <el-input
              v-model="versionSearchQuery"
              placeholder="搜索版本号、显示名、更新内容"
              clearable
              style="width: 240px; margin-left: 8px;"
              @clear="onVersionSearch"
              @keyup.enter="onVersionSearch"
            >
              <template #append>
                <el-button icon="Search" @click="onVersionSearch" />
              </template>
            </el-input>
          </div>
          <el-table :data="versions" style="width: 100%; margin-top: 15px;" stripe border>
            <el-table-column prop="version_code" label="版本号" width="120" />
            <el-table-column prop="version_name" label="显示名称" width="140" />
            <el-table-column prop="release_notes" label="更新内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="platform" label="平台" width="100" />
            <el-table-column prop="file_size" label="大小" width="100">
              <template #default="scope">
                {{ formatSize(scope.row.file_size) }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="170">
              <template #default="scope">
                {{ new Date(scope.row.created_at).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button type="primary" link @click="openEditVersion(scope.row)">编辑</el-button>
                  <el-divider direction="vertical" />
                  <el-button type="danger" link @click="handleDeleteVersion(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              v-model:current-page="versionPage"
              v-model:page-size="versionPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="versionTotal"
              @size-change="fetchVersions"
              @current-change="fetchVersions"
            />
          </div>
        </div>
      </template>
    </div>

    <!-- 新建/编辑版本 -->
    <el-dialog v-model="versionDialogVisible" :title="versionEditId ? '编辑版本' : '新建版本'" width="520px">
      <el-form :model="versionForm" label-width="100px">
        <!-- 新建：第一步 选择平台 -->
        <template v-if="!versionEditId && createStep === 1">
          <el-form-item label="平台" required>
            <el-select v-model="versionForm.platform" placeholder="请先选择平台" style="width: 100%">
              <el-option label="Android" value="android" />
              <el-option label="安卓手机" value="android_phone" />
              <el-option label="安卓平板" value="android_tablet" />
              <el-option label="iOS" value="ios" />
              <el-option label="iPadOS" value="ipados" />
              <el-option label="Windows" value="windows" />
              <el-option label="macOS" value="macos" />
              <el-option label="鸿蒙电脑" value="harmonyos_pc" />
              <el-option label="鸿蒙平板" value="harmonyos_pad" />
              <el-option label="鸿蒙手机" value="harmonyos_phone" />
            </el-select>
          </el-form-item>
        </template>
        <!-- 新建：第二步 版本内容 -->
        <template v-if="!versionEditId && createStep === 2">
          <el-form-item label="平台">
            <span class="platform-readonly">{{ platformLabel(versionForm.platform) }}</span>
          </el-form-item>
          <el-form-item label="版本号" required>
            <el-input v-model="versionForm.version_code" placeholder="如 1.2.3" />
            <div v-if="latestVersionForPlatform" class="tip tip-hint">当前该平台最新版本：{{ latestVersionForPlatform }}</div>
          </el-form-item>
          <el-form-item label="安装包" required>
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
              :on-change="onFileChange"
              :on-exceed="() => ElMessage.warning('仅支持上传一个文件')"
              accept=".apk,.ipa,.exe,.dmg"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <span class="tip">支持 APK、IPA、EXE 等，最大 500MB</span>
              </template>
            </el-upload>
            <span v-if="versionForm.fileName" class="file-name">{{ versionForm.fileName }}</span>
            <el-progress
              v-if="versionUploadPercent >= 0"
              :percentage="versionUploadPercent"
              style="margin-top: 8px;"
              :status="versionUploadPercent === 100 ? 'success' : undefined"
            />
          </el-form-item>
          <el-form-item label="显示名称">
            <el-input v-model="versionForm.version_name" placeholder="选填，默认同版本号" />
          </el-form-item>
          <el-form-item label="更新内容">
            <el-input v-model="versionForm.release_notes" type="textarea" :rows="4" placeholder="选填" />
          </el-form-item>
        </template>
        <!-- 编辑：不展示版本号，平台必选 -->
        <template v-if="versionEditId">
          <el-form-item label="版本号">
            <span class="platform-readonly">{{ versionForm.version_code }}</span>
          </el-form-item>
          <el-form-item label="平台" required>
            <el-select v-model="versionForm.platform" placeholder="请选择平台" style="width: 100%">
              <el-option label="Android" value="android" />
              <el-option label="安卓手机" value="android_phone" />
              <el-option label="安卓平板" value="android_tablet" />
              <el-option label="iOS" value="ios" />
              <el-option label="iPadOS" value="ipados" />
              <el-option label="Windows" value="windows" />
              <el-option label="macOS" value="macos" />
              <el-option label="鸿蒙电脑" value="harmonyos_pc" />
              <el-option label="鸿蒙平板" value="harmonyos_pad" />
              <el-option label="鸿蒙手机" value="harmonyos_phone" />
            </el-select>
          </el-form-item>
          <el-form-item label="显示名称">
            <el-input v-model="versionForm.version_name" placeholder="选填" />
          </el-form-item>
          <el-form-item label="更新内容">
            <el-input v-model="versionForm.release_notes" type="textarea" :rows="4" placeholder="选填" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <template v-if="!versionEditId && createStep === 2">
          <el-button @click="createStep = 1">上一步</el-button>
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleVersionSubmit" :loading="versionSubmitting">确定</el-button>
        </template>
        <template v-else-if="!versionEditId && createStep === 1">
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="goCreateStep2">下一步</el-button>
        </template>
        <template v-else>
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleVersionSubmit" :loading="versionSubmitting">确定</el-button>
        </template>
      </template>
    </el-dialog>

    <!-- 管理自动更新软件（update 桶） -->
    <el-dialog v-model="updateFilesDialogVisible" title="管理自动更新软件" width="680px" @open="onUpdateFilesDialogOpen">
      <div class="update-files-dialog">
        <el-form-item label="操作系统" required>
          <el-select
            v-model="updateFilesPlatform"
            placeholder="请先选择操作系统"
            style="width: 100%"
            @change="fetchUpdateFilesList"
          >
            <el-option label="Android" value="android" />
            <el-option label="安卓手机" value="android_phone" />
            <el-option label="安卓平板" value="android_tablet" />
            <el-option label="iOS" value="ios" />
            <el-option label="iPadOS" value="ipados" />
            <el-option label="Windows" value="windows" />
            <el-option label="macOS" value="macos" />
            <el-option label="鸿蒙电脑" value="harmonyos_pc" />
            <el-option label="鸿蒙平板" value="harmonyos_pad" />
            <el-option label="鸿蒙手机" value="harmonyos_phone" />
          </el-select>
        </el-form-item>
        <template v-if="updateFilesPlatform">
          <div v-if="updateFilesBaseUrl" class="update-base-url-wrap">
            <span class="label">更新目录 URL（Electron generic 可填）：</span>
            <el-input v-model="updateFilesBaseUrl" readonly>
              <template #append>
                <el-button @click="copyUpdateUrl(updateFilesBaseUrl)">复制</el-button>
              </template>
            </el-input>
          </div>
          <div class="update-files-upload">
            <el-upload
              :auto-upload="false"
              :show-file-list="false"
              :on-change="onUpdateFileSelect"
              :disabled="updateFileUploadPercent >= 0"
              accept="*"
            >
              <el-button type="primary" :loading="updateFileUploadPercent >= 0">上传文件</el-button>
            </el-upload>
            <el-progress
              v-if="updateFileUploadPercent >= 0"
              :percentage="updateFileUploadPercent"
              style="margin-top: 8px;"
              :status="updateFileUploadPercent === 100 ? 'success' : undefined"
            />
          </div>
          <el-table v-loading="updateFilesLoading" :data="updateFilesList" border stripe style="width: 100%; margin-top: 12px;">
            <el-table-column prop="name" label="文件名" min-width="180" show-overflow-tooltip />
            <el-table-column prop="size" label="大小" width="100">
              <template #default="scope">{{ formatSize(scope.row.size) }}</template>
            </el-table-column>
            <el-table-column label="URL" width="100">
              <template #default="scope">
                <el-button link type="primary" @click="copyUpdateUrl(scope.row.url)">复制</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button link type="danger" @click="handleDeleteUpdateFile(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="!updateFilesLoading && updateFilesList.length === 0" description="暂无文件，请上传" style="margin-top: 16px;" />
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import type { UploadInstance, UploadFile, UploadFiles } from 'element-plus'
import {
  getDistribution,
  listVersions,
  createVersion,
  updateVersion,
  deleteVersion,
  listUpdateFiles,
  uploadUpdateFile,
  deleteUpdateFile,
  ClientDistribution,
  ClientVersion,
  type UpdateFileItem
} from '../../api/clientDistributions'

const route = useRoute()
const distId = computed(() => Number(route.params.id))
const distribution = ref<ClientDistribution | null>(null)
const versions = ref<ClientVersion[]>([])
const loading = ref(false)
const versionPage = ref(1)
const versionPageSize = ref(10)
const versionTotal = ref(0)
const versionPlatformFilter = ref('')
const versionSearchQuery = ref('')
const versionDialogVisible = ref(false)
const versionEditId = ref<number | null>(null)
const versionSubmitting = ref(false)
const uploadRef = ref<UploadInstance>()
const selectedFile = ref<File | null>(null)
/** 新建版本步骤：1=选平台，2=填版本内容 */
const createStep = ref(1)
/** 用于提示“当前该平台最新版本”，打开新建弹窗时拉取 */
const allVersionsForHint = ref<ClientVersion[]>([])

/** 新建版本上传进度：-1 不显示，0-100 显示百分比 */
const versionUploadPercent = ref(-1)
/** 管理自动更新文件上传进度：-1 不显示，0-100 显示百分比 */
const updateFileUploadPercent = ref(-1)

/** 管理自动更新软件弹窗 */
const updateFilesDialogVisible = ref(false)
const updateFilesPlatform = ref('')
const updateFilesList = ref<UpdateFileItem[]>([])
const updateFilesBaseUrl = ref('')
const updateFilesLoading = ref(false)

const versionForm = ref({
  version_code: '',
  version_name: '',
  release_notes: '',
  platform: '',
  fileName: ''
})

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 : '-')

/** 当前选中平台下的最新版本号（用于新建第二步提示） */
const latestVersionForPlatform = computed(() => {
  const p = versionForm.value.platform
  if (!p) return ''
  const list = allVersionsForHint.value.filter((v) => v.platform === p)
  return list.length > 0 ? list[0].version_code : ''
})

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

const fetchDetail = async () => {
  loading.value = true
  try {
    const res = await getDistribution(distId.value)
    distribution.value = res.data
  } catch {
    distribution.value = null
  } finally {
    loading.value = false
  }
}

const fetchVersions = async () => {
  if (!distId.value) return
  try {
    const res = await listVersions(distId.value, {
      skip: (versionPage.value - 1) * versionPageSize.value,
      limit: versionPageSize.value,
      platform: versionPlatformFilter.value || undefined,
      search: versionSearchQuery.value?.trim() || undefined
    })
    versions.value = res.data.items
    versionTotal.value = res.data.total
  } catch {
    versions.value = []
  }
}

const onVersionFilterChange = () => {
  versionPage.value = 1
  fetchVersions()
}

const onVersionSearch = () => {
  versionPage.value = 1
  fetchVersions()
}

const openCreateVersion = async () => {
  versionEditId.value = null
  createStep.value = 1
  versionUploadPercent.value = -1
  versionForm.value = { version_code: '', version_name: '', release_notes: '', platform: '', fileName: '' }
  selectedFile.value = null
  uploadRef.value?.clearFiles()
  versionDialogVisible.value = true
  try {
    const res = await listVersions(distId.value, { skip: 0, limit: 200 })
    allVersionsForHint.value = res.data.items || []
  } catch {
    allVersionsForHint.value = []
  }
}

const goCreateStep2 = () => {
  if (!versionForm.value.platform?.trim()) {
    ElMessage.warning('请先选择平台')
    return
  }
  createStep.value = 2
}

const openEditVersion = (row: ClientVersion) => {
  versionEditId.value = row.id
  versionForm.value = {
    version_code: row.version_code,
    version_name: row.version_name || '',
    release_notes: row.release_notes || '',
    platform: row.platform || '',
    fileName: ''
  }
  versionDialogVisible.value = true
}

const onFileChange = (_file: UploadFile, files: UploadFiles) => {
  if (files.length > 0 && files[0].raw) {
    selectedFile.value = files[0].raw
    versionForm.value.fileName = files[0].name
  } else {
    selectedFile.value = null
    versionForm.value.fileName = ''
  }
}

const handleVersionSubmit = async () => {
  if (versionEditId.value) {
    if (!versionForm.value.platform?.trim()) {
      ElMessage.warning('请选择平台')
      return
    }
    versionSubmitting.value = true
    try {
      await updateVersion(versionEditId.value, {
        version_name: versionForm.value.version_name || undefined,
        release_notes: versionForm.value.release_notes || undefined,
        platform: versionForm.value.platform?.trim() || undefined
      })
      ElMessage.success('更新成功')
      versionDialogVisible.value = false
      fetchVersions()
    } catch (err: any) {
      const msg = err?.response?.data?.detail || err?.message || '更新失败'
      ElMessage.error(typeof msg === 'string' ? msg : JSON.stringify(msg))
    } finally {
      versionSubmitting.value = false
    }
  } else {
    if (!versionForm.value.version_code.trim()) {
      ElMessage.warning('请输入版本号')
      return
    }
    if (!selectedFile.value) {
      ElMessage.warning('请选择安装包文件')
      return
    }
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('version_code', versionForm.value.version_code.trim())
    formData.append('platform', versionForm.value.platform)
    if (versionForm.value.version_name) formData.append('version_name', versionForm.value.version_name)
    if (versionForm.value.release_notes) formData.append('release_notes', versionForm.value.release_notes)
    versionSubmitting.value = true
    versionUploadPercent.value = 0
    try {
      await createVersion(distId.value, formData, {
        onUploadProgress: (p) => { versionUploadPercent.value = p }
      })
      ElMessage.success('创建成功')
      versionDialogVisible.value = false
      fetchVersions()
    } catch (err: any) {
      const msg = err?.response?.data?.detail || err?.message || '创建失败'
      ElMessage.error(typeof msg === 'string' ? msg : JSON.stringify(msg))
    } finally {
      versionSubmitting.value = false
      versionUploadPercent.value = -1
    }
  }
}

const handleDeleteVersion = async (row: ClientVersion) => {
  await ElMessageBox.confirm(`确定删除版本 ${row.version_code}？`, '确认删除', { type: 'warning' })
  try {
    await deleteVersion(row.id)
    ElMessage.success('已删除')
    fetchVersions()
  } catch {}
}

const openUpdateFilesDialog = () => {
  updateFilesPlatform.value = ''
  updateFilesList.value = []
  updateFilesBaseUrl.value = ''
  updateFilesDialogVisible.value = true
}

const onUpdateFilesDialogOpen = () => {
  updateFilesPlatform.value = ''
  updateFilesList.value = []
  updateFilesBaseUrl.value = ''
}

const fetchUpdateFilesList = async () => {
  if (!distId.value || !updateFilesPlatform.value) return
  updateFilesLoading.value = true
  try {
    const res = await listUpdateFiles(distId.value, updateFilesPlatform.value)
    updateFilesList.value = res.data.files || []
    updateFilesBaseUrl.value = res.data.base_url || ''
  } catch {
    updateFilesList.value = []
    updateFilesBaseUrl.value = ''
  } finally {
    updateFilesLoading.value = false
  }
}

const onUpdateFileSelect = async (file: { raw?: File }) => {
  if (!file.raw || !distId.value || !updateFilesPlatform.value) return
  updateFileUploadPercent.value = 0
  try {
    await uploadUpdateFile(distId.value, updateFilesPlatform.value, file.raw, {
      onUploadProgress: (p) => { updateFileUploadPercent.value = p }
    })
    ElMessage.success('上传成功')
    await fetchUpdateFilesList()
  } catch (err: any) {
    const msg = err?.response?.data?.detail || err?.message || '上传失败'
    ElMessage.error(typeof msg === 'string' ? msg : JSON.stringify(msg))
  } finally {
    updateFileUploadPercent.value = -1
  }
}

const handleDeleteUpdateFile = async (row: UpdateFileItem) => {
  await ElMessageBox.confirm(`确定删除 ${row.name}？`, '确认删除', { type: 'warning' })
  if (!distId.value || !updateFilesPlatform.value) return
  try {
    await deleteUpdateFile(distId.value, updateFilesPlatform.value, row.key)
    ElMessage.success('已删除')
    await fetchUpdateFilesList()
  } catch {}
}

const copyUpdateUrl = (url: string) => {
  if (!url) return
  navigator.clipboard.writeText(url).then(() => ElMessage.success('已复制到剪贴板')).catch(() => ElMessage.error('复制失败'))
}

onMounted(() => {
  fetchDetail()
  fetchVersions()
})
</script>

<style scoped>
.mapping-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}
.header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}
.title-group {
  display: flex;
  align-items: center;
  gap: 15px;
}
.title-group h2 {
  margin: 0;
}
.versions-section {
  margin-top: 0;
}
.toolbar {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.tip {
  font-size: 12px;
  color: #666;
}
.file-name {
  margin-left: 8px;
  font-size: 13px;
}
.platform-readonly {
  color: #606266;
  font-size: 14px;
}
.tip-hint {
  margin-top: 4px;
  color: #909399;
}

.update-files-dialog .label {
  font-size: 13px;
  color: #606266;
}
.update-base-url-wrap {
  margin-bottom: 16px;
}
.update-base-url-wrap .label {
  display: block;
  margin-bottom: 6px;
}
.update-files-upload {
  margin-bottom: 8px;
}
</style>
