<template>
	<view class="max-w-4xl mx-auto p-6 relative">
		<!-- 页面标题 -->
		<view class="bg-[#1d1e3a] text-white p-4 rounded-t-lg">
			<view class="flex justify-between items-center">
				<view class="text-sm">No.{{ candidateInfo.idNumber || '未知' }}</view>
				<view class="text-sm">{{ formatDate(applicationData?.application?.create_datetime) }}</view>
			</view>
		</view>

		<view class="bg-white rounded-b-lg shadow-lg p-6">
			<!-- 头部信息 -->
			<view class="flex justify-between items-center mb-8 pb-4 border-b">
				<view class="flex items-center space-x-4">
					<view class="w-20 h-20 bg-gray-200 rounded-lg overflow-hidden">
						<image :src="candidateInfo.additionalInfo.faceVerification.images[0]" mode="aspectFill" class="w-full h-full"></image>
					</view>
					<view class="flex flex-col custom-column" style="margin-left: 10px;">
						<text class="text-2xl font-bold">{{ candidateInfo.name }}</text>
						<text class="text-gray-600 block mt-1">{{ candidateInfo.phoneNumber }}</text>
					</view>
				</view>
				<view class="text-right">
					<view class="text-4xl font-bold text-yellow-500">{{ candidateInfo.score }}<text class="text-base ml-1">分</text></view>
					<view class="text-sm text-yellow-500">推荐 👍</view>
				</view>
			</view>

			<!-- 基本信息 -->
			<view class="grid grid-cols-1 gap-4 mb-8">
				<view>
					<text class="text-gray-600 block">身份证号</text>
					<text>{{ candidateInfo.idNumber }}</text>
				</view>
				<view>
					<text class="text-gray-600 block">入职之后，您缺岗的班次时间段是？</text>
					<text>{{ candidateInfo.availabilityPeriod }}</text>
				</view>
				<view>
					<text class="text-gray-600 block">请问您通过面试之后多久可以入职？</text>
					<text>{{ candidateInfo.onboardingTime }}</text>
				</view>
			</view>

			<!-- AI维度分析 -->
			<view class="mb-8">
				<text class="text-xl font-bold mb-6 block">1. AI维度分析</text>
				<view class="space-y-6">
					<view v-for="(value, key) in candidateInfo.dimensions" :key="key" class="border-b pb-4">
						<view class="flex items-center mb-2">
							<text class="text-gray-600 w-32">{{ dimensionLabels[key] }}</text>
							<text class="ml-4" :class="{
								'text-red-500': value === '欠佳',
								'text-green-500': value === '优秀',
								'text-yellow-500': value === '中等'
							}">{{ value }}</text>
						</view>
						<text class="text-gray-600 text-sm block">{{ candidateInfo.dimensionDetails[key] }}</text>
					</view>
				</view>
			</view>

			<!-- DUV分析评估 -->
			<view class="mb-8">
				<text class="text-xl font-bold mb-6 block">2. DUV分析评估</text>
				<view class="space-y-4">
					<view v-for="(item, index) in candidateInfo.duvAnalysis" :key="index" class="border-b pb-4">
						<view class="flex items-center justify-between mb-2">
							<text class="text-gray-600">{{ item.title }}</text>
							<text :class="{
								'text-green-500': item.type === 'positive',
								'text-red-500': item.type === 'negative',
								'text-yellow-500': item.type === 'neutral'
							}">{{ item.score }}</text>
						</view>
						<text class="text-gray-600 text-sm block">{{ item.content }}</text>
					</view>
				</view>
			</view>

			<!-- 面试记录 -->
			<view class="mb-8">
				<text class="text-xl font-bold mb-6 block">3. 面试记录</text>
				<view class="space-y-6">
					<view v-for="(record, index) in candidateInfo.interviewRecord" :key="index" class="border-b pb-4">
						<view class="mb-2">
							<text class="font-semibold block">问题：{{ record.question }}</text>
							<text class="text-gray-600 mt-2 block">答案：{{ record.answer }}</text>
							<text class="text-gray-500 mt-2 text-sm block">分析：{{ record.analysis }}</text>
							
							<!-- 视频回放 -->
							<view v-if="record.videoUrl" class="mt-4">
								<view class="video-container">
									<video
										class="w-full h-full"
										:src="record.videoUrl"
										:poster="record.thumbnail"
										controls
									></video>
								</view>
							</view>
							
							<view class="mt-2 flex justify-end">
								<text class="text-blue-500">得分：{{ record.score }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 视频记录 -->
			<view class="mb-8">
				<text class="text-xl font-bold mb-6 block">4. 视频记录</text>
				<view class="space-y-8">
					<view v-for="(category, index) in candidateInfo.videoRecords" :key="index">
						<text class="text-lg font-semibold mb-4 block">{{ category.category }}</text>
						<view class="grid grid-cols-1 gap-4">
							<view v-for="(video, vIndex) in category.videos" :key="vIndex" class="bg-gray-50 rounded-lg p-4">
								<view class="video-container">
									<video
										class="w-full h-full"
										:src="video.url"
										:poster="video.thumbnail"
										controls
									></video>
								</view>
								<text class="text-sm text-gray-600 mt-2 block">{{ video.description }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 其他信息 -->
			<view class="mb-8">
				<text class="text-xl font-bold mb-6 block">5. 其他信息</text>
				<view class="space-y-6">
					<!-- 验证状态 -->
					<view class="grid grid-cols-1 gap-4 mb-4">
						<view class="flex items-center space-x-2">
							<text class="text-gray-600">身份证验证:</text>
							<text class="text-green-500">{{ candidateInfo.additionalInfo.idVerification }}</text>
						</view>
						<view class="flex items-center space-x-2">
							<text class="text-gray-600">手机号验证:</text>
							<text class="text-green-500">{{ candidateInfo.additionalInfo.phoneVerification }}</text>
						</view>
					</view>

					<!-- 手势验证 -->
					<view class="mb-6">
						<text class="font-semibold mb-4 block">手势验证</text>
						<view class="grid grid-cols-2 gap-8">
							<!-- 左手手势 -->
							<view>
								<text class="text-sm font-medium mb-2 block">左手手势验证</text>
								<view class="grid grid-cols-3 gap-2">
									<view v-for="(image, index) in candidateInfo.additionalInfo.leftHandGestures.images" :key="index"
										class="aspect-square rounded-lg overflow-hidden bg-gray-100">
										<image :src="image" mode="aspectFill" class="w-full h-full"></image>
									</view>
								</view>
							</view>
							<!-- 右手手势 -->
							<view>
								<text class="text-sm font-medium mb-2 block">右手手势验证</text>
								<view class="grid grid-cols-3 gap-2">
									<view v-for="(image, index) in candidateInfo.additionalInfo.rightHandGestures.images" :key="index"
										class="aspect-square rounded-lg overflow-hidden bg-gray-100">
										<image :src="image" mode="aspectFill" class="w-full h-full"></image>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 人脸验证 -->
					<view>
						<text class="font-semibold mb-4 block">人脸验证</text>
						<view class="grid grid-cols-3 gap-2">
							<view v-for="(image, index) in candidateInfo.additionalInfo.faceVerification.images" :key="index"
								class="aspect-square rounded-lg overflow-hidden bg-gray-100">
								<image :src="image" mode="aspectFill" class="w-full h-full"></image>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 评估表单 --><!-- 评分 --><!-- 评价 --><!-- 提交按钮 -->
		<!-- 	<view>
				
				<view class="mb-8">
					<text class="text-xl font-bold mb-4 block">6. 面试评分</text>
					<view class="form-item">
						<text class="block mb-2">请为候选人打分</text>
						<uni-rate v-model="evaluationScore" :max="5" allow-half />
					</view>
				</view>

				
				<view class="mb-8">
					<text class="text-xl font-bold mb-4 block">评价意见</text>
					<view class="form-item">
						<text class="block mb-2">请输入评价意见</text>
						<textarea
							v-model="evaluationComments"
							class="w-full border p-2 rounded"
							placeholder="请输入您的评价意见..."
							:rows="4"
						></textarea>
					</view>
				</view>

				
				<view class="flex justify-end">
					<button 
						class="bg-blue-500 text-white px-4 py-2 rounded"
						@click="handleSubmit"
					>提交评估</button>
				</view>
			</view> -->
		</view>

		<!-- 悬浮按钮 -->
		<!-- <view class="fixed-buttons">
			<button class="action-button share-button" @click="handleShare">
				<text class="iconfont">&#xe600;</text>
			</button>
			<button class="action-button download-button" @click="handleDownload">
				<text class="iconfont">&#xe601;</text>
			</button>
			<button class="action-button top-button" @click="scrollToTop">
				<text class="iconfont">&#xe602;</text>
			</button>
		</view> -->
	</view>
</template>

<script>
import { apiBaseUrl } from '@/common/config';
	export default {
		data() {
			return {
				applicationData: null, // 存储API返回的原始数据
				candidateInfo: {
					name: '',
					idNumber: '',
					phoneNumber: '',
					score: 0,
					availabilityPeriod: '',
					onboardingTime: '',
					dimensions: {
						teamwork: '',
						learningAbility: '',
						attention: '',
						workAdaptability: '',
						serviceAwareness: ''
					},
					dimensionDetails: {
						teamwork: '',
						learningAbility: '',
						attention: '',
						workAdaptability: '',
						serviceAwareness: ''
					},
					duvAnalysis: [],
					interviewRecord: [],
					videoRecords: [],
					additionalInfo: {
						idVerification: '',
						phoneVerification: '',
						leftHandGestures: {
							passed: true,
							images: []
						},
						rightHandGestures: {
							passed: true,
							images: []
						},
						faceVerification: {
							passed: true,
							images: []
						}
					}
				},
				evaluationScore: 0,
				evaluationComments: '',
				dimensionLabels: {
					teamwork: '团队合作能力',
					learningAbility: '学习能力',
					attention: '细致严谨',
					workAdaptability: '工作适应性',
					serviceAwareness: '服务意识'
				}
			}
		},
		onLoad(options) {
			// 获取URL参数
			const id = options.id || 1;
			const tenant_id = options.tenant_id || 1;
			const application_id = options.application_id || 1;
			
			// 调用API获取数据
			this.fetchApplicationDetail(id, tenant_id, application_id);
		},
		methods: {
			// 获取申请详情数据
			fetchApplicationDetail(id, tenant_id, application_id) {
				uni.showLoading({
					title: '加载中...'
				});
				
				uni.request({
					url: `${apiBaseUrl}/api/job/application_detail?id=${id}&tenant_id=${tenant_id}&application_id=${application_id}`,
					method: 'GET',
					success: (res) => {
						if (res.data && res.data.code === 2000) {
							this.applicationData = res.data.data;
							this.processApiData();
						} else {
							uni.showToast({
								title: '获取数据失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			
			// 处理API返回的数据，映射到现有数据结构
			processApiData() {
				if (!this.applicationData) return;
				
				const { application, applicant, position, interview_progress, posture_photos } = this.applicationData;
				
				// 基本信息
				this.candidateInfo.name = applicant.name || '';
				this.candidateInfo.idNumber = applicant.id || '';
				this.candidateInfo.phoneNumber = applicant.phone || '';
				
				// 计算综合得分 (使用AI分析的平均分或综合分)
				if (application.comprehensive_score) {
					this.candidateInfo.score = application.comprehensive_score;
				} else if (application.ai_capability_scores) {
					const scores = Object.values(application.ai_capability_scores);
					this.candidateInfo.score = scores.length ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : 0;
				}
				
				// 处理AI维度分析
				if (application.ai_capability_scores) {
					// 将API返回的能力分数映射到现有维度
					const scoreMapping = {
						'专业性': 'workAdaptability',
						'沟通能力': 'teamwork',
						'技术匹配度': 'learningAbility',
						'解决问题能力': 'attention'
					};
					
					// 根据分数设置评价等级
					Object.entries(application.ai_capability_scores).forEach(([key, value]) => {
						const mappedKey = scoreMapping[key] || 'serviceAwareness';
						let rating = '中等';
						if (value >= 80) rating = '优秀';
						else if (value < 65) rating = '欠佳';
						
						this.candidateInfo.dimensions[mappedKey] = rating;
					});
				}
				
				// 处理维度详情
				if (application.ai_analysis_details && application.ai_analysis_details.requirements_feedback) {
					// 将反馈分配到各个维度
					const feedback = application.ai_analysis_details.requirements_feedback;
					Object.keys(this.candidateInfo.dimensionDetails).forEach(key => {
						this.candidateInfo.dimensionDetails[key] = feedback;
					});
				}
				
				// 处理DUV分析
				if (application.ai_overall_feedback) {
					this.candidateInfo.duvAnalysis = [
						{
							title: '综合评估',
							content: application.ai_overall_feedback,
							score: this.candidateInfo.score >= 70 ? '良好' : '需改进',
							type: this.candidateInfo.score >= 70 ? 'positive' : 'negative'
						}
					];
					
					// 添加职位匹配度
					if (position) {
						this.candidateInfo.duvAnalysis.push({
							title: '职位匹配度',
							content: `应聘职位: ${position.title}, ${position.department}, ${position.location}`,
							score: '匹配',
							type: 'positive'
						});
					}
				}
				
				// 处理面试记录
				if (interview_progress && interview_progress.length) {
					this.candidateInfo.interviewRecord = interview_progress
						.filter(item => item.question_text)
						.map(item => {
							const answer = this.extractAnswerFromNotes(application.note, item.question_text);
							return {
								question: item.question_text,
								answer: answer || '未回答',
								analysis: '候选人回答简短，需进一步评估',
								score: '待评估',
								videoUrl: item.video_answer ? item.video_answer.video_url : null,
								thumbnail: '/images/video-placeholder.jpg'
							};
						});
				}
				
				// 处理视频记录
				const videoAnswers = interview_progress
					.filter(item => item.video_answer && item.video_answer.video_url);
				
				if (videoAnswers.length) {
					this.candidateInfo.videoRecords = [
						{
							category: '面试视频',
							videos: videoAnswers.map(item => ({
								url: item.video_answer.video_url,
								thumbnail: '/images/thumbnail1.jpg',
								description: item.question_text
							}))
						}
					];
				}
				
				// 处理手势验证和人脸验证
				if (posture_photos && posture_photos.length) {
					// 分类照片
					const leftHandPhotos = posture_photos.filter(p => 
						p.description.includes('left') && !p.description.includes('face'));
					const rightHandPhotos = posture_photos.filter(p => 
						p.description.includes('right') && !p.description.includes('face'));
					const facePhotos = posture_photos.filter(p => 
						!p.description.includes('left') && !p.description.includes('right'));
					
					// 更新照片数据
					this.candidateInfo.additionalInfo.leftHandGestures.images = 
						leftHandPhotos.map(p => p.photo_url);
					this.candidateInfo.additionalInfo.rightHandGestures.images = 
						rightHandPhotos.map(p => p.photo_url);
					this.candidateInfo.additionalInfo.faceVerification.images = 
						facePhotos.map(p => p.photo_url);
				}
				
				// 设置验证状态
				this.candidateInfo.additionalInfo.idVerification = '通过';
				this.candidateInfo.additionalInfo.phoneVerification = '通过';
			},
			
			// 从面试记录中提取答案
			extractAnswerFromNotes(notes, question) {
				if (!notes) return '';
				
				const pattern = new RegExp(`问题 ${question}:\\s*([^\\n]+)`, 'i');
				const match = notes.match(pattern);
				return match ? match[1].trim() : '';
			},
			
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '';
				
				try {
					const date = new Date(dateString);
					return date.toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit',
						second: '2-digit'
					});
				} catch (e) {
					return dateString;
				}
			},
			
			handleSubmit() {
				if (this.evaluationScore === 0 || !this.evaluationComments.trim()) {
					uni.showToast({
						title: '请完成所有必填项',
						icon: 'none'
					});
					return;
				}
				
				uni.showToast({
					title: '评估已提交',
					icon: 'success'
				});
			},
			
			scrollToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			
			handleShare() {
				uni.showToast({
					title: '分享链接已复制',
					icon: 'success'
				});
			},
			
			handleDownload() {
				uni.showToast({
					title: '报告下载中...',
					icon: 'loading'
				});
			}
		}
	}
</script>

<style>
.max-w-4xl {
	max-width: 56rem;
	margin: 0 auto;
}

.p-6 {
	padding: 1.5rem;
}

.relative {
	position: relative;
}

/* .bg-\[\#1d1e3a\] {
	background-color: #1d1e3a;
} */

.text-white {
	color: white;
}

.p-4 {
	padding: 1rem;
}

.rounded-t-lg {
	border-top-left-radius: 0.5rem;
	border-top-right-radius: 0.5rem;
}

.flex {
	display: flex;
}

.justify-between {
	justify-content: space-between;
}

.items-center {
	align-items: center;
}

.text-sm {
	font-size: 0.875rem;
}

.bg-white {
	background-color: white;
}

.rounded-b-lg {
	border-bottom-left-radius: 0.5rem;
	border-bottom-right-radius: 0.5rem;
}

.shadow-lg {
	box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.mb-8 {
	margin-bottom: 2rem;
}

.pb-4 {
	padding-bottom: 1rem;
}

.border-b {
	border-bottom-width: 1px;
	border-bottom-style: solid;
	border-bottom-color: #e5e7eb;
}

/* .space-x-4 > * + * {
	margin-left: 1rem;
} */

.w-20 {
	width: 5rem;
}

.h-20 {
	height: 5rem;
}

.bg-gray-200 {
	background-color: #e5e7eb;
}

.rounded-lg {
	border-radius: 0.5rem;
}

.overflow-hidden {
	overflow: hidden;
}

.w-full {
	width: 100%;
}

.h-full {
	height: 100%;
}

.object-cover {
	object-fit: cover;
}

.text-2xl {
	font-size: 1.5rem;
}

.font-bold {
	font-weight: bold;
}

.text-gray-600 {
	color: #4b5563;
}

.text-right {
	text-align: right;
}

.text-4xl {
	font-size: 2.25rem;
}

.text-yellow-500 {
	color: #f59e0b;
}

.ml-1 {
	margin-left: 0.25rem;
}

.text-base {
	font-size: 1rem;
}

.grid {
	display: grid;
}

.grid-cols-1 {
	grid-template-columns: repeat(1, minmax(0, 1fr));
}

.grid-cols-2 {
	grid-template-columns: repeat(2, minmax(0, 1fr));
}

.grid-cols-3 {
	grid-template-columns: repeat(3, minmax(0, 1fr));
}

.gap-4 {
	gap: 1rem;
}

.gap-2 {
	gap: 0.5rem;
}

.gap-8 {
	gap: 2rem;
}

.text-xl {
	font-size: 1.25rem;
}

.mb-6 {
	margin-bottom: 1.5rem;
}

.mb-4 {
	margin-bottom: 1rem;
}

.mb-2 {
	margin-bottom: 0.5rem;
}

/* .space-y-6 > * + * {
	margin-top: 1.5rem;
}

.space-y-4 > * + * {
	margin-top: 1rem;
}

.space-y-8 > * + * {
	margin-top: 2rem;
} */

.w-32 {
	width: 8rem;
}

.text-red-500 {
	color: #ef4444;
}

.text-green-500 {
	color: #10b981;
}

.text-sm {
	font-size: 0.875rem;
}

.font-semibold {
	font-weight: 600;
}

.mt-2 {
	margin-top: 0.5rem;
}

.text-gray-500 {
	color: #6b7280;
}

.mt-4 {
	margin-top: 1rem;
}

.video-container {
	position: relative;
	width: 100%;
	max-width: 240px;
	aspect-ratio: 3/4;
	margin: 0 auto;
	background: #000;
	border-radius: 12px;
	overflow: hidden;
}

.justify-end {
	justify-content: flex-end;
}

.text-blue-500 {
	color: #3b82f6;
}

.text-lg {
	font-size: 1.125rem;
}

.bg-gray-50 {
	background-color: #f9fafb;
}

.aspect-square {
	aspect-ratio: 1 / 1;
}

.bg-gray-100 {
	background-color: #f3f4f6;
}

.form-item {
	margin-bottom: 1.5rem;
}

.border {
	border-width: 1px;
	border-style: solid;
	border-color: #e5e7eb;
}

.rounded {
	border-radius: 0.25rem;
}

.bg-blue-500 {
	background-color: #3b82f6;
}

.px-4 {
	padding-left: 1rem;
	padding-right: 1rem;
}

.py-2 {
	padding-top: 0.5rem;
	padding-bottom: 0.5rem;
}

.fixed-buttons {
	position: fixed;
	right: 2rem;
	bottom: 6rem;
	display: flex;
	flex-direction: column;
	gap: 1rem;
	z-index: 100;
}

.action-button {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	background-color: #3b82f6;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* 为了模拟图标，你可能需要引入字体图标或使用其他方式 */
@font-face {
	font-family: "iconfont";
	src: url('data:font/woff2;charset=utf-8;base64,...') format('woff2');
}

.iconfont {
	font-family: "iconfont" !important;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

/* 媒体查询适配移动端 */
@media (max-width: 768px) {
	.p-6 {
		padding: 1rem;
	}
	
	.fixed-buttons {
		right: 1rem;
	}
}

.custom-column {
	flex-direction: column;
}
</style>
