<template>
	<view class="laser-thinking-page">
		<LaserThinkingShell :progress="progress" :status-text="statusText" />
		<LaserBatchCanvasHost />
	</view>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import LaserThinkingShell from '@/components/laser/LaserThinkingShell.vue'
import LaserBatchCanvasHost from '@/components/laser/LaserBatchCanvasHost.vue'
import { useLaserBatchGenerate } from '@/composables/useLaserBatchGenerate.js'
import {
	consumeGenerationFlowPayload,
	LASER_RESULT_URL,
} from '@/utils/castloveGenerationFlow.js'

const { progress, simulateProgress, setFlowStartedAt, run } = useLaserBatchGenerate()

const genMode = ref('client') // will be set on mount

const statusText = computed(() => {
	if (genMode.value !== 'dify') return ''
	const p = progress.value
	if (p < 0.1) return 'AI 正在设计背景...'
	if (p < 0.4) return 'AI 正在绘制装饰图案...'
	if (p < 0.7) return '正在合成光栅效果...'
	if (p < 0.95) return '即将完成...'
	return ''
})

const revertAndBack = () => {
	setTimeout(() => {
		uni.navigateBack()
	}, 800)
}

const revertProgress = () => {
	let p = progress.value
	const revertInterval = setInterval(() => {
		if (p > 0) {
			p = Math.max(0, p - 10)
			progress.value = p
		} else {
			clearInterval(revertInterval)
			revertAndBack()
		}
	}, 100)
}

const handleSuccess = () => {
	uni.showToast({ title: '生成成功', icon: 'success', duration: 1200 })
	setTimeout(() => {
		uni.navigateTo({ url: LASER_RESULT_URL })
	}, 1200)
}

onMounted(async () => {
	const startedAt = Date.now()
	setFlowStartedAt(startedAt)
	simulateProgress()

	// 检测生成模式
	genMode.value = (typeof import.meta !== 'undefined' && import.meta.env?.VITE_LASER_GEN_MODE) || 'client'

	try {
		const flow = consumeGenerationFlowPayload()
		if (!flow) {
			throw new Error('缺少生成流程数据')
		}
		await run({ flow })
		handleSuccess()
	} catch (err) {
		console.error('[laser-thinking]', err)
		const msg = String(err?.message || '镭射生成失败')
		uni.showToast({
			title: msg.length > 48 ? msg.slice(0, 48) + '…' : msg,
			icon: 'none',
			duration: 3500,
		})
		revertProgress()
	}
})
</script>

<style scoped>
.laser-thinking-page {
	width: 100%;
	height: 100vh;
}
</style>
