<script setup lang="ts">
/**
 * OSS 配置：分厂商 Tab，保存 / 测试连接 / 删除。
 */
import { computed, reactive, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useDialog, useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import { adminCreate, adminDelete, adminList, adminUpdate, normalizeAdminList, testOssConfig } from '@/api'

type StorageType = 'local' | 'aliyun' | 'qcloud' | 'qiniu'

const TABS: { id: StorageType, label: string }[] = [
  { id: 'local', label: '本地' },
  { id: 'aliyun', label: '阿里云' },
  { id: 'qcloud', label: '腾讯云' },
  { id: 'qiniu', label: '七牛' },
]

const toast = useToast()
const dialog = useDialog()
const { guardAdmin } = useAdminGuard()
const loading = ref(false)
const submitting = ref(false)
const tab = ref(0)
const configs = ref<Record<string, unknown>[]>([])

const form = reactive({
  id: '' as string | number,
  name: '',
  storageType: 'local' as string,
  isActive: 1 as number,
  accessKeyId: '',
  accessKeySecret: '',
  secretId: '',
  secretKey: '',
  accessKey: '',
  endpoint: '',
  region: '',
  bucket: '',
  domain: '',
})

const currentType = computed(() => TABS[tab.value]?.id || 'local')

function fillForm(row?: Record<string, unknown>) {
  const type = currentType.value
  form.id = ''
  form.accessKeyId = ''
  form.accessKeySecret = ''
  form.secretId = ''
  form.secretKey = ''
  form.accessKey = ''
  form.endpoint = ''
  form.region = ''
  form.bucket = ''
  form.domain = ''
  form.storageType = type
  form.isActive = 1
  form.name = `${TABS[tab.value]?.label || type} 存储`
  if (!row) return
  form.id = (row.id as string | number) || ''
  form.name = String(row.name || form.name)
  form.storageType = String(row.storageType || type)
  form.isActive = row.isActive === 0 || row.isActive === false ? 0 : 1
  form.accessKeyId = String(row.accessKeyId || '')
  form.accessKeySecret = row.accessKeySecret === '***' ? '' : String(row.accessKeySecret || '')
  form.secretId = String(row.secretId || '')
  form.secretKey = row.secretKey === '***' ? '' : String(row.secretKey || '')
  form.accessKey = String(row.accessKey || '')
  form.endpoint = String(row.endpoint || '')
  form.region = String(row.region || '')
  form.bucket = String(row.bucket || '')
  form.domain = String(row.domain || '')
}

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    configs.value = normalizeAdminList(await adminList('oss-configs'))
    const hit = configs.value.find(c => String(c.storageType) === currentType.value)
    fillForm(hit)
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

function onTabChange() {
  const hit = configs.value.find(c => String(c.storageType) === currentType.value)
  fillForm(hit)
}

onShow(load)

async function onSave() {
  submitting.value = true
  try {
    const { id, ...rest } = form
    const payload = { ...rest }
    if (id) await adminUpdate('oss-configs', id, payload)
    else await adminCreate('oss-configs', payload)
    toast.success('已保存')
    load()
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}

async function onTest() {
  if (!form.id) {
    toast.show('请先保存配置')
    return
  }
  try {
    await testOssConfig(form.id as string | number)
    toast.success('连接成功')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '测试失败')
  }
}

function onDelete() {
  if (!form.id) return
  dialog.confirm({ title: '确认删除', msg: '确定删除该 OSS 配置吗？' }).then(async () => {
    try {
      await adminDelete('oss-configs', form.id as string | number)
      toast.success('已删除')
      load()
    }
    catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : '删除失败')
    }
  }).catch(() => {})
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar title="OSS 配置" show-back />
    <view class="page-pad">
      <wd-tabs v-model="tab" @change="onTabChange">
        <wd-tab v-for="t in TABS" :key="t.id" :title="t.label" />
      </wd-tabs>
      <view class="admin-card form-card">
        <wd-input v-model="form.name" label="名称" clearable />
        <view class="switch-row">
          <text>启用</text>
          <wd-switch :model-value="!!form.isActive" @change="(v: boolean) => form.isActive = v ? 1 : 0" />
        </view>
        <template v-if="currentType === 'aliyun'">
          <wd-input v-model="form.accessKeyId" label="AccessKeyId" clearable />
          <wd-input v-model="form.accessKeySecret" label="AccessKeySecret" clearable />
          <wd-input v-model="form.endpoint" label="Endpoint" clearable />
          <wd-input v-model="form.bucket" label="Bucket" clearable />
          <wd-input v-model="form.domain" label="Domain" clearable />
        </template>
        <template v-else-if="currentType === 'qcloud'">
          <wd-input v-model="form.secretId" label="SecretId" clearable />
          <wd-input v-model="form.secretKey" label="SecretKey" clearable />
          <wd-input v-model="form.region" label="Region" clearable />
          <wd-input v-model="form.bucket" label="Bucket" clearable />
          <wd-input v-model="form.domain" label="Domain" clearable />
        </template>
        <template v-else-if="currentType === 'qiniu'">
          <wd-input v-model="form.accessKey" label="AccessKey" clearable />
          <wd-input v-model="form.secretKey" label="SecretKey" clearable />
          <wd-input v-model="form.bucket" label="Bucket" clearable />
          <wd-input v-model="form.region" label="Region" clearable />
          <wd-input v-model="form.domain" label="Domain" clearable />
        </template>
        <template v-else>
          <text class="hint text-art-muted">本地存储无需额外密钥，仅需启用即可。</text>
        </template>
        <view class="actions">
          <wd-button type="primary" :loading="submitting" @click="onSave">保存</wd-button>
          <wd-button plain @click="onTest">测试连接</wd-button>
          <wd-button v-if="form.id" type="warning" plain @click="onDelete">删除</wd-button>
        </view>
      </view>
      <wd-loading v-if="loading" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.form-card { padding: 24rpx; margin-top: 20rpx; }
.switch-row {
  display: flex; justify-content: space-between; align-items: center;
  padding: 20rpx 0; color: rgb(var(--art-text));
}
.hint { font-size: 24rpx; display: block; margin: 16rpx 0; }
.actions { display: flex; flex-wrap: wrap; gap: 12rpx; margin-top: 24rpx; }
</style>
