<template>
	<view class="success-container">
		<view class="success-icon">
			<image src="https://data.qicai321.com/minlong/dbf3202a-de17-4d1d-8b8c-d0d708c55552.png" mode="aspectFit"></image>
		</view>
		<view class="success-title">
			<block v-if="isAnalyzing">照片解析中...</block>
			<block v-else>恭喜完成全部检测</block>
		</view>
		
		<view v-if="isAnalyzing" class="loading-container">
			<view class="loading-spinner"></view>
			<view class="loading-text">正在分析照片，请稍候...</view>
		</view>
		
		<view v-else class="check-list">
			<view class="check-item" v-for="(item, index) in checkItems" :key="index">
				<view class="check-index">{{index + 1}}</view>
				<view class="check-name">{{item.name}}</view>
				<view class="check-status" :class="{'status-fail': !item.success}">
					{{item.success ? '动作检测成功' : '动作检测失败'}}
				</view>
			</view>
		</view>
		
		<view class="button-group" v-if="!isAnalyzing">
			<button class="btn-retake" @click="retake" :disabled="isAnalyzing">重新拍摄</button>
			<button class="btn-next" @click="goNext" :disabled="isAnalyzing">
				{{hasFailedItems ? '补拍' : '下一步'}}
			</button>
		</view>
	</view>
</template>

<script>
import { apiBaseUrl } from '@/common/config.js'; // 导入基础URL配置
	export default {
		data() {
			return {
				checkItems: [
					{ name: '左手手心', success: true, type: 'left_palm', description: '展示完整的左手手掌' },
					{ name: '左手手背', success: true, type: 'left_back', description: '展示完整的左手手背' },
					{ name: '左手握拳', success: true, type: 'left_fist', description: '展示完整的左手握拳' },
					{ name: '右手手心', success: true, type: 'right_palm', description: '展示完整的右手手掌' },
					{ name: '右手手背', success: true, type: 'right_back', description: '展示完整的右手手背' },
					{ name: '右手握拳', success: true, type: 'right_fist', description: '展示完整的右手握拳' }
				],
				maxRetries: 3,
				currentRetry: 0,
				retryInterval: 3000, // 3秒
				applicationId: null,
				isAnalyzing: false, // 添加分析状态标志
			}
		},
		computed: {
			hasFailedItems() {
				return this.checkItems.some(item => !item.success)
			},
			failedItems() {
				return this.checkItems.filter(item => !item.success)
			}
		},
		onLoad(options) {
			this.applicationId = uni.getStorageSync('appId')
			this.fetchAnalysisResults()
		},
		methods: {
			async fetchAnalysisResults() {
				try {
					this.isAnalyzing = true // 开始分析时设置状态
					const response = await uni.request({
						url: `${apiBaseUrl}/api/system/job/get_visual_analysis_results?application_id=${this.applicationId}`,
					})
					console.log(response)
					
					// 检查响应状态码
					if (response.data.code === 2001) {
						// 状态码2001表示正在处理中，继续轮询
						setTimeout(() => {
							this.fetchAnalysisResults()
						}, this.retryInterval)
						return
					}
					
					// 处理成功响应
					if (response.data.code === 2000 && response.data.data && response.data.data.photo_results && response.data.data.photo_results.length > 0) {
						this.isAnalyzing = false // 分析完成
						this.processResults(response.data.data.photo_results)
					} else if (this.currentRetry < this.maxRetries) {
						// 如果没有结果且未达到最大重试次数，则重试
						this.currentRetry++
						setTimeout(() => {
							this.fetchAnalysisResults()
						}, this.retryInterval)
					} else {
						this.isAnalyzing = false // 重试结束后也要关闭分析状态
					}
				} catch (error) {
					console.error('获取分析结果失败:', error)
					this.isAnalyzing = false // 发生错误时关闭分析状态
				}
			},
			
			processResults(photoResults) {
				const results = {}
				
				photoResults.forEach(photo => {
					// 根据description匹配对应的检测项
					const checkItem = this.checkItems.find(item => 
						photo.description === item.description
					)
					console.log(checkItem, photo)
					if (checkItem) {
						results[checkItem.type] = photo.part_verification.is_correct_part
					}
				})
				
				this.updateCheckResults(results)
			},
			updateCheckResults(results) {
				this.checkItems = this.checkItems.map(item => ({
					...item,
					success: results[item.type] || false
				}))
			},
			retake() {
				if (this.hasFailedItems) {
					// 携带失败项信息跳转到拍照页面
					uni.navigateTo({
						url: '/pages/interview/interview?retake=true&failedItems=' + 
							 JSON.stringify(this.failedItems.map(item => item.type))
					})
				} else {
					uni.navigateBack()
				}
			},
			goNext() {
				if (!this.hasFailedItems) {
					// 根据配置决定跳转到下一个页面
					this.navigateToNextPage();
				} else {
					// 使用 redirectTo 替代 navigateTo
					uni.reLaunch({
						url: '/pages/interview_retake/interview_retake?failedItems=' + 
							 JSON.stringify(this.failedItems)
					})
				}
			},

			// 根据配置决定跳转到下一个页面
			navigateToNextPage() {
				// 获取本地存储的配置数据
				let configData = {};
				try {
					const configStr = uni.getStorageSync('configData');
					if (configStr && configStr.trim()) {
						configData = JSON.parse(configStr);
					}
				} catch (error) {
					console.error('解析configData失败:', error);
					configData = {};
				}

				console.log('interview_success页面获取到的配置数据:', configData);

				// 获取问题形式开关配置
				const questionFormSwitches = configData?.question_form_switches || {};
				
				// 检查是否启用了选择题相关功能
				const hasChoiceQuestions = questionFormSwitches.enable_fill_blank || 
										  questionFormSwitches.enable_image_choice || 
										  questionFormSwitches.enable_multiple_choice || 
										  questionFormSwitches.enable_single_choice;
				
				// 肢体检测配置
				const hasPostureDetection = configData?.enable_posture_check;
				// 候选人提问配置
				const hasCandidateQuestions = questionFormSwitches.enable_candidate_questions;

				let targetUrl = '/pages/success/success'; // 默认跳转到成功页面
				let pageName = 'success页面';

				console.log('interview_success页面配置检查:', {
					hasChoiceQuestions,
					hasPostureDetection,
					hasCandidateQuestions,
					questionFormSwitches
				});

				if (hasCandidateQuestions) {
					// 如果启用了候选人提问，跳转到interview-question页面
					targetUrl = '/pages/interview-question/interview-question';
					pageName = 'interview-question页面';
				}else{
					targetUrl = '/pages/success/success';
					pageName = 'success页面';
				}

				console.log('interview_success页面根据配置跳转到:', targetUrl);

				// 执行页面跳转
				uni.reLaunch({
					url: targetUrl,
					success: () => {
						console.log(`成功跳转到${pageName}`);
					},
					fail: (err) => {
						console.error(`跳转到${pageName}失败:`, err);
						
						// 如果跳转失败，尝试使用navigateTo
						uni.navigateTo({
							url: targetUrl,
							fail: (navigateErr) => {
								console.error(`导航到${pageName}也失败:`, navigateErr);
								
								// 最后尝试使用redirectTo
								uni.redirectTo({
									url: targetUrl,
									fail: (redirectErr) => {
										console.error('所有跳转方式都失败:', redirectErr);
										
										// 如果所有跳转方式都失败，跳转到默认成功页面
										uni.reLaunch({
											url: '/pages/success/success'
										});
									}
								});
							}
						});
					}
				});
			}
		}
	}
</script>

<style>
.success-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 30rpx;
}

.success-icon {
	margin-top: 162rpx;
	width: 160rpx;
	height: 160rpx;
}

.success-icon image {
	width: 100%;
	height: 100%;
}

.success-title {
	font-size: 36rpx;
	font-weight: bold;
	margin: 30rpx 0 50rpx;
}

.check-list {
	width: 100%;
	margin-bottom: 60rpx;
	display: flex;
	flex-direction: column;
	align-content: center;
	flex-wrap: wrap;
}

.check-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.check-index {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	background-color: #f0f0f0;
	color: #999;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 24rpx;
	margin-right: 20rpx;
}

.check-name {
	margin-right: 20px;
	font-size: 28rpx;
	color: #333;
}

.check-status {
	font-size: 28rpx;
	color: #003399;
}

.status-fail {
	color: #f56c6c;
}

.button-group {
	display: flex;
	width: 100%;
	justify-content: space-between;
	margin-top: 240rpx;
}

.btn-retake, .btn-next {
	width: 45%;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 8rpx;
}

.btn-retake {
	background-color: #f5f5f5;
	color: #333;
	border: 1px solid #ddd;
}

.btn-next {
	background-color: #003399;
	color: #fff;
}

.btn-next:disabled {
	background-color: #999;
	opacity: 0.6;
}

.loading-container {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(255, 255, 255, 0.8);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.loading-spinner {
	border: 4px solid #f3f3f3;
	border-top: 4px solid #003399;
	border-radius: 50%;
	width: 40rpx;
	height: 40rpx;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-text {
	margin-top: 20rpx;
	font-size: 28rpx;
	color: #333;
}

/* 添加 loading 相关样式 */
.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin: 40rpx 0;
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #003399;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* 修改按钮禁用状态样式 */
.btn-retake:disabled, .btn-next:disabled {
	opacity: 0.5;
	cursor: not-allowed;
}
</style>
