<template>
  <div class="release-page">
    <div class="release-header">
      <div>
        <h2 class="ops-page-title release-title">客户端版本</h2>
        <div class="release-summary">
          <span>全部 {{ total }}</span>
          <span>本页启用 {{ enabledRows }}</span>
          <span>强制更新 {{ forceRows }}</span>
        </div>
      </div>
      <a-button type="primary" @click="openCreate">
        <template #icon><PlusOutlined /></template>
        新增版本
      </a-button>
    </div>

    <div class="ops-card release-card">
      <div class="ops-toolbar release-toolbar">
        <a-input
          v-model:value="filter.keyword"
          class="release-search"
          placeholder="搜索版本 / Object Key / 下载地址"
          allow-clear
          @press-enter="resetAndReload"
          @change="onKeywordChange"
        />
        <a-select
          v-model:value="filter.platform"
          class="release-select"
          :options="platformOptions"
          placeholder="平台"
          allow-clear
          @change="resetAndReload"
        />
        <a-input
          v-model:value="filter.channel"
          class="release-channel"
          placeholder="渠道 stable"
          allow-clear
          @press-enter="resetAndReload"
        />
        <a-select
          v-model:value="filter.enabled"
          class="release-enabled"
          :options="enabledOptions"
          placeholder="状态"
          allow-clear
          @change="resetAndReload"
        />
        <a-button @click="reload">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="rows"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1280 }"
        @change="onTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'target'">
            <div class="target-cell">
              <strong>{{ platformLabel(record.platform) }}</strong>
              <span>{{ record.arch }} · {{ record.channel }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'version'">
            <div class="version-cell">
              <strong>{{ record.version }}</strong>
              <span v-if="record.min_supported_version">
                最低 {{ record.min_supported_version }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'source'">
            <div class="source-stack">
              <div class="source-asset">
                <a-tag :color="record.download_source === 'oss' ? 'blue' : 'gold'">
                  官网 {{ record.download_source === 'oss' ? 'OSS' : '自定义' }}
                </a-tag>
                <span>{{ assetTargetText(record, 'installer') }}</span>
              </div>
              <div class="source-asset">
                <a-tag :color="updaterAssetConfigured(record) ? 'purple' : 'default'">
                  更新 {{ updaterSourceText(record) }}
                </a-tag>
                <span>{{ assetTargetText(record, 'updater') }}</span>
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'policy'">
            <a-space size="small">
              <a-tag :color="record.enabled ? 'green' : 'default'">
                {{ record.enabled ? '启用' : '停用' }}
              </a-tag>
              <a-tag v-if="record.force_update" color="red">强更</a-tag>
            </a-space>
          </template>
          <template v-else-if="column.key === 'updated_at'">
            {{ formatDate(record.updated_at) }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <div class="table-actions-row" style="justify-content: flex-end">
              <a-tooltip title="复制最终下载地址">
                <a-button
                  type="text"
                  shape="circle"
                  size="small"
                  class="action-btn"
                  @click="copyDownloadURL(record)"
                >
                  <LinkOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip title="编辑">
                <a-button
                  type="text"
                  shape="circle"
                  size="small"
                  class="action-btn action-edit"
                  @click="openEdit(record)"
                >
                  <EditOutlined />
                </a-button>
              </a-tooltip>
              <a-tooltip :title="record.enabled ? '停用' : '启用'">
                <a-switch
                  size="small"
                  :checked="record.enabled"
                  :loading="statusLoadingId === record.id"
                  @change="onEnabledSwitchChange(record, $event)"
                />
              </a-tooltip>
              <a-tooltip title="删除">
                <a-popconfirm title="确认删除该客户端版本配置？" @confirm="deleteRelease(record)">
                  <a-button
                    type="text"
                    shape="circle"
                    size="small"
                    class="action-btn action-delete"
                  >
                    <DeleteOutlined />
                  </a-button>
                </a-popconfirm>
              </a-tooltip>
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <a-drawer
      v-model:open="drawerOpen"
      :title="editingRow ? '编辑客户端版本' : '新增客户端版本'"
      width="620"
      :destroy-on-close="true"
      @close="closeDrawer"
    >
      <a-form layout="vertical" :model="form">
        <div class="form-grid">
          <a-form-item label="平台" required>
            <a-select v-model:value="form.platform" :options="platformOptions" />
          </a-form-item>
          <a-form-item label="架构" required>
            <a-select v-model:value="form.arch" :options="archOptions" />
          </a-form-item>
        </div>
        <div class="form-grid">
          <a-form-item label="渠道" required>
            <a-input v-model:value="form.channel" placeholder="stable" />
          </a-form-item>
          <a-form-item label="版本号" required>
            <a-input v-model:value="form.version" placeholder="0.1.0" />
          </a-form-item>
        </div>
        <a-form-item label="最低支持版本">
          <a-input v-model:value="form.min_supported_version" placeholder="低于该版本将强制更新" />
        </a-form-item>

        <section class="asset-section">
          <div class="asset-section-head">
            <div>
              <h3>官网安装包</h3>
              <p>installer</p>
            </div>
          </div>
          <a-form-item label="下载来源" required>
            <a-segmented v-model:value="form.download_source" :options="sourceOptions" />
          </a-form-item>
          <template v-if="form.download_source === 'oss'">
            <a-form-item label="上传安装包" required>
              <a-upload
                :before-upload="beforeUploadInstallerPackage"
                :show-upload-list="false"
                accept=".dmg,.pkg,.exe,.msi,.zip,.AppImage,.appimage,.deb,.rpm,.tar.gz,.tgz"
              >
                <a-button :loading="uploadButtonLoading('installer')" :disabled="uploading">
                  <template #icon><UploadOutlined /></template>
                  {{ uploadButtonText('installer') }}
                </a-button>
              </a-upload>
              <div v-if="uploading" class="upload-progress">
                <a-progress
                  :percent="uploadProgress ?? 0"
                  :status="uploadStage === 'verifying' ? 'active' : 'normal'"
                  size="small"
                />
                <span>{{ uploadProgressText('installer') }}</span>
              </div>
              <div v-if="form.file_name" class="upload-result">
                <strong>{{ form.file_name }}</strong>
                <span>{{ formatBytes(form.file_size_bytes) }}</span>
                <a v-if="canCopyFormDownloadURL" href="#" @click.prevent="copyFormDownloadURL">
                  复制下载地址
                </a>
              </div>
            </a-form-item>
            <a-form-item label="OSS Object Key">
              <a-input
                v-model:value="form.oss_object_key"
                placeholder="上传后自动生成，可手动填已有对象作为兜底"
              />
            </a-form-item>
          </template>
          <a-form-item v-else label="自定义下载地址" required>
            <a-input
              v-model:value="form.custom_download_url"
              placeholder="https://download.example.com/desktop/app.exe"
            />
          </a-form-item>

          <div class="form-grid">
            <a-form-item label="文件名">
              <a-input v-model:value="form.file_name" placeholder="可选" />
            </a-form-item>
            <a-form-item label="文件大小 Bytes">
              <a-input-number
                v-model:value="form.file_size_bytes"
                :min="0"
                style="width: 100%"
                placeholder="可选"
              />
            </a-form-item>
          </div>
          <a-form-item label="SHA256">
            <a-input v-model:value="form.sha256" placeholder="64 位十六进制，可选" />
          </a-form-item>
        </section>

        <section class="asset-section">
          <div class="asset-section-head">
            <div>
              <h3>自动更新包</h3>
              <p>updater</p>
            </div>
            <a-button size="small" @click="reuseInstallerForUpdater">复用官网包</a-button>
          </div>
          <a-form-item label="更新来源">
            <a-segmented
              v-model:value="form.updater_download_source"
              :options="updaterSourceOptions"
            />
          </a-form-item>
          <template v-if="form.updater_download_source === 'oss'">
            <a-form-item label="上传更新包">
              <a-upload
                :before-upload="beforeUploadUpdaterPackage"
                :show-upload-list="false"
                accept=".zip,.exe,.AppImage,.appimage"
              >
                <a-button :loading="uploadButtonLoading('updater')" :disabled="updaterUploading">
                  <template #icon><UploadOutlined /></template>
                  {{ uploadButtonText('updater') }}
                </a-button>
              </a-upload>
              <div v-if="updaterUploading" class="upload-progress">
                <a-progress
                  :percent="updaterUploadProgress ?? 0"
                  :status="updaterUploadStage === 'verifying' ? 'active' : 'normal'"
                  size="small"
                />
                <span>{{ uploadProgressText('updater') }}</span>
              </div>
              <div v-if="form.updater_file_name" class="upload-result">
                <strong>{{ form.updater_file_name }}</strong>
                <span>{{ formatBytes(form.updater_file_size_bytes) }}</span>
              </div>
            </a-form-item>
            <a-form-item label="更新包 OSS Object Key">
              <a-input
                v-model:value="form.updater_oss_object_key"
                placeholder="可复用官网包 Object Key，也可上传后自动生成"
              />
            </a-form-item>
          </template>
          <a-form-item
            v-else-if="form.updater_download_source === 'custom'"
            label="更新包自定义地址"
          >
            <a-input
              v-model:value="form.updater_custom_download_url"
              placeholder="https://download.example.com/desktop/app.zip"
            />
          </a-form-item>
          <a-alert v-else type="info" show-icon message="复用官网安装包" />

          <div v-if="form.updater_download_source !== ''" class="form-grid">
            <a-form-item label="更新包文件名">
              <a-input v-model:value="form.updater_file_name" placeholder="可选" />
            </a-form-item>
            <a-form-item label="更新包大小 Bytes">
              <a-input-number
                v-model:value="form.updater_file_size_bytes"
                :min="0"
                style="width: 100%"
                placeholder="可选"
              />
            </a-form-item>
          </div>
          <a-form-item v-if="form.updater_download_source !== ''" label="更新包 SHA256" required>
            <a-input v-model:value="form.updater_sha256" placeholder="64 位十六进制" />
          </a-form-item>
        </section>

        <a-form-item label="发布说明">
          <a-textarea v-model:value="form.release_notes" :rows="4" placeholder="可选" />
        </a-form-item>
        <div class="switch-row">
          <a-checkbox v-model:checked="form.force_update">强制更新</a-checkbox>
          <a-checkbox v-model:checked="form.enabled">启用该版本</a-checkbox>
        </div>
      </a-form>

      <template #footer>
        <div class="drawer-footer">
          <a-button @click="closeDrawer">取消</a-button>
          <a-button type="primary" :loading="saving" @click="submitForm">保存</a-button>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import {
  DeleteOutlined,
  EditOutlined,
  LinkOutlined,
  PlusOutlined,
  ReloadOutlined,
  UploadOutlined,
} from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref, watch } from 'vue'

import { copyTextToClipboard } from '@/lib/clipboard'
import {
  archOptions,
  desktopClientReleaseApi,
  platformLabel,
  platformOptions,
  type DesktopClientRelease,
  type DesktopClientReleaseUploadProgress,
  type DesktopReleaseArch,
  type DesktopReleasePlatform,
  type DesktopReleaseSource,
} from '@/lib/desktop-client-releases'
import { showOpsError } from '@/lib/errors'

const enabledOptions = [
  { label: '启用', value: 'true' },
  { label: '停用', value: 'false' },
]

const sourceOptions = [
  { label: 'OSS 自动地址', value: 'oss' },
  { label: '自定义地址', value: 'custom' },
]

const updaterSourceOptions = [
  { label: '复用/不单独配置', value: '' },
  { label: 'OSS 自动地址', value: 'oss' },
  { label: '自定义地址', value: 'custom' },
]

const columns = [
  { title: '目标', key: 'target', width: 190 },
  { title: '版本', key: 'version', width: 170 },
  { title: '下载来源', key: 'source', width: 420 },
  { title: '策略', key: 'policy', width: 150 },
  { title: '更新时间', key: 'updated_at', width: 180 },
  { title: '操作', key: 'actions', width: 190, align: 'right' as const },
]

const filter = reactive({
  keyword: '',
  platform: undefined as string | undefined,
  channel: '',
  enabled: undefined as string | undefined,
})

const rows = ref<DesktopClientRelease[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const statusLoadingId = ref<number | null>(null)
const uploading = ref(false)
const updaterUploading = ref(false)
const uploadProgress = ref<number | null>(null)
const updaterUploadProgress = ref<number | null>(null)
const uploadStage = ref<DesktopClientReleaseUploadProgress['stage'] | null>(null)
const updaterUploadStage = ref<DesktopClientReleaseUploadProgress['stage'] | null>(null)
const uploadMessage = ref<string | null>(null)
const updaterUploadMessage = ref<string | null>(null)

const enabledRows = computed(() => rows.value.filter((row) => row.enabled).length)
const forceRows = computed(() => rows.value.filter((row) => row.force_update).length)
const pagination = computed<TablePaginationConfig>(() => ({
  current: page.value,
  pageSize: size.value,
  total: total.value,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
}))

let keywordTimer: number | null = null

function onKeywordChange() {
  if (keywordTimer) window.clearTimeout(keywordTimer)
  keywordTimer = window.setTimeout(() => {
    resetAndReload()
  }, 300)
}

function resetAndReload() {
  page.value = 1
  void reload()
}

async function reload() {
  loading.value = true
  try {
    const result = await desktopClientReleaseApi.list({
      keyword: filter.keyword || undefined,
      platform: filter.platform || undefined,
      channel: filter.channel || undefined,
      enabled: filter.enabled || undefined,
      page: page.value,
      size: size.value,
    })
    rows.value = result.items
    total.value = result.total
  } catch (error) {
    showOpsError(error)
  } finally {
    loading.value = false
  }
}

function onTableChange(pag: TablePaginationConfig) {
  page.value = pag.current ?? 1
  size.value = pag.pageSize ?? 20
  void reload()
}

const drawerOpen = ref(false)
const saving = ref(false)
const editingRow = ref<DesktopClientRelease | null>(null)
const form = reactive({
  platform: 'darwin' as DesktopReleasePlatform,
  arch: 'universal' as DesktopReleaseArch,
  channel: 'stable',
  version: '',
  min_supported_version: '',
  download_source: 'oss' as DesktopReleaseSource,
  oss_object_key: '',
  custom_download_url: '',
  download_url: '',
  file_name: '',
  file_size_bytes: undefined as number | undefined,
  sha256: '',
  updater_download_source: '' as '' | DesktopReleaseSource,
  updater_oss_object_key: '',
  updater_custom_download_url: '',
  updater_file_name: '',
  updater_file_size_bytes: undefined as number | undefined,
  updater_sha256: '',
  release_notes: '',
  force_update: false,
  enabled: true,
})
const canCopyFormDownloadURL = computed(
  () => Boolean(editingRow.value?.id) || Boolean(form.download_url.trim()),
)

watch(
  () => form.download_source,
  (source) => {
    if (source === 'oss') {
      form.custom_download_url = ''
    } else {
      form.oss_object_key = ''
      form.download_url = ''
    }
  },
)

watch(
  () => form.updater_download_source,
  (source) => {
    if (source === 'oss') {
      form.updater_custom_download_url = ''
    } else if (source === 'custom') {
      form.updater_oss_object_key = ''
    } else {
      clearUpdaterAsset()
    }
  },
)

function resetForm() {
  form.platform = 'darwin'
  form.arch = 'universal'
  form.channel = 'stable'
  form.version = ''
  form.min_supported_version = ''
  form.download_source = 'oss'
  form.oss_object_key = ''
  form.custom_download_url = ''
  form.download_url = ''
  form.file_name = ''
  form.file_size_bytes = undefined
  form.sha256 = ''
  clearUpdaterAsset()
  form.release_notes = ''
  form.force_update = false
  form.enabled = true
  editingRow.value = null
}

function openCreate() {
  resetForm()
  drawerOpen.value = true
}

function openEdit(row: DesktopClientRelease) {
  editingRow.value = row
  form.platform = row.platform
  form.arch = row.arch
  form.channel = row.channel
  form.version = row.version
  form.min_supported_version = row.min_supported_version ?? ''
  form.download_source = row.download_source
  form.oss_object_key = row.oss_object_key ?? ''
  form.custom_download_url = row.custom_download_url ?? ''
  form.download_url = row.download_url ?? ''
  form.file_name = row.file_name ?? ''
  form.file_size_bytes = row.file_size_bytes ?? undefined
  form.sha256 = row.sha256 ?? ''
  form.updater_download_source = row.updater_download_source ?? ''
  form.updater_oss_object_key = row.updater_oss_object_key ?? ''
  form.updater_custom_download_url = row.updater_custom_download_url ?? ''
  form.updater_file_name = row.updater_file_name ?? ''
  form.updater_file_size_bytes = row.updater_file_size_bytes ?? undefined
  form.updater_sha256 = row.updater_sha256 ?? ''
  form.release_notes = row.release_notes ?? ''
  form.force_update = row.force_update
  form.enabled = row.enabled
  drawerOpen.value = true
}

function closeDrawer() {
  drawerOpen.value = false
}

async function beforeUploadReleasePackage(file: File, kind: 'installer' | 'updater') {
  if (!form.version.trim()) {
    message.warning('请先填写最新版本')
    return false
  }
  if (kind === 'installer') {
    uploading.value = true
    uploadProgress.value = 0
    uploadStage.value = 'hashing'
    uploadMessage.value = null
  } else {
    updaterUploading.value = true
    updaterUploadProgress.value = 0
    updaterUploadStage.value = 'hashing'
    updaterUploadMessage.value = null
  }
  try {
    const result = await desktopClientReleaseApi.uploadOSS(file, {
      platform: form.platform,
      arch: form.arch,
      channel: form.channel.trim() || 'stable',
      version: form.version.trim(),
      kind,
      onProgress(progress) {
        if (typeof progress.percent !== 'number') return
        if (kind === 'installer') {
          uploadProgress.value = progress.percent
          uploadStage.value = progress.stage ?? null
          uploadMessage.value = progress.message ?? null
        } else {
          updaterUploadProgress.value = progress.percent
          updaterUploadStage.value = progress.stage ?? null
          updaterUploadMessage.value = progress.message ?? null
        }
      },
    })
    if (kind === 'installer') {
      form.oss_object_key = result.oss_object_key
      form.download_url = ''
      form.file_name = result.file_name
      form.file_size_bytes = result.file_size_bytes
      form.sha256 = result.sha256
    } else {
      form.updater_download_source = 'oss'
      form.updater_oss_object_key = result.oss_object_key
      form.updater_custom_download_url = ''
      form.updater_file_name = result.file_name
      form.updater_file_size_bytes = result.file_size_bytes
      form.updater_sha256 = result.sha256
    }
    message.success(kind === 'installer' ? '安装包已上传到 OSS' : '自动更新包已上传到 OSS')
  } catch (error) {
    showOpsError(error)
  } finally {
    uploading.value = false
    updaterUploading.value = false
    uploadProgress.value = null
    updaterUploadProgress.value = null
    uploadStage.value = null
    updaterUploadStage.value = null
    uploadMessage.value = null
    updaterUploadMessage.value = null
  }
  return false
}

function uploadButtonText(kind: 'installer' | 'updater') {
  const isUploading = kind === 'installer' ? uploading.value : updaterUploading.value
  const progress = kind === 'installer' ? uploadProgress.value : updaterUploadProgress.value
  const stage = kind === 'installer' ? uploadStage.value : updaterUploadStage.value
  const hasUploaded =
    kind === 'installer' ? Boolean(form.oss_object_key) : Boolean(form.updater_oss_object_key)
  if (isUploading && stage === 'hashing' && typeof progress === 'number') {
    return `计算 SHA256 ${progress}%`
  }
  if (isUploading && stage === 'signing') {
    return '获取直传地址...'
  }
  if (isUploading && stage === 'uploading' && typeof progress === 'number' && progress < 100) {
    return `上传中 ${progress}%`
  }
  if (isUploading && (stage === 'verifying' || progress === 100)) {
    return '确认上传...'
  }
  if (isUploading) {
    return '准备上传...'
  }
  return hasUploaded ? '重新上传' : '选择文件并上传'
}

function uploadProgressText(kind: 'installer' | 'updater') {
  const progress = kind === 'installer' ? uploadProgress.value : updaterUploadProgress.value
  const stage = kind === 'installer' ? uploadStage.value : updaterUploadStage.value
  const message = kind === 'installer' ? uploadMessage.value : updaterUploadMessage.value
  if (message) return `${message} ${progress ?? 0}%`
  if (stage === 'hashing') return `正在计算 SHA256 ${progress ?? 0}%`
  if (stage === 'signing') return '正在获取 OSS 直传地址'
  if (stage === 'uploading') return `正在上传 ${progress ?? 0}%`
  if (stage === 'verifying') return '服务端正在确认文件完整性'
  if (stage === 'complete') return '上传完成'
  return '准备上传'
}

function uploadButtonLoading(kind: 'installer' | 'updater') {
  return kind === 'installer' ? uploading.value : updaterUploading.value
}

function beforeUploadInstallerPackage(file: File) {
  return beforeUploadReleasePackage(file, 'installer')
}

function beforeUploadUpdaterPackage(file: File) {
  return beforeUploadReleasePackage(file, 'updater')
}

function clearUpdaterAsset() {
  form.updater_download_source = ''
  form.updater_oss_object_key = ''
  form.updater_custom_download_url = ''
  form.updater_file_name = ''
  form.updater_file_size_bytes = undefined
  form.updater_sha256 = ''
}

function reuseInstallerForUpdater() {
  form.updater_download_source = form.download_source
  form.updater_oss_object_key = form.download_source === 'oss' ? form.oss_object_key : ''
  form.updater_custom_download_url =
    form.download_source === 'custom' ? form.custom_download_url : ''
  form.updater_file_name = form.file_name
  form.updater_file_size_bytes = form.file_size_bytes
  form.updater_sha256 = form.sha256
  message.success('已复用官网安装包配置')
}

async function submitForm() {
  if (!form.version.trim()) {
    message.warning('请输入最新版本')
    return
  }
  if (form.download_source === 'oss' && !form.oss_object_key.trim()) {
    message.warning('请输入 OSS Object Key')
    return
  }
  if (form.download_source === 'custom' && !form.custom_download_url.trim()) {
    message.warning('请输入自定义下载地址')
    return
  }
  if (form.updater_download_source === 'oss' && !form.updater_oss_object_key.trim()) {
    message.warning('请输入更新包 OSS Object Key')
    return
  }
  if (form.updater_download_source === 'custom' && !form.updater_custom_download_url.trim()) {
    message.warning('请输入更新包自定义地址')
    return
  }
  if (form.updater_download_source !== '' && !form.updater_sha256.trim()) {
    message.warning('请输入更新包 SHA256')
    return
  }

  saving.value = true
  try {
    const payload = {
      platform: form.platform,
      arch: form.arch,
      channel: form.channel.trim() || 'stable',
      version: form.version.trim(),
      min_supported_version: nullableText(form.min_supported_version),
      download_source: form.download_source,
      oss_object_key: form.download_source === 'oss' ? nullableText(form.oss_object_key) : null,
      custom_download_url:
        form.download_source === 'custom' ? nullableText(form.custom_download_url) : null,
      file_name: nullableText(form.file_name),
      file_size_bytes: form.file_size_bytes ?? null,
      sha256: nullableText(form.sha256),
      updater_download_source: form.updater_download_source || null,
      updater_oss_object_key:
        form.updater_download_source === 'oss' ? nullableText(form.updater_oss_object_key) : null,
      updater_custom_download_url:
        form.updater_download_source === 'custom'
          ? nullableText(form.updater_custom_download_url)
          : null,
      updater_file_name:
        form.updater_download_source !== '' ? nullableText(form.updater_file_name) : null,
      updater_file_size_bytes:
        form.updater_download_source !== '' ? (form.updater_file_size_bytes ?? null) : null,
      updater_sha256:
        form.updater_download_source !== '' ? nullableText(form.updater_sha256) : null,
      release_notes: nullableText(form.release_notes),
      force_update: form.force_update,
      enabled: form.enabled,
    }
    if (editingRow.value) {
      await desktopClientReleaseApi.update(editingRow.value.id, payload)
      message.success('已保存客户端版本')
    } else {
      await desktopClientReleaseApi.create(payload)
      message.success('已新增客户端版本')
    }
    drawerOpen.value = false
    resetForm()
    void reload()
  } catch (error) {
    showOpsError(error)
  } finally {
    saving.value = false
  }
}

function nullableText(value: string): string | null {
  const trimmed = value.trim()
  return trimmed ? trimmed : null
}

function updaterAssetConfigured(row: DesktopClientRelease): boolean {
  return Boolean(row.updater_download_source)
}

function updaterSourceText(row: DesktopClientRelease): string {
  if (!row.updater_download_source) {
    return '复用官网'
  }
  return row.updater_download_source === 'oss' ? 'OSS' : '自定义'
}

function assetTargetText(row: DesktopClientRelease, kind: 'installer' | 'updater'): string {
  if (kind === 'installer' || !row.updater_download_source) {
    return row.download_source === 'oss'
      ? (row.oss_object_key ?? '未配置')
      : (row.custom_download_url ?? '未配置')
  }
  return row.updater_download_source === 'oss'
    ? (row.updater_oss_object_key ?? '未配置')
    : (row.updater_custom_download_url ?? '未配置')
}

async function setEnabled(row: DesktopClientRelease, enabled: boolean) {
  statusLoadingId.value = row.id
  try {
    const next = await desktopClientReleaseApi.setEnabled(row.id, enabled)
    Object.assign(row, next)
    message.success(enabled ? '已启用' : '已停用')
  } catch (error) {
    showOpsError(error)
  } finally {
    statusLoadingId.value = null
  }
}

function onEnabledSwitchChange(row: DesktopClientRelease, checked: unknown) {
  void setEnabled(row, Boolean(checked))
}

async function deleteRelease(row: DesktopClientRelease) {
  try {
    await desktopClientReleaseApi.delete(row.id)
    message.success('已删除')
    void reload()
  } catch (error) {
    showOpsError(error)
  }
}

async function copyDownloadURL(row: DesktopClientRelease) {
  let downloadURL = ''
  try {
    const result = await desktopClientReleaseApi.resolveDownloadURL(row.id)
    downloadURL = result.download_url
  } catch (error) {
    showOpsError(error)
    return
  }

  try {
    await copyTextToClipboard(downloadURL)
    message.success('下载地址已复制')
  } catch {
    message.error('复制失败，请在接口返回中手动复制下载地址')
  }
}

async function copyFormDownloadURL() {
  if (form.download_url) {
    try {
      await copyTextToClipboard(form.download_url)
      message.success('下载地址已复制')
    } catch {
      message.error('复制失败，请手动复制下载地址')
    }
    return
  }
  if (!editingRow.value?.id) return
  await copyDownloadURL(editingRow.value)
}

function formatDate(value: string | null | undefined): string {
  return value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '—'
}

function formatBytes(value: number | null | undefined): string {
  if (!value) return '0 B'
  if (value < 1024) return `${value} B`
  if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
  if (value < 1024 * 1024 * 1024) return `${(value / 1024 / 1024).toFixed(1)} MB`
  return `${(value / 1024 / 1024 / 1024).toFixed(1)} GB`
}

onMounted(() => {
  void reload()
})
</script>

<style scoped>
.release-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.release-header {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
}

.release-title {
  margin-bottom: 8px;
}

.release-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  color: #64748b;
  font-size: 13px;
}

.release-summary span {
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: #fff;
  padding: 4px 8px;
}

.release-card {
  padding-top: 20px;
}

.release-toolbar {
  margin-bottom: 18px;
}

.release-search {
  width: 320px;
}

.release-select,
.release-enabled {
  width: 140px;
}

.release-channel {
  width: 150px;
}

.target-cell,
.version-cell {
  display: flex;
  min-width: 0;
  flex-direction: column;
  gap: 4px;
}

.target-cell strong,
.version-cell strong {
  color: #0f172a;
  font-weight: 750;
}

.target-cell span,
.version-cell span {
  color: #94a3b8;
  font-size: 12px;
}

.source-stack {
  display: flex;
  min-width: 0;
  flex-direction: column;
  gap: 8px;
}

.source-asset {
  display: grid;
  min-width: 0;
  grid-template-columns: auto minmax(0, 1fr);
  align-items: center;
  gap: 6px;
}

.source-asset span {
  overflow: hidden;
  max-width: 360px;
  color: #64748b;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.asset-section {
  margin: 16px 0;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 14px 14px 4px;
}

.asset-section-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

.asset-section-head h3 {
  margin: 0 0 4px;
  color: #0f172a;
  font-size: 15px;
  font-weight: 750;
  line-height: 1.3;
}

.asset-section-head p {
  margin: 0;
  color: #64748b;
  font-size: 12px;
  line-height: 1.5;
}

.form-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  gap: 14px;
}

.switch-row {
  display: flex;
  gap: 24px;
  margin-top: 4px;
}

.upload-result {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
  color: #64748b;
  font-size: 12px;
}

.upload-progress {
  display: grid;
  max-width: 360px;
  gap: 4px;
  margin-top: 10px;
}

.upload-progress span {
  color: #64748b;
  font-size: 12px;
}

.upload-result strong {
  color: #0f172a;
  font-weight: 750;
}

.upload-result a {
  color: #1677ff;
  font-weight: 700;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

@media (max-width: 768px) {
  .release-header {
    align-items: stretch;
    flex-direction: column;
  }

  .release-search,
  .release-select,
  .release-channel,
  .release-enabled {
    width: 100%;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }
}
</style>
