|
- <template>
- <div class="min-h-screen bg-[var(--c-f3f7fb)]">
- <!-- ========== Hero ========== -->
- <AppHero
- kicker="PORTRAIT PHOTO STUDIO"
- title="形象照 / 职业照 / 写真"
- desc="上传一张人像照片,AI 重绘服装与背景,生成商务形象照、日常职业照或艺术写真。"
- >
- <template #actions>
- <button
- v-if="hasDemo"
- type="button"
- class="h-10 cursor-pointer rounded-full bg-[var(--c-0b8cff)] px-5 text-sm font-extrabold text-white shadow-[0_10px_20px_var(--sh-11-140-255-220)] transition-colors hover:bg-[var(--c-0a7ce0)] lg:h-11"
- @click="openDemoCompare"
- >
- 查看对比
- </button>
- <button
- type="button"
- class="h-10 cursor-pointer rounded-full bg-[var(--c-ffffff)] px-5 text-sm font-extrabold text-[var(--c-0b8cff)] shadow-sm transition-colors hover:bg-[var(--c-f7faff)] lg:h-11"
- @click="triggerUpload"
- >
- 上传照片
- </button>
- <button
- type="button"
- class="inline-flex h-10 cursor-pointer items-center gap-1.5 rounded-full bg-[var(--c-ffffff)] px-5 text-sm font-extrabold text-[var(--c-5b6b80)] shadow-sm transition-colors hover:bg-[var(--c-f7faff)] lg:h-11"
- @click="historyOpen = true"
- >
- <UIcon name="i-lucide-history" class="size-4" />
- 历史记录
- </button>
- </template>
- <template #aside>
- <HeroComparePreview
- v-if="hasDemo"
- :before="demoPair.original"
- :after="demoPair.result"
- after-label="艺术"
- @open="openDemoCompare"
- />
- </template>
- </AppHero>
-
- <!-- ========== Main Grid ========== -->
- <div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:py-8">
- <div class="lg:grid lg:grid-cols-12 lg:gap-8">
- <!-- ===== LEFT: 表单 ===== -->
- <div class="space-y-5 pb-28 lg:col-span-7 lg:pb-0">
- <!-- 1. 上传 -->
- <div class="rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:p-6">
- <div class="mb-4 flex items-start justify-between gap-4">
- <div class="min-w-0">
- <h3 class="text-base font-extrabold text-[var(--c-172033)] lg:text-lg">人像照片</h3>
- <p class="mt-1 text-xs text-[var(--c-8a97a8)]">建议正面、五官无遮挡、光线均匀的半身照,单张不超过 10M</p>
- </div>
- <span class="flex-shrink-0 rounded-full bg-[var(--c-fff1f1)] px-3 py-1 text-[11px] font-bold text-[var(--c-ff6b6b)]">必选</span>
- </div>
-
- <div
- class="flex cursor-pointer items-center gap-4 rounded-2xl border-2 border-[var(--c-e5edf7)] bg-[var(--c-f7faff)] p-4 transition-colors hover:border-[var(--c-1f8cff)]/40"
- role="button"
- tabindex="0"
- @click="triggerUpload"
- @keydown.enter.prevent="triggerUpload"
- @keydown.space.prevent="triggerUpload"
- @dragover.prevent
- @drop.prevent="onDrop"
- >
- <div class="relative h-28 w-20 flex-shrink-0 overflow-hidden rounded-2xl bg-[var(--c-edf3fb)]">
- <img v-if="previewImage" :src="previewImage" class="h-full w-full object-cover" alt="已选照片预览">
- <div v-else class="flex h-full w-full items-center justify-center">
- <span class="flex size-9 items-center justify-center rounded-full bg-[var(--c-1f8cff)] text-2xl font-light text-white">+</span>
- </div>
- </div>
- <div class="min-w-0 flex-1">
- <div class="text-sm font-extrabold text-[var(--c-172033)] lg:text-base">{{ previewImage ? '已选择照片' : '上传正面清晰的人像照片' }}</div>
- <div class="mt-1.5 text-xs text-[var(--c-8a97a8)]">支持自拍与半身照;也可以直接把文件拖进来</div>
- </div>
- <div class="flex h-9 w-16 flex-shrink-0 items-center justify-center rounded-full bg-[var(--c-1f8cff)] text-xs font-extrabold text-white">
- {{ previewImage ? '更换' : '上传' }}
- </div>
- </div>
- <input ref="fileInput" type="file" accept="image/*" class="hidden" aria-label="选择人像照片" @change="onFileChange">
- </div>
-
- <!-- 2. 生成模型(只有一个模型时不展示,后续多模型自动出现) -->
- <div v-if="models.length > 1" class="rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:p-6">
- <div class="flex items-start justify-between gap-4">
- <h3 class="text-base font-extrabold text-[var(--c-172033)] lg:text-lg">生成模型</h3>
- <span class="mt-1 text-xs text-[var(--c-8a97a8)]">不同模型价格可能不同</span>
- </div>
- <div class="mt-4 grid gap-2.5 sm:grid-cols-2">
- <button
- v-for="item in models"
- :key="item.key"
- type="button"
- class="cursor-pointer rounded-2xl border-2 p-4 text-left transition-colors"
- :class="activeModel === item.key
- ? 'border-[var(--c-1f8cff)] bg-[var(--c-eef7ff)]'
- : 'border-transparent bg-[var(--c-f6f9fd)] hover:border-[var(--c-e5edf7)]'"
- :aria-pressed="activeModel === item.key"
- @click="activeModel = item.key"
- >
- <span class="block text-sm font-extrabold text-[var(--c-172033)]">{{ item.name }}</span>
- <span v-if="item.desc" class="mt-1 block text-xs leading-relaxed text-[var(--c-8a97a8)]">{{ item.desc }}</span>
- </button>
- </div>
- </div>
-
- <!-- 3. 照片风格 + 选项 -->
- <div class="rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:p-6">
- <div class="flex items-start justify-between gap-4">
- <h3 class="text-base font-extrabold text-[var(--c-172033)] lg:text-lg">照片风格</h3>
- <span class="mt-1 text-xs text-[var(--c-8a97a8)]">选择生成方向</span>
- </div>
-
- <!-- 加载骨架:>300ms 的等待都要有反馈 -->
- <div v-if="configLoading" class="mt-4 space-y-2.5">
- <div v-for="i in 3" :key="i" class="h-[76px] animate-pulse rounded-2xl bg-[var(--c-f1f5fa)]" />
- </div>
-
- <template v-else>
- <div class="mt-4 grid gap-2.5 sm:grid-cols-3">
- <button
- v-for="item in styles"
- :key="item.key"
- type="button"
- class="cursor-pointer rounded-2xl border-2 p-4 text-left transition-colors"
- :class="activeStyle === item.key
- ? 'border-[var(--c-1f8cff)] bg-[var(--c-eef7ff)]'
- : 'border-transparent bg-[var(--c-f6f9fd)] hover:border-[var(--c-e5edf7)]'"
- :aria-pressed="activeStyle === item.key"
- @click="selectStyle(item.key)"
- >
- <span class="block text-sm font-extrabold text-[var(--c-172033)]">{{ item.name }}</span>
- <span class="mt-1 block text-xs leading-relaxed text-[var(--c-8a97a8)]">{{ item.desc }}</span>
- </button>
- </div>
-
- <div v-for="group in currentGroups" :key="group.key" class="mt-5">
- <div class="text-sm font-extrabold text-[var(--c-172033)]">{{ group.name }}</div>
- <div class="mt-2.5 flex flex-wrap gap-2.5">
- <button
- v-for="item in group.items"
- :key="item.key"
- type="button"
- class="h-10 cursor-pointer rounded-full border-2 px-4 text-xs font-bold transition-colors"
- :class="options[group.key] === item.key
- ? 'border-[var(--c-1f8cff)] bg-[var(--c-eef7ff)] text-[var(--c-0b8cff)]'
- : 'border-transparent bg-[var(--c-f6f9fd)] text-[var(--c-526174)] hover:border-[var(--c-e5edf7)]'"
- :aria-pressed="options[group.key] === item.key"
- @click="options[group.key] = item.key"
- >
- {{ item.name }}
- </button>
- </div>
- </div>
- </template>
- </div>
-
- <!-- 4. 比例与张数 -->
- <div class="rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:p-6">
- <div class="flex items-start justify-between gap-4">
- <h3 class="text-base font-extrabold text-[var(--c-172033)] lg:text-lg">{{ quantityEnabled ? '图片比例与张数' : '图片比例' }}</h3>
- <span class="mt-1 text-xs font-extrabold text-[var(--c-0b8cff)]">{{ quantityPriceText }}</span>
- </div>
-
- <div class="mt-4 flex flex-wrap gap-2.5">
- <button
- v-for="item in ratios"
- :key="item.key"
- type="button"
- class="h-10 w-[76px] cursor-pointer rounded-xl border-2 text-xs font-extrabold transition-colors"
- :class="activeRatio === item.key
- ? 'border-[var(--c-1f8cff)] bg-[var(--c-eef7ff)] text-[var(--c-0b8cff)]'
- : 'border-transparent bg-[var(--c-f6f9fd)] text-[var(--c-526174)] hover:border-[var(--c-e5edf7)]'"
- :aria-pressed="activeRatio === item.key"
- @click="activeRatio = item.key"
- >
- {{ item.name }}
- </button>
- </div>
-
- <div v-if="configLoading" class="mt-5 h-14 animate-pulse rounded-2xl bg-[var(--c-f1f5fa)]" />
-
- <div v-else-if="quantityEnabled" class="mt-5 flex items-center gap-4">
- <span class="text-sm font-bold text-[var(--c-526174)]">生成张数</span>
- <div class="flex items-center gap-3">
- <button
- type="button"
- class="flex size-10 cursor-pointer items-center justify-center rounded-xl bg-[var(--c-eef7ff)] text-lg font-extrabold text-[var(--c-0b8cff)] transition-colors hover:bg-[var(--c-e0f0ff)] disabled:cursor-not-allowed disabled:opacity-50"
- aria-label="减少张数"
- :disabled="quantity <= 1"
- @click="quantity = Math.max(1, quantity - 1)"
- >
- -
- </button>
- <span class="min-w-8 text-center text-lg font-extrabold text-[var(--c-172033)]">{{ quantity }}</span>
- <button
- type="button"
- class="flex size-10 cursor-pointer items-center justify-center rounded-xl bg-[var(--c-eef7ff)] text-lg font-extrabold text-[var(--c-0b8cff)] transition-colors hover:bg-[var(--c-e0f0ff)] disabled:cursor-not-allowed disabled:opacity-50"
- aria-label="增加张数"
- :disabled="quantity >= maxCount"
- @click="quantity = Math.min(maxCount, quantity + 1)"
- >
- +
- </button>
- </div>
- <span class="text-xs text-[var(--c-8a97a8)]">一次最多 {{ maxCount }} 张,按张扣点,失败的不扣</span>
- </div>
-
- <div v-else class="mt-5 rounded-2xl bg-[var(--c-f7faff)] px-4 py-3">
- <div class="flex items-center justify-between gap-3">
- <span class="text-sm font-bold text-[var(--c-526174)]">生成张数</span>
- <span class="rounded-full bg-[var(--c-eef7ff)] px-3 py-1 text-xs font-extrabold text-[var(--c-0b8cff)]">固定 1 张</span>
- </div>
- <p class="mt-1 text-xs leading-relaxed text-[var(--c-8a97a8)]">后台已关闭多张生成,本次只生成 1 张。</p>
- </div>
- </div>
-
- <!-- 5. 补充描述 -->
- <div class="rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:p-6">
- <div class="flex items-start justify-between gap-4">
- <h3 class="text-base font-extrabold text-[var(--c-172033)] lg:text-lg">补充描述</h3>
- <span class="mt-1 text-xs text-[var(--c-8a97a8)]">选填</span>
- </div>
- <label class="mt-4 block text-xs font-bold text-[var(--c-526174)]" for="portrait-extra">职业、服装、背景等客观信息</label>
- <input
- id="portrait-extra"
- v-model="extraPrompt"
- type="text"
- maxlength="100"
- placeholder="例如:程序员、深灰西装、浅色背景"
- class="mt-2 h-12 w-full rounded-xl bg-[var(--c-f6f9fd)] px-4 text-sm text-[var(--c-172033)] placeholder:text-[var(--c-a0aabb)] focus:outline-none focus:ring-2 focus:ring-[var(--c-1f8cff)]/30"
- >
- <p class="mt-2 text-xs text-[var(--c-8a97a8)]">只用来补充客观信息,风格由上方选项决定。</p>
- </div>
-
- <!-- 6. 说明 -->
- <div v-if="tips.length" class="space-y-3 rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:p-6">
- <div v-for="(tip, index) in tips" :key="tip" class="flex items-start">
- <span class="mr-3 mt-0.5 flex h-5 w-7 flex-shrink-0 items-center justify-center rounded-[14px] bg-[var(--c-eef7ff)] text-[11px] font-extrabold text-[var(--c-1f8cff)]">
- {{ String(index + 1).padStart(2, '0') }}
- </span>
- <span class="text-sm leading-relaxed text-[var(--c-5f6f83)]">{{ tip }}</span>
- </div>
- </div>
-
- <!-- Desktop 提交 -->
- <div class="hidden items-center gap-3 rounded-2xl bg-[var(--c-ffffff)] p-4 shadow-[0_10px_28px_var(--sh-32-56-92-50)] lg:flex">
- <div class="min-w-0 flex-1">
- <div class="whitespace-nowrap text-sm font-bold text-[var(--c-172033)]">{{ balanceText }}</div>
- <button v-if="isBalanceInsufficient" type="button" class="mt-1 cursor-pointer text-xs text-[var(--c-f04438)] hover:underline" @click="goRecharge">
- 点数不足,前往充值
- </button>
- </div>
- <button
- type="button"
- class="flex h-14 flex-shrink-0 cursor-pointer items-center gap-1.5 rounded-full border border-[var(--c-e5edf7)] px-6 text-sm font-bold text-[var(--c-5b6b80)] transition-colors hover:bg-[var(--c-f7f9fd)]"
- @click="historyOpen = true"
- >
- <UIcon name="i-lucide-history" class="size-4" />
- 历史记录
- </button>
- <button
- type="button"
- class="flex h-14 min-w-[168px] flex-shrink-0 cursor-pointer items-center justify-center rounded-full px-10 text-base font-bold text-white shadow-[0_12px_24px_var(--sh-31-140-255-280)] transition-all disabled:cursor-not-allowed disabled:opacity-50"
- :class="submitting ? 'bg-[var(--c-1979e6)]' : 'bg-gradient-to-r from-[var(--c-1f8cff)] to-[var(--c-41b9ff)] hover:opacity-90'"
- :disabled="!canSubmit"
- @click="handleSubmit"
- >
- <UIcon v-if="!submitting" name="i-lucide-zap" class="mr-1.5 size-4" />
- <span>{{ submitting ? '提交中...' : submitText }}</span>
- </button>
- </div>
- </div>
-
- <!-- ===== RIGHT: 结果 ===== -->
- <div class="lg:col-span-5">
- <div class="space-y-4 lg:sticky lg:top-20">
- <!-- 空态 -->
- <div v-if="!resultState.visible" class="flex min-h-[300px] flex-col items-center justify-center rounded-2xl bg-[var(--c-ffffff)] p-8 text-center shadow-sm lg:p-10">
- <UIcon name="i-lucide-image" class="mb-4 size-12 text-[var(--c-a0aabb)]" />
- <div class="mb-1 text-base font-medium text-[var(--c-172033)]">等待生成</div>
- <div class="text-sm text-[var(--c-a0aabb)]">上传人像并选好风格后</div>
- <div class="text-sm text-[var(--c-a0aabb)]">点击"立即生成"即可看到效果</div>
- </div>
-
- <!-- 处理中 -->
- <div v-if="resultState.loading" class="rounded-2xl bg-[var(--c-ffffff)] p-6 shadow-sm lg:p-8">
- <div class="mb-1 text-base font-bold text-[var(--c-172033)]">{{ pendingTitle }}</div>
- <div class="mb-6 text-sm text-[var(--c-7f8896)]">每张单独生成,混元未购买并发,高峰期会排队</div>
- <div class="flex flex-col items-center rounded-2xl bg-[var(--c-f7f9fd)] py-10">
- <div class="mb-4 flex gap-1.5">
- <span class="animate-pulse-dot size-2.5 rounded-full bg-[var(--c-1f8cff)]" />
- <span class="animate-pulse-dot2 size-2.5 rounded-full bg-[var(--c-1f8cff)]" />
- <span class="animate-pulse-dot3 size-2.5 rounded-full bg-[var(--c-1f8cff)]" />
- </div>
- <div class="text-sm font-bold text-[var(--c-172033)]">
- {{ job.success_count || 0 }} / {{ job.count || effectiveQuantity }} 张 · 已等待 {{ waitedSeconds }}s
- </div>
- <div v-if="pollCountdown > 0" class="mt-2 text-xs text-[var(--c-8a95a6)]">下次刷新 {{ pollCountdown }}s</div>
- </div>
- </div>
-
- <!-- 失败 -->
- <div v-if="resultState.error" class="rounded-2xl bg-[var(--c-ffffff)] p-6 py-10 text-center shadow-sm lg:p-8">
- <UIcon name="i-lucide-circle-alert" class="mx-auto mb-3 size-12 text-[var(--c-f04438)]" />
- <div class="mb-2 text-base font-medium text-[var(--c-f04438)]">生成失败</div>
- <div class="mb-4 text-sm text-[var(--c-7f8896)]">{{ resultState.errorMsg }}</div>
- <UButton color="primary" variant="outline" size="sm" @click="handleSubmit">重试</UButton>
- </div>
-
- <!-- 成功 -->
- <div v-if="resultState.success" class="space-y-4">
- <div class="rounded-2xl bg-[var(--c-ffffff)] p-5 shadow-sm lg:p-6">
- <div class="mb-4 flex items-center justify-between gap-3">
- <div class="text-base font-bold text-[var(--c-172033)]">生成结果</div>
- <span class="rounded-full bg-[var(--c-edfdf4)] px-2.5 py-1 text-[11px] font-extrabold text-[var(--c-159a54)]">{{ job.style_name }}</span>
- </div>
-
- <!-- 主视图直接看成品,对比放进弹层 -->
- <div class="overflow-hidden rounded-xl bg-[var(--c-f7f9fd)]">
- <img :src="activeResultUrl" class="w-full" alt="形象照生成结果">
- </div>
-
- <div v-if="resultUrls.length > 1" class="mt-3 flex flex-wrap gap-2.5">
- <button
- v-for="(url, index) in resultUrls"
- :key="url"
- type="button"
- class="size-16 cursor-pointer overflow-hidden rounded-xl border-2 transition-colors"
- :class="activeIndex === index ? 'border-[var(--c-1f8cff)]' : 'border-transparent hover:border-[var(--c-e5edf7)]'"
- :aria-label="`查看第 ${index + 1} 张`"
- :aria-pressed="activeIndex === index"
- @click="activeIndex = index"
- >
- <img :src="url" class="size-full object-cover" :alt="`第 ${index + 1} 张`">
- </button>
- </div>
-
- <div v-if="job.fail_count" class="mt-3 text-xs text-[var(--c-f04438)]">
- 有 {{ job.fail_count }} 张生成失败,失败的不扣点
- </div>
-
- <div class="mt-5 flex gap-3">
- <button
- type="button"
- class="flex h-12 flex-1 cursor-pointer items-center justify-center rounded-full border-2 border-[var(--c-1f8cff)] font-bold text-[var(--c-1f8cff)] transition-colors hover:bg-[var(--c-eef7ff)]"
- @click="openResultCompare"
- >
- <UIcon name="i-lucide-columns-2" class="mr-1.5 size-4" />
- 查看对比
- </button>
- <button
- type="button"
- class="flex h-12 flex-1 cursor-pointer items-center justify-center rounded-full bg-[var(--c-1f8cff)] text-base font-bold text-white shadow-[0_8px_20px_var(--sh-31-140-255-200)] transition-colors hover:bg-[var(--c-1979e6)]"
- @click="downloadResult"
- >
- <UIcon name="i-lucide-download" class="mr-1.5 size-4" />
- 下载
- </button>
- </div>
- </div>
- <button
- type="button"
- class="h-12 w-full cursor-pointer rounded-full border-2 border-[var(--c-1f8cff)] font-bold text-[var(--c-1f8cff)] transition-colors hover:bg-[var(--c-eef7ff)]"
- @click="resetJob"
- >
- 再拍一组
- </button>
- <p class="text-center text-xs leading-relaxed text-[var(--c-8a97a8)]">
- AI 会重绘服装与背景,五官可能出现轻微变化,建议对照原图确认
- </p>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- ========== 移动端底部操作条 ========== -->
- <div
- class="fixed bottom-0 left-0 right-0 z-50 bg-[var(--c-ffffff)]/95 shadow-[0_-10px_30px_var(--sh-32-56-92-100)] backdrop-blur lg:hidden"
- style="padding: 14px 16px calc(14px + env(safe-area-inset-bottom))"
- >
- <div class="mb-2.5 flex items-center justify-between gap-3 text-sm">
- <div class="min-w-0 truncate text-[var(--c-7b8797)]">{{ balanceText }}</div>
- <button v-if="isBalanceInsufficient" type="button" class="flex-shrink-0 cursor-pointer text-xs font-extrabold text-[var(--c-1f8cff)]" @click="goRecharge">
- 去充值
- </button>
- </div>
- <div class="flex gap-3">
- <button type="button" class="h-12 w-[120px] cursor-pointer rounded-full bg-[var(--c-eef7ff)] text-sm font-extrabold text-[var(--c-1f8cff)]" @click="historyOpen = true">
- 历史记录
- </button>
- <button
- type="button"
- class="flex h-12 flex-1 cursor-pointer items-center justify-center rounded-full bg-gradient-to-r from-[var(--c-1f8cff)] to-[var(--c-41b9ff)] text-sm font-extrabold text-white shadow-[0_12px_24px_var(--sh-31-140-255-280)] transition-opacity disabled:opacity-60"
- :disabled="!canSubmit"
- @click="handleSubmit"
- >
- <UIcon v-if="!submitting" name="i-lucide-zap" class="mr-1.5 size-4" />
- {{ submitting ? '提交中...' : submitText }}
- </button>
- </div>
- </div>
-
- <!-- ========== 历史记录 / 详情 ========== -->
- <WorkHistoryDrawer v-model="historyOpen" type="portrait" @select="openHistoryItem" />
- <WorkDetailModal v-model="detailOpen" :work="currentWork" />
-
- <!-- ========== 对比弹层(demo 与成品共用) ========== -->
- <Teleport to="body">
- <Transition name="modal">
- <div v-if="compareVisible" class="fixed inset-0 z-[100] flex items-center justify-center p-4">
- <div class="absolute inset-0 bg-[var(--c-0f172a)]/60" @click="closeCompare" />
- <div class="relative w-full max-w-2xl overflow-hidden rounded-2xl bg-[var(--c-ffffff)] shadow-2xl">
- <div class="flex items-center justify-between border-b border-[var(--c-f3f4f6)] px-5 py-4">
- <h3 class="text-base font-extrabold text-[var(--c-172033)]">{{ compareTarget === 'result' ? '生成结果对比' : '效果对比' }}</h3>
- <button
- type="button"
- class="flex size-8 cursor-pointer items-center justify-center rounded-full text-2xl leading-none text-[var(--c-a0aabb)] transition-colors hover:bg-[var(--c-f3f4f6)]"
- aria-label="关闭对比"
- @click="closeCompare"
- >
- ×
- </button>
- </div>
- <div class="p-5">
- <div
- ref="largeCompareRef"
- class="relative max-h-[70vh] w-full cursor-ew-resize select-none overflow-hidden rounded-2xl bg-[var(--c-dfe8f4)]"
- style="aspect-ratio: 3 / 4"
- @mousedown="onCompareStart"
- @touchstart.passive="onCompareStart"
- >
- <img :src="comparePair.after" class="pointer-events-none absolute inset-0 h-full w-full object-contain" alt="生成结果">
- <img
- :src="comparePair.before"
- class="pointer-events-none absolute inset-0 h-full w-full object-contain"
- :style="{ clipPath: `inset(0 ${100 - comparePercent}% 0 0)` }"
- alt="原图"
- >
- <div
- class="pointer-events-none absolute bottom-0 top-0 -ml-px w-1 bg-[var(--c-ffffff)]/95 shadow-[0_0_12px_var(--sh-20-37-66-220)]"
- :style="{ left: comparePercent + '%' }"
- >
- <div class="absolute left-1/2 top-1/2 flex h-14 w-9 -translate-x-1/2 -translate-y-1/2 items-center justify-center gap-px rounded-full bg-[var(--c-ffffff)] text-lg font-extrabold text-[var(--c-1f8cff)] shadow-[0_8px_18px_var(--sh-20-37-66-220)]">
- <span>‹</span><span>›</span>
- </div>
- </div>
- <div class="pointer-events-none absolute left-3 top-3 rounded-full bg-[var(--c-0f172a)]/50 px-2 py-0.5 text-[10px] font-bold text-white">原图</div>
- <div class="pointer-events-none absolute right-3 top-3 rounded-full bg-[var(--c-0f172a)]/50 px-2 py-0.5 text-[10px] font-bold text-white">艺术照</div>
- </div>
- <div class="mt-3 text-center text-xs text-[var(--c-64748b)]">左右拖动中间按钮查看变化</div>
- </div>
- </div>
- </div>
- </Transition>
- </Teleport>
- </div>
- </template>
-
- <script setup>
- useSeoMeta({
- title: 'AI 形象照 / 职业照 / 写真 - AI在线',
- description: '上传一张人像照片,AI 生成商务形象照、日常职业照与古风、港风等艺术写真,支持多张生成、前后对比与原图下载。',
- })
-
- const { post } = useApi()
- const { create: createPortrait, createRequestId } = usePortrait()
- const user = useUser()
- const router = useRouter()
- const toast = useToast()
-
- const POLL_INTERVAL = 3000
- const POLL_LIMIT = 8 * 60 * 1000
- // 首屏示例对比图由配置项下发(同 old_photo_demo),不在端上硬编码
- const DEMO_CONFIG_KEY = 'portrait_photo_demo'
-
- // ==================== State ====================
- const fileInput = ref(null)
- const selectedFile = ref(null)
- const previewImage = ref('')
- const extraPrompt = ref('')
- const models = ref([])
- const styles = ref([])
- const ratios = ref([])
- const tips = ref([])
- const activeModel = ref('')
- const activeStyle = ref('')
- const activeRatio = ref('')
- const options = reactive({})
- const quantity = ref(1)
- const maxCount = ref(4)
- const quantityEnabled = ref(true)
- const unitPoints = ref(0)
- const configLoading = ref(true)
- const submitting = ref(false)
- const balance = reactive({ points: 0 })
- const job = ref({})
- const activeIndex = ref(0)
- const demoPair = ref({ original: '', result: '' })
- const historyOpen = ref(false)
- const detailOpen = ref(false)
- const currentWork = ref({})
-
- const resultState = ref({ visible: false, loading: false, error: false, success: false, errorMsg: '' })
- const pollCountdown = ref(3)
- const waitedSeconds = ref(0)
- let pollTimer = null
- let countTimer = null
- let pollStart = 0
-
- // ==================== Computed ====================
- const hasDemo = computed(() => Boolean(demoPair.value.original && demoPair.value.result))
- const currentStyle = computed(() => styles.value.find(item => item.key === activeStyle.value) || {})
- const currentGroups = computed(() => currentStyle.value.groups || [])
- const resultUrls = computed(() => job.value.result_urls || [])
- const activeResultUrl = computed(() => resultUrls.value[activeIndex.value] || resultUrls.value[0] || '')
- const effectiveQuantity = computed(() => (quantityEnabled.value ? quantity.value : 1))
- const totalPoints = computed(() => unitPoints.value * effectiveQuantity.value)
- const quantityPriceText = computed(() => {
- if (!unitPoints.value) return quantityEnabled.value ? `共${totalPoints.value}点` : '固定1张'
- return quantityEnabled.value ? `${unitPoints.value}点/张 · 共${totalPoints.value}点` : `${unitPoints.value}点/张 · 固定1张`
- })
- const currentPoints = computed(() => Number(balance.points || 0))
- const isBalanceInsufficient = computed(
- () => user.isLogin.value && totalPoints.value > 0 && currentPoints.value < totalPoints.value,
- )
- const canSubmit = computed(() => Boolean(selectedFile.value) && !submitting.value && !resultState.value.loading)
- const balanceText = computed(() => {
- if (!user.isLogin.value) return unitPoints.value ? `形象照 · ${unitPoints.value}点/张` : '形象照'
- return totalPoints.value
- ? `余额${currentPoints.value}点 · 预计消耗${totalPoints.value}点`
- : `余额${currentPoints.value}点`
- })
- const submitText = computed(() => {
- if (!user.isLogin.value) return totalPoints.value ? `登录后生成 · ${totalPoints.value}点` : '登录后生成'
- return totalPoints.value ? `立即生成 · ${totalPoints.value}点` : '立即生成'
- })
- const pendingTitle = computed(() => (Number(job.value.status) === 10 ? '排队中,等待 AI 处理' : 'AI 正在生成形象照'))
-
- function showToast(message, color = 'error') {
- toast.add({ title: message, color })
- }
-
- function pickFirstDefined(values) {
- return values.find(value => value !== undefined && value !== null && value !== '')
- }
-
- function normalizeQuantityEnabled(data = {}) {
- const raw = pickFirstDefined([
- data.quantity_enabled,
- data.quantity_supported,
- data.product?.quantity_enabled,
- data.billing?.product?.quantity_enabled,
- data.billing?.quote?.product?.quantity_enabled,
- ])
- if (raw === undefined) return Number(data.max_count || 1) > 1
- if (typeof raw === 'boolean') return raw
- return !['0', 'false', 'no', 'off', 'unsupported', 'not_support', '不支持'].includes(String(raw).toLowerCase())
- }
-
- function applyQuantityConfig(data = {}) {
- const enabled = normalizeQuantityEnabled(data)
- const rawMax = pickFirstDefined([
- data.max_count,
- data.product?.max_quantity,
- data.billing?.product?.max_quantity,
- data.billing?.quote?.product?.max_quantity,
- ])
- const nextMax = enabled ? Math.max(1, Number(rawMax || maxCount.value || 1)) : 1
- quantityEnabled.value = enabled
- maxCount.value = nextMax
- quantity.value = enabled ? Math.min(Math.max(1, quantity.value), nextMax) : 1
- }
-
- // ==================== 配置 / 示例 / 余额 ====================
- async function loadConfig(silent = false) {
- try {
- const res = await post('/portrait/config', {
- style: activeStyle.value || undefined,
- model: activeModel.value || undefined,
- count: effectiveQuantity.value,
- })
- const data = res.data || {}
- models.value = data.models || []
- styles.value = data.styles || []
- ratios.value = data.ratios || []
- tips.value = data.tips || []
- applyQuantityConfig(data)
- unitPoints.value = Number(data.unit_points || 0)
- if (!activeModel.value) activeModel.value = data.default_model || models.value[0]?.key || ''
- if (!activeRatio.value) {
- activeRatio.value = (ratios.value.find(item => item.is_default) || ratios.value[0] || {}).key || ''
- }
- if (!activeStyle.value) {
- activeStyle.value = data.default_style || styles.value[0]?.key || ''
- applyStyleDefaults()
- }
- if (data.billing?.balance) {
- balance.points = data.billing.balance.points || data.billing.balance.point_balance || 0
- }
- } catch (e) {
- if (!silent) showToast(e.message || '配置加载失败')
- } finally {
- configLoading.value = false
- }
- }
-
- /** 切换风格时把该风格的选项重置为默认值 */
- function applyStyleDefaults() {
- Object.keys(options).forEach(key => delete options[key])
- for (const group of currentGroups.value) {
- const picked = group.items.find(item => item.is_default) || group.items[0]
- if (picked) options[group.key] = picked.key
- }
- }
-
- function selectStyle(key) {
- if (activeStyle.value === key) return
- activeStyle.value = key
- applyStyleDefaults()
- }
-
- // 换模型会影响单价,重新取一次报价
- watch(activeModel, (value, old) => {
- if (old && value && value !== old) loadConfig(true)
- })
-
- /** 示例对比图走配置项 portrait_photo_demo,格式 [{ original, result }] */
- async function loadDemo() {
- try {
- const res = await post('/common/getconfig', { keys: DEMO_CONFIG_KEY })
- const rows = Array.isArray(res.list) ? res.list : []
- const item = rows.find(it => it.key === DEMO_CONFIG_KEY)
- if (!item?.value) return
- const data = typeof item.value === 'string' ? JSON.parse(item.value) : item.value
- const first = Array.isArray(data) ? data[0] : data
- if (!first) return
- demoPair.value = {
- original: first.original || first.before || first.source || '',
- result: first.result || first.after || '',
- }
- } catch (e) {
- console.error('[portrait-photo] loadDemo failed:', e)
- }
- }
-
- async function loadBalance() {
- try {
- const res = await post('/point/balance', {})
- if (res.code === 0 && res.data) balance.points = res.data.points || res.data.point_balance || 0
- } catch (e) {
- console.error('[portrait-photo] loadBalance failed:', e)
- }
- user.refreshBalance()
- }
-
- onMounted(() => {
- loadConfig()
- loadDemo()
- if (user.isLogin.value) loadBalance()
- })
- onUnmounted(() => clearPoll())
-
- // ==================== 上传 ====================
- function triggerUpload() {
- if (!user.isLogin.value) {
- user.showLogin.value = true
- return
- }
- fileInput.value?.click()
- }
-
- function onFileChange(e) {
- const file = e.target.files?.[0]
- if (file) handleFile(file)
- e.target.value = ''
- }
-
- function onDrop(e) {
- if (!user.isLogin.value) {
- user.showLogin.value = true
- return
- }
- const file = e.dataTransfer?.files?.[0]
- if (file) handleFile(file)
- }
-
- function handleFile(file) {
- if (!/^image\//.test(file.type)) return showToast('请选择图片文件')
- if (file.size > 10 * 1024 * 1024) return showToast('图片不能超过 10M')
- if (previewImage.value) URL.revokeObjectURL(previewImage.value)
- selectedFile.value = file
- previewImage.value = URL.createObjectURL(file)
- resultState.value = { visible: false, loading: false, error: false, success: false, errorMsg: '' }
- job.value = {}
- activeIndex.value = 0
- }
-
- // ==================== 提交与轮询 ====================
- function clearPoll() {
- clearTimeout(pollTimer)
- clearInterval(countTimer)
- pollTimer = null
- countTimer = null
- }
-
- async function handleSubmit() {
- if (!user.isLogin.value) {
- user.showLogin.value = true
- return
- }
- if (!selectedFile.value) return showToast('请先上传人像照片')
- if (!canSubmit.value) return
- if (isBalanceInsufficient.value) return showToast('点数不足,请充值后重试')
-
- submitting.value = true
- resultState.value = { visible: true, loading: true, error: false, success: false, errorMsg: '' }
- waitedSeconds.value = 0
- activeIndex.value = 0
- pollStart = Date.now()
-
- try {
- const res = await createPortrait(selectedFile.value, {
- style: activeStyle.value,
- model: activeModel.value,
- ratio: activeRatio.value,
- count: effectiveQuantity.value,
- extra_prompt: extraPrompt.value,
- request_id: createRequestId(),
- options: { ...options },
- })
- job.value = res.data || {}
- if (Number(job.value.status) === 30) {
- onSuccess()
- } else {
- startPoll()
- }
- } catch (e) {
- const msg = e.code === 1011 ? '点数不足,请充值后重试' : (e.message || '提交失败,请稍后重试')
- resultState.value = { visible: true, loading: false, error: true, success: false, errorMsg: msg }
- } finally {
- submitting.value = false
- }
- }
-
- function startPoll() {
- clearPoll()
- pollCountdown.value = POLL_INTERVAL / 1000
- countTimer = setInterval(() => {
- pollCountdown.value = Math.max(0, pollCountdown.value - 1)
- waitedSeconds.value = Math.round((Date.now() - pollStart) / 1000)
- }, 1000)
- pollTimer = setTimeout(async () => {
- if (Date.now() - pollStart > POLL_LIMIT) {
- clearPoll()
- resultState.value = {
- visible: true,
- loading: false,
- error: true,
- success: false,
- errorMsg: '生成时间较长,可稍后从历史记录查看结果',
- }
- return
- }
- try {
- const res = await post('/portrait/getdetail', { photo_open_id: job.value.photo_open_id })
- const data = res.data || {}
- job.value = data
- const status = Number(data.status)
- if (status === 30) {
- clearPoll()
- onSuccess()
- } else if (status < 0) {
- clearPoll()
- resultState.value = {
- visible: true,
- loading: false,
- error: true,
- success: false,
- errorMsg: data.error_msg || '生成失败,本次未扣点',
- }
- } else {
- startPoll()
- }
- } catch (e) {
- // 单次查询失败不打断轮询
- startPoll()
- }
- }, POLL_INTERVAL)
- }
-
- function onSuccess() {
- activeIndex.value = 0
- resultState.value = { visible: true, loading: false, error: false, success: true, errorMsg: '' }
- loadBalance()
- }
-
- function resetJob() {
- clearPoll()
- job.value = {}
- activeIndex.value = 0
- selectedFile.value = null
- if (previewImage.value) URL.revokeObjectURL(previewImage.value)
- previewImage.value = ''
- extraPrompt.value = ''
- resultState.value = { visible: false, loading: false, error: false, success: false, errorMsg: '' }
- }
-
- async function downloadResult() {
- const url = activeResultUrl.value
- if (!url) return
- try {
- const res = await fetch(url)
- const blob = await res.blob()
- const link = document.createElement('a')
- link.href = URL.createObjectURL(blob)
- link.download = `portrait-photo-${Date.now()}.jpg`
- link.click()
- URL.revokeObjectURL(link.href)
- } catch {
- window.open(url, '_blank')
- }
- }
-
- function goRecharge() {
- router.push('/recharge')
- }
-
- function openHistoryItem(item) {
- currentWork.value = item
- detailOpen.value = true
- }
-
- // ==================== 对比弹层 ====================
- const compareVisible = ref(false)
- const comparePercent = ref(50)
- const compareTarget = ref('demo')
- const largeCompareRef = ref(null)
- let dragging = false
-
- const comparePair = computed(() => {
- if (compareTarget.value === 'result') {
- return { before: job.value.source_url || previewImage.value, after: activeResultUrl.value }
- }
- return { before: demoPair.value.original, after: demoPair.value.result }
- })
-
- function openDemoCompare() {
- if (!hasDemo.value) return showToast('暂无对比图')
- comparePercent.value = 50
- compareTarget.value = 'demo'
- compareVisible.value = true
- }
-
- function openResultCompare() {
- if (!activeResultUrl.value) return showToast('结果图暂不可用')
- comparePercent.value = 50
- compareTarget.value = 'result'
- compareVisible.value = true
- }
-
- function closeCompare() {
- compareVisible.value = false
- onCompareEnd()
- }
-
- function onCompareStart(e) {
- dragging = true
- updateComparePercent(e.touches?.[0] || e)
- window.addEventListener('mousemove', onCompareMove)
- window.addEventListener('mouseup', onCompareEnd)
- window.addEventListener('touchmove', onCompareMove, { passive: false })
- window.addEventListener('touchend', onCompareEnd)
- }
-
- function onCompareMove(e) {
- if (!dragging) return
- if (e.cancelable) e.preventDefault()
- updateComparePercent(e.touches?.[0] || e)
- }
-
- function onCompareEnd() {
- dragging = false
- window.removeEventListener('mousemove', onCompareMove)
- window.removeEventListener('mouseup', onCompareEnd)
- window.removeEventListener('touchmove', onCompareMove)
- window.removeEventListener('touchend', onCompareEnd)
- }
-
- function updateComparePercent(e) {
- if (!largeCompareRef.value) return
- const rect = largeCompareRef.value.getBoundingClientRect()
- const percent = (((e.clientX || 0) - rect.left) / rect.width) * 100
- comparePercent.value = Math.max(2, Math.min(98, Number(percent.toFixed(1))))
- }
- </script>
-
- <style scoped>
- .animate-pulse-dot { animation: dotPulse 1.1s ease-in-out infinite; }
- .animate-pulse-dot2 { animation: dotPulse 1.1s ease-in-out 0.15s infinite; }
- .animate-pulse-dot3 { animation: dotPulse 1.1s ease-in-out 0.3s infinite; }
- @keyframes dotPulse {
- 0%, 100% { opacity: 0.35; transform: scale(0.82); }
- 50% { opacity: 1; transform: scale(1); }
- }
- .modal-enter-active, .modal-leave-active { transition: opacity 0.2s ease; }
- .modal-enter-from, .modal-leave-to { opacity: 0; }
-
- /* 尊重系统的减少动效设置 */
- @media (prefers-reduced-motion: reduce) {
- .animate-pulse-dot,
- .animate-pulse-dot2,
- .animate-pulse-dot3 { animation: none; }
- .modal-enter-active, .modal-leave-active { transition: none; }
- }
- </style>
|