e265c188f7
- 本地代理回填兼容旧版全局 proxy_url,补报成功后重拉服务端快照 - 创建任务前检查服务端代理,缺失时弹窗拦截并引导配置 - 商标查询失败的真实原因写入结果原因列,不再只显示查询失败
685 lines
24 KiB
Vue
685 lines
24 KiB
Vue
<template>
|
||
<div class="secret-settings-body">
|
||
<section v-for="module in modules" :key="module.moduleKey" class="secret-card">
|
||
<div class="secret-card-head">
|
||
<div>
|
||
<div class="secret-card-title">{{ module.moduleLabel }}</div>
|
||
<div class="secret-card-desc">{{ descriptionOf(module.moduleKey) }}</div>
|
||
</div>
|
||
<button
|
||
v-if="snapshotOf(module.moduleKey).exists"
|
||
type="button"
|
||
class="link-danger"
|
||
:disabled="busy"
|
||
@click="clearModule(module.moduleKey as ApiSecretModuleKey)"
|
||
>
|
||
清空
|
||
</button>
|
||
</div>
|
||
|
||
<input
|
||
v-model="moduleStates[module.moduleKey].input"
|
||
class="secret-input"
|
||
type="password"
|
||
:placeholder="placeholderOf(module.moduleKey)"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="busy"
|
||
/>
|
||
|
||
<div class="secret-actions">
|
||
<button
|
||
type="button"
|
||
class="check-btn"
|
||
:disabled="busy || moduleStates[module.moduleKey].checking"
|
||
@click="runCheck(module.moduleKey as ApiSecretModuleKey)"
|
||
>
|
||
{{ moduleStates[module.moduleKey].checking ? '检测中...' : (moduleStates[module.moduleKey].input.trim() ? '检测输入值(未保存)' : '检测配置密钥') }}
|
||
</button>
|
||
<span class="check-result" :class="resultClassOf(module.moduleKey)">
|
||
{{ statusTextOf(module.moduleKey) }}
|
||
</span>
|
||
</div>
|
||
</section>
|
||
|
||
<section v-if="showProxy" class="secret-card">
|
||
<div class="secret-card-head">
|
||
<div>
|
||
<div class="secret-card-title">
|
||
代理设置
|
||
<span v-if="proxyLocked" class="lock-tag">后台锁定</span>
|
||
</div>
|
||
<div class="secret-card-desc">
|
||
{{ proxyLocked
|
||
? '代理由管理员统一配置并锁定,客户端不可修改或清空;如需变更请联系管理员。'
|
||
: '供客户端任务连接代理服务,支持静态代理地址或代理服务商的提取链接。' }}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="proxy-field">
|
||
<label class="field-label" for="proxy-url">代理地址</label>
|
||
<input
|
||
id="proxy-url"
|
||
v-model="proxyUrl"
|
||
class="secret-input"
|
||
type="text"
|
||
placeholder="如 http://user:pass@host:port 或代理提取链接"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="!proxyReady || busy || proxyLocked"
|
||
@input="proxyDirty = true"
|
||
/>
|
||
</div>
|
||
|
||
<div class="retention-block">
|
||
<div class="field-label">代理模式</div>
|
||
<div class="retention-options">
|
||
<label
|
||
v-for="option in proxyModeOptions"
|
||
:key="option.value"
|
||
class="retention-option"
|
||
:class="{ 'retention-option--disabled': !proxyReady || busy || proxyLocked }"
|
||
>
|
||
<input
|
||
v-model="proxyMode"
|
||
type="radio"
|
||
:value="option.value"
|
||
:disabled="!proxyReady || busy || proxyLocked"
|
||
@change="proxyDirty = true"
|
||
/>
|
||
<span>{{ option.label }}</span>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
|
||
<div v-if="proxySupported" class="retention-block">
|
||
<div class="field-label">jikip 套餐信息(用于余量查询与预警)</div>
|
||
<div class="proxy-plan-row">
|
||
<input
|
||
v-model="proxyPlanId"
|
||
class="secret-input"
|
||
type="text"
|
||
placeholder="套餐 ID"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
/>
|
||
<input
|
||
v-model="proxyPlanUserId"
|
||
class="secret-input"
|
||
type="text"
|
||
placeholder="用户 ID"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
/>
|
||
</div>
|
||
<div class="secret-actions">
|
||
<button
|
||
type="button"
|
||
class="check-btn"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
@click="saveProxyPlanInfo"
|
||
>
|
||
{{ proxyPlanSaving ? '保存中...' : '保存套餐信息' }}
|
||
</button>
|
||
<button
|
||
v-if="proxyPlanConfigured"
|
||
type="button"
|
||
class="link-danger"
|
||
:disabled="proxyPlanSaving"
|
||
@click="clearProxyPlanInfo"
|
||
>
|
||
清除
|
||
</button>
|
||
</div>
|
||
<div class="proxy-plan-hint">
|
||
填写后,下方余量按你自己的 jikip 套餐查询;留空则显示平台默认套餐。套餐 ID / 用户 ID 在 jikip 后台「我的套餐」和「账户信息」查看。
|
||
</div>
|
||
</div>
|
||
|
||
<div class="secret-actions">
|
||
<button
|
||
type="button"
|
||
class="check-btn"
|
||
:disabled="!proxyReady || busy || proxyChecking"
|
||
@click="runProxyCheck"
|
||
>
|
||
{{ proxyChecking ? '检测中...' : (proxyUrl.trim() && proxyDirty ? '检测输入地址(未保存)' : '检测配置代理') }}
|
||
</button>
|
||
<span class="check-result" :class="proxyResultClass">
|
||
{{ proxyStatusText }}
|
||
</span>
|
||
</div>
|
||
|
||
<div class="secret-meta">
|
||
<span v-if="proxyLoading">正在读取代理配置...</span>
|
||
<span v-else-if="proxyLoadFailed">代理配置读取失败,请关闭弹窗后重试</span>
|
||
<span v-else-if="!proxySupported">代理设置仅在桌面客户端中可用</span>
|
||
<span v-else-if="balanceLoading">正在查询代理余量...</span>
|
||
<span v-else-if="balance">{{ balanceText }}</span>
|
||
<span v-else>余额查询暂不可用</span>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||
import { ElMessage } from 'element-plus'
|
||
import {
|
||
checkApiSecret,
|
||
clearApiSecret,
|
||
fetchProxyBalanceSafely,
|
||
getServerProxySnapshot,
|
||
getStoredApiSecretSnapshot,
|
||
listApiSecretModules,
|
||
loadApiSecrets,
|
||
saveApiSecret,
|
||
subscribeApiSecrets,
|
||
type ApiSecretCheckStatus,
|
||
type ApiSecretModuleKey,
|
||
type ApiSecretSnapshot,
|
||
type ServerProxySnapshot,
|
||
type UserApiSecretCheckResult,
|
||
} from '@/shared/utils/api-secret-store'
|
||
import { getPywebviewApi, type ProxyMode, type DesktopConfigUpdate } from '@/shared/bridges/pywebview'
|
||
import { deleteMyApiSecret, putMyApiSecret, fetchProxyPlan, saveProxyPlan, clearProxyPlan } from '@/shared/api/types/modules/user-secret'
|
||
import { PROXY_PLAN_CHANGED_EVENT } from '@/shared/utils/proxy-balance-alert'
|
||
|
||
const props = withDefaults(
|
||
defineProps<{
|
||
/** 是否展示代理设置区(默认展示)。 */
|
||
showProxy?: boolean
|
||
}>(),
|
||
{
|
||
showProxy: true,
|
||
},
|
||
)
|
||
|
||
type ModuleState = {
|
||
input: string
|
||
checking: boolean
|
||
result: UserApiSecretCheckResult | null
|
||
error: string
|
||
/** 最近一次检测的来源:saved=密钥配置里已保存的密钥,input=输入框里的未保存值。 */
|
||
lastCheckSource: 'saved' | 'input' | ''
|
||
}
|
||
|
||
const modules = ref(listApiSecretModules())
|
||
const moduleStates = reactive<Record<string, ModuleState>>({})
|
||
// 首次渲染即需可读:按模块清单预初始化状态(后续 refreshSnapshots 兜底补齐)
|
||
for (const module of modules.value) {
|
||
moduleStates[module.moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' }
|
||
}
|
||
const snapshots = ref<Record<string, ApiSecretSnapshot>>({})
|
||
const busy = ref(false)
|
||
|
||
/** 服务端代理状态:后台代填并锁定时客户端只读。 */
|
||
const serverProxy = ref<ServerProxySnapshot | null>(getServerProxySnapshot())
|
||
const proxyLocked = computed(() => Boolean(serverProxy.value?.locked && serverProxy.value?.exists))
|
||
|
||
const proxyUrl = ref('')
|
||
const proxyMode = ref<ProxyMode>(1)
|
||
const proxyLoading = ref(false)
|
||
const proxyLoadFailed = ref(false)
|
||
const proxyReady = ref(false)
|
||
const proxySupported = ref(false)
|
||
const proxyDirty = ref(false)
|
||
|
||
const proxyChecking = ref(false)
|
||
const proxyCheckResult = ref<UserApiSecretCheckResult | null>(null)
|
||
const proxyCheckError = ref('')
|
||
|
||
const proxyPlanId = ref('')
|
||
const proxyPlanUserId = ref('')
|
||
const proxyPlanConfigured = ref(false)
|
||
const proxyPlanLoading = ref(false)
|
||
const proxyPlanSaving = ref(false)
|
||
|
||
const proxyStatusText = computed(() => {
|
||
if (proxyChecking.value) return '正在检测...'
|
||
if (proxyCheckResult.value) {
|
||
const latency = proxyCheckResult.value.checkLatencyMs != null ? `(${proxyCheckResult.value.checkLatencyMs}ms)` : ''
|
||
if (proxyCheckResult.value.checkStatus === 'passed') return `代理连通正常${latency}`
|
||
return `${proxyCheckResult.value.checkMessage || '代理检测失败'}`
|
||
}
|
||
if (proxyCheckError.value) return proxyCheckError.value
|
||
return ''
|
||
})
|
||
|
||
const proxyResultClass = computed(() => {
|
||
const status = proxyCheckResult.value?.checkStatus
|
||
return {
|
||
'check-result--ok': status === 'passed',
|
||
'check-result--fail': status === 'failed',
|
||
'check-result--warn': status === 'error',
|
||
}
|
||
})
|
||
|
||
/** 检测代理连通性:地址有改动时检测输入值(不落库),否则检测/落库已存值并刷新状态展示。 */
|
||
async function runProxyCheck() {
|
||
if (proxyChecking.value) return
|
||
const inputValue = proxyUrl.value.trim()
|
||
const dirty = proxyDirty.value && inputValue
|
||
proxyChecking.value = true
|
||
proxyCheckError.value = ''
|
||
proxyCheckResult.value = null
|
||
try {
|
||
proxyCheckResult.value = await checkApiSecret('proxy', dirty ? inputValue : undefined)
|
||
const result = proxyCheckResult.value
|
||
if (result.checkStatus === 'failed') {
|
||
ElMessage.warning(
|
||
result.checkCode === 'insufficient_balance' ? '代理服务商余额不足,请充值或联系管理员' : (result.checkMessage || '代理不可用'),
|
||
)
|
||
} else if (result.checkStatus === 'error') {
|
||
ElMessage.warning(result.checkMessage || '暂时无法判定代理可用性')
|
||
} else {
|
||
ElMessage.success(dirty ? '输入地址连通正常(未保存)' : '代理连通正常')
|
||
}
|
||
} catch (error) {
|
||
proxyCheckError.value = error instanceof Error ? error.message : '代理检测失败'
|
||
ElMessage.error(proxyCheckError.value)
|
||
} finally {
|
||
proxyChecking.value = false
|
||
}
|
||
}
|
||
|
||
const balance = ref<{ surplus: string | null; balance: string | null } | null>(null)
|
||
const balanceLoading = ref(false)
|
||
|
||
const proxyModeOptions: Array<{ value: ProxyMode; label: string }> = [
|
||
{ value: 1, label: '白名单' },
|
||
{ value: 2, label: '账号密码' },
|
||
]
|
||
|
||
const MODULE_DESCRIPTIONS: Record<string, string> = {
|
||
'appearance-patent': '仅用于外观专利检测,保存在服务端并绑定当前账号。',
|
||
'similar-asin': '仅用于货源查询,保存在服务端并绑定当前账号。',
|
||
}
|
||
|
||
const balanceText = computed(() => {
|
||
if (!balance.value) return ''
|
||
const surplus = balance.value.surplus ?? '-'
|
||
const amount = balance.value.balance ?? '-'
|
||
return `套餐IP余量:${surplus} · 账户余额:${amount}`
|
||
})
|
||
|
||
function ensureModuleState(moduleKey: string) {
|
||
if (!moduleStates[moduleKey]) {
|
||
moduleStates[moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' }
|
||
}
|
||
return moduleStates[moduleKey]
|
||
}
|
||
|
||
function refreshSnapshots() {
|
||
modules.value = listApiSecretModules()
|
||
const next: Record<string, ApiSecretSnapshot> = {}
|
||
for (const module of modules.value) {
|
||
next[module.moduleKey] = getStoredApiSecretSnapshot(module.moduleKey as ApiSecretModuleKey)
|
||
ensureModuleState(module.moduleKey)
|
||
}
|
||
snapshots.value = next
|
||
serverProxy.value = getServerProxySnapshot()
|
||
}
|
||
|
||
function snapshotOf(moduleKey: string): ApiSecretSnapshot {
|
||
return snapshots.value[moduleKey] || getStoredApiSecretSnapshot(moduleKey as ApiSecretModuleKey)
|
||
}
|
||
|
||
function descriptionOf(moduleKey: string) {
|
||
return MODULE_DESCRIPTIONS[moduleKey] || '保存在服务端并绑定当前账号。'
|
||
}
|
||
|
||
function placeholderOf(moduleKey: string) {
|
||
const snapshot = snapshotOf(moduleKey)
|
||
if (snapshot.exists) {
|
||
return `已保存(${snapshot.masked || '****'}),输入新值可覆盖`
|
||
}
|
||
return '请输入 LLM 接口密钥'
|
||
}
|
||
|
||
const CHECK_STATUS_TEXT: Record<ApiSecretCheckStatus, string> = {
|
||
passed: '检测通过',
|
||
failed: '检测失败',
|
||
error: '暂时无法判定',
|
||
unknown: '已保存,未检测',
|
||
}
|
||
|
||
function formatTime(millis: number | null) {
|
||
if (!millis) return ''
|
||
const date = new Date(millis)
|
||
const hour = String(date.getHours()).padStart(2, '0')
|
||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||
return `${hour}:${minute}`
|
||
}
|
||
|
||
function statusTextOf(moduleKey: string) {
|
||
const state = ensureModuleState(moduleKey)
|
||
if (state.checking) return state.input.trim() ? '正在检测输入值...' : '正在检测配置密钥...'
|
||
if (state.result) {
|
||
const latency = state.result.checkLatencyMs != null ? `(${state.result.checkLatencyMs}ms)` : ''
|
||
const suffix = state.result.viaProxy === true ? ' · 经代理' : ''
|
||
const snapshot = snapshotOf(moduleKey)
|
||
// 明确展示本次检测的对象:输入值(未保存)或该用户密钥配置里保存的密钥(脱敏)
|
||
const prefix = state.lastCheckSource === 'input'
|
||
? '输入值(未保存):'
|
||
: `配置密钥${snapshot.masked ? ` ${snapshot.masked}` : ''}:`
|
||
if (state.result.checkStatus === 'passed') return `${prefix}检测通过${latency}${suffix}`
|
||
if (state.result.checkCode === 'insufficient_balance') return `${prefix}欠费:${state.result.checkMessage || '代理服务商余额不足'}${suffix}`
|
||
return `${prefix}${state.result.checkMessage || '检测失败'}${suffix}`
|
||
}
|
||
if (state.error) return state.error
|
||
const snapshot = snapshotOf(moduleKey)
|
||
if (!snapshot.exists) return '当前未保存,请填写后保存'
|
||
const status = CHECK_STATUS_TEXT[snapshot.checkStatus] || '已保存'
|
||
const time = formatTime(snapshot.checkedAt)
|
||
const message = snapshot.checkStatus === 'unknown' ? '' : `:${snapshot.checkMessage || ''}`
|
||
const masked = snapshot.masked ? `配置密钥 ${snapshot.masked} · ` : ''
|
||
return `${masked}${status}${message}${time ? ` · ${time}` : ''}`
|
||
}
|
||
|
||
function resultClassOf(moduleKey: string) {
|
||
const state = ensureModuleState(moduleKey)
|
||
const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus
|
||
return {
|
||
'check-result--ok': status === 'passed',
|
||
'check-result--fail': status === 'failed',
|
||
'check-result--warn': status === 'error',
|
||
}
|
||
}
|
||
|
||
async function runCheck(moduleKey: ApiSecretModuleKey) {
|
||
const state = ensureModuleState(moduleKey)
|
||
if (state.checking) return
|
||
state.checking = true
|
||
state.error = ''
|
||
state.result = null
|
||
const inputValue = state.input.trim()
|
||
state.lastCheckSource = inputValue ? 'input' : 'saved'
|
||
try {
|
||
// 不传 override 时服务端检测的是当前登录用户在密钥配置里保存的密钥(按 uid 绑定)
|
||
const result = await checkApiSecret(moduleKey, inputValue || undefined)
|
||
state.result = result
|
||
if (result.checkStatus === 'failed') {
|
||
ElMessage.warning(result.checkMessage || '密钥无效')
|
||
} else if (result.checkStatus === 'error') {
|
||
ElMessage.warning(result.checkMessage || '暂时无法判定密钥有效性')
|
||
} else {
|
||
ElMessage.success(inputValue ? '输入值检测通过(未保存)' : '配置密钥检测通过')
|
||
}
|
||
} catch (error) {
|
||
state.error = error instanceof Error ? error.message : '检测失败'
|
||
ElMessage.error(state.error)
|
||
} finally {
|
||
state.checking = false
|
||
refreshSnapshots()
|
||
}
|
||
}
|
||
|
||
async function clearModule(moduleKey: ApiSecretModuleKey) {
|
||
if (busy.value) return
|
||
busy.value = true
|
||
try {
|
||
await clearApiSecret(moduleKey)
|
||
const state = ensureModuleState(moduleKey)
|
||
state.input = ''
|
||
state.result = null
|
||
state.error = ''
|
||
refreshSnapshots()
|
||
ElMessage.success('已清空密钥')
|
||
} catch (error) {
|
||
ElMessage.error(error instanceof Error ? error.message : '清空失败')
|
||
} finally {
|
||
busy.value = false
|
||
}
|
||
}
|
||
|
||
function proxyUserId() {
|
||
if (typeof window === 'undefined') return '0'
|
||
return window.localStorage.getItem('uid') || '0'
|
||
}
|
||
|
||
/** 代理地址按登录用户隔离:proxy_users[uid],各自计费各自复用;
|
||
* 用户项为空(含老版本只存了全局 proxy_url 的账号)回退全局,口径与客户端任务链
|
||
* `resolve_current_proxy` 一致——否则这些账号的代理既显示不出来,也补报不到服务端。 */
|
||
function readUserProxy(config: Record<string, unknown> | null | undefined) {
|
||
const uid = proxyUserId()
|
||
if (uid !== '0') {
|
||
const users = (config?.proxy_users ?? {}) as Record<string, unknown>
|
||
const own = (users[uid] ?? {}) as Record<string, unknown>
|
||
const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
|
||
if (ownUrl) {
|
||
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
|
||
}
|
||
}
|
||
return {
|
||
url: typeof config?.proxy_url === 'string' ? config.proxy_url : '',
|
||
mode: Number(config?.proxy_mode) === 2 ? 2 : 1,
|
||
}
|
||
}
|
||
|
||
function userProxyPatch(nextProxyUrl: string, nextProxyMode: ProxyMode) {
|
||
const uid = proxyUserId()
|
||
if (uid === '0') {
|
||
return { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode }
|
||
}
|
||
const users: Record<string, unknown> = {}
|
||
users[uid] = { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode }
|
||
return { proxy_users: users }
|
||
}
|
||
|
||
async function loadProxyConfig() {
|
||
proxyLoading.value = true
|
||
proxyLoadFailed.value = false
|
||
proxyReady.value = false
|
||
proxyDirty.value = false
|
||
|
||
const api = getPywebviewApi()
|
||
proxySupported.value = Boolean(api?.read_config && api.save_config)
|
||
if (!api?.read_config || !api.save_config) {
|
||
proxyUrl.value = ''
|
||
proxyMode.value = 1
|
||
proxyLoading.value = false
|
||
return
|
||
}
|
||
|
||
try {
|
||
const config = await api.read_config()
|
||
const own = readUserProxy(config as Record<string, unknown>)
|
||
proxyUrl.value = own.url
|
||
proxyMode.value = (own.mode === 2 ? 2 : 1) as ProxyMode
|
||
proxyReady.value = true
|
||
} catch (error) {
|
||
proxyLoadFailed.value = true
|
||
ElMessage.error(error instanceof Error ? error.message : '代理配置读取失败')
|
||
} finally {
|
||
proxyLoading.value = false
|
||
}
|
||
}
|
||
|
||
/** 代理配置上报服务端(后台密钥管理观测/检测):有地址则保存、清空则删除;失败不阻断本地保存。 */
|
||
async function syncProxyToServer(url: string) {
|
||
if (proxyUserId() === '0') return
|
||
try {
|
||
if (url) {
|
||
await putMyApiSecret('proxy', url)
|
||
} else {
|
||
await deleteMyApiSecret('proxy')
|
||
}
|
||
} catch (error) {
|
||
console.warn('[api-secret] 代理配置上报失败(不影响本地任务):', error)
|
||
ElMessage.warning('代理已保存到本地,但上报后台失败')
|
||
}
|
||
}
|
||
|
||
async function loadProxyPlan() {
|
||
proxyPlanLoading.value = true
|
||
try {
|
||
const result = await fetchProxyPlan().catch((error) => {
|
||
console.warn('[api-secret] 代理套餐配置读取失败:', error)
|
||
return null
|
||
})
|
||
if (!result) return
|
||
proxyPlanId.value = result.planId || ''
|
||
proxyPlanUserId.value = result.jikipUserId || ''
|
||
proxyPlanConfigured.value = Boolean(result.configured)
|
||
} finally {
|
||
proxyPlanLoading.value = false
|
||
}
|
||
}
|
||
|
||
async function saveProxyPlanInfo() {
|
||
const planId = proxyPlanId.value.trim()
|
||
const jikipUserId = proxyPlanUserId.value.trim()
|
||
if (!planId || !jikipUserId) {
|
||
ElMessage.warning('请同时填写套餐 ID 和用户 ID')
|
||
return
|
||
}
|
||
proxyPlanSaving.value = true
|
||
try {
|
||
const result = await saveProxyPlan(planId, jikipUserId).catch((error) => {
|
||
ElMessage.error(error instanceof Error ? error.message : '套餐信息保存失败')
|
||
return null
|
||
})
|
||
if (!result) return
|
||
proxyPlanConfigured.value = Boolean(result.configured)
|
||
ElMessage.success('套餐信息已保存,余量将按你的套餐查询')
|
||
window.dispatchEvent(new Event(PROXY_PLAN_CHANGED_EVENT))
|
||
await loadBalance()
|
||
} finally {
|
||
proxyPlanSaving.value = false
|
||
}
|
||
}
|
||
|
||
async function clearProxyPlanInfo() {
|
||
if (proxyPlanSaving.value) return
|
||
proxyPlanSaving.value = true
|
||
try {
|
||
const cleared = await clearProxyPlan().then(() => true).catch((error) => {
|
||
ElMessage.error(error instanceof Error ? error.message : '套餐信息清除失败')
|
||
return false
|
||
})
|
||
if (!cleared) return
|
||
proxyPlanId.value = ''
|
||
proxyPlanUserId.value = ''
|
||
proxyPlanConfigured.value = false
|
||
ElMessage.success('已清除套餐信息,余量恢复为平台默认套餐')
|
||
window.dispatchEvent(new Event(PROXY_PLAN_CHANGED_EVENT))
|
||
await loadBalance()
|
||
} finally {
|
||
proxyPlanSaving.value = false
|
||
}
|
||
}
|
||
|
||
async function loadBalance() {
|
||
balanceLoading.value = true
|
||
try {
|
||
const result = await fetchProxyBalanceSafely()
|
||
if (result?.available) {
|
||
balance.value = { surplus: result.surplus, balance: result.balance }
|
||
} else {
|
||
balance.value = null
|
||
}
|
||
} catch (error) {
|
||
console.warn('[api-secret] 代理余量查询失败:', error)
|
||
balance.value = null
|
||
} finally {
|
||
balanceLoading.value = false
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 保存:逐模块保存非空输入(空输入保留服务端原值),代理仅在改动时保存。
|
||
* 检测一律由用户手动点击触发;保存时服务端会沿用「刚检测过的同一个输入值」的结果,
|
||
* 其余情况(改过值 / 从未检测)保持未检测,需用户点「检测」确认可用性。
|
||
*/
|
||
async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean> {
|
||
if (busy.value || proxyLoading.value) return false
|
||
const pendingModules = modules.value.filter((module) => ensureModuleState(module.moduleKey).input.trim())
|
||
if (options.requireAll) {
|
||
const missing = modules.value.filter(
|
||
(module) => !ensureModuleState(module.moduleKey).input.trim() && !snapshotOf(module.moduleKey).exists,
|
||
)
|
||
if (missing.length) {
|
||
ElMessage.warning(`请填写:${missing.map((module) => module.moduleLabel).join('、')}`)
|
||
return false
|
||
}
|
||
}
|
||
|
||
busy.value = true
|
||
let secretsSaved = false
|
||
try {
|
||
for (const module of pendingModules) {
|
||
const moduleKey = module.moduleKey as ApiSecretModuleKey
|
||
const state = ensureModuleState(module.moduleKey)
|
||
await saveApiSecret(moduleKey, state.input.trim())
|
||
state.input = ''
|
||
// 输入值已保存:本地那次「检测输入值」的结果不再代表当前配置,清掉后展示统一走服务端快照
|
||
// (保存前检测过的同一个值,服务端会沿用那次结果,快照里直接是「检测通过」)
|
||
state.result = null
|
||
state.lastCheckSource = ''
|
||
state.error = ''
|
||
}
|
||
secretsSaved = true
|
||
refreshSnapshots()
|
||
|
||
if (props.showProxy && proxyReady.value && proxyDirty.value && !proxyLocked.value) {
|
||
const api = getPywebviewApi()
|
||
if (!api?.save_config) throw new Error('当前客户端未提供代理配置保存能力')
|
||
const nextProxyUrl = proxyUrl.value.trim()
|
||
await api.save_config(userProxyPatch(nextProxyUrl, proxyMode.value) as DesktopConfigUpdate)
|
||
proxyUrl.value = nextProxyUrl
|
||
proxyDirty.value = false
|
||
// 同上:地址已保存,本地「未保存」的检测文案不再适用
|
||
proxyCheckResult.value = null
|
||
proxyCheckError.value = ''
|
||
await syncProxyToServer(nextProxyUrl)
|
||
}
|
||
|
||
// 保存后不再自动检测:检测一律由用户手动点击「检测」触发
|
||
refreshSnapshots()
|
||
return true
|
||
} catch (error) {
|
||
const message = error instanceof Error ? error.message : '设置保存失败'
|
||
ElMessage.error(secretsSaved ? `密钥已保存,但后续步骤失败:${message}` : message)
|
||
return false
|
||
} finally {
|
||
busy.value = false
|
||
}
|
||
}
|
||
|
||
/** 重新从服务端拉取(设置页/弹窗打开时调用)。 */
|
||
async function reload() {
|
||
await loadApiSecrets({ force: true })
|
||
refreshSnapshots()
|
||
}
|
||
|
||
let unsubscribe: (() => void) | null = null
|
||
|
||
onMounted(() => {
|
||
refreshSnapshots()
|
||
unsubscribe = subscribeApiSecrets(refreshSnapshots)
|
||
// 先拉服务端密钥包(后台锁定的代理会先对齐到本地配置),再读本地代理,避免展示对齐前的旧值
|
||
void (async () => {
|
||
await reload()
|
||
if (props.showProxy) {
|
||
await loadProxyConfig()
|
||
if (proxySupported.value) {
|
||
void loadProxyPlan()
|
||
}
|
||
void loadBalance()
|
||
}
|
||
})()
|
||
})
|
||
|
||
onUnmounted(() => {
|
||
if (unsubscribe) unsubscribe()
|
||
})
|
||
|
||
defineExpose({ saveAll, reload })
|
||
</script>
|
||
|
||
<style scoped src="./api-secret-settings-panel.css"></style>
|