<template>
	<view class="upload-container">
		<!-- 顶部插图区域 -->
		<view class="header-notice">
		<image style="width: 30rpx;height: 30rpx;" src="https://data.qicai321.com/minlong/57d03f34-47de-43fe-8730-b764ed8bdda2.png" mode="aspectFit"></image>请上传简历文件，格式支持pdf及doc格式
		</view>
		<view class="illustration">
			<image class="img" src="https://data.qicai321.com/minlong/09d4daa6-6507-4133-81ff-68e47b0259e5.png" mode="aspectFit"></image>
		</view>
		
		<!-- 上传按钮 -->
		<button class="upload-btn" @click="chooseFile" :disabled="!!uploadedFile">
			{{uploadedFile ? '已上传文件' : '选择并上传文件'}}
		</button>
		<!-- 跳过，直接进入下一环节 -->
		<button class="skip-btn" @click="handleSkip" v-if="showSkipButton">跳过，直接进入下一环节</button>
		
		<!-- 文件信息显示区域 -->
		<view class="file-info" v-if="uploadedFile">
			<view class="file-info-header">
				<view class="file-info-title">已上传文件</view>
				<view class="file-delete" @click="clearFile">
					<image class="delete-icon" src="https://data.qicai321.com/minlong/delete.png" mode="aspectFit"></image>
				</view>
			</view>
			<view class="file-info-content">
				<view class="file-name">{{uploadedFile.name}}</view>
				<view class="file-size">{{formatFileSize(uploadedFile.size)}}</view>
				<view class="file-time">上传时间：{{uploadedFile.uploadTime}}</view>
			</view>
		</view>
		
		<!-- 使用说明区域 -->
		<view class="instructions">
			<view class="title">使用说明及注意事项</view>
			<view class="instruction-list">
				<view class="instruction-item">1. 点击【选择并上传文件】按钮，上传简历;</view>
				<view class="instruction-item">2. 请在本地选择简历文件，文件小于30mb;</view>
				<view class="instruction-item">3. 支持pdf及doc格式。</view>
			</view>
			
			<!-- 隐私提示 -->
			<view class="privacy-notice">
				* 我们将对您的隐私保护，所内容仅用于评估岗位的匹配度。
			</view>
		</view>
	</view>
</template>

<script>
	import { apiBaseUrl } from '@/common/config.js';
	
	export default {
		data() {
			return {
				fileType: ['pdf', 'doc', 'docx'],
				maxSize: 30 * 1024 * 1024, // 30MB in bytes
				uploadedFile: null,
				showSkipButton: false // 控制跳过按钮显示
			}
		},
		onLoad(options) {
			// 判断是否从index页面跳转来
			const pages = getCurrentPages();
			const prevPage = pages[pages.length - 2]; // 获取上一个页面
			if (prevPage && (prevPage.route === 'pages/index/index' || prevPage.route === 'pages/job-detail/job-detail' || prevPage.route === 'pages/video-briefing/video-briefing')) {
				this.showSkipButton = true;
			}
		},
		methods: {
			// 处理跳过按钮点击
			handleSkip() {
				uni.showModal({
					title: '提示',
					content: '确定要跳过上传简历环节吗？',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/Personal/Personal'
							});
						}
					}
				});
			},
			
			// 调用简历解析接口
			/* async parseResume(fileUrl) {
				try {
					const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
					const userId = userInfo.id;
					const openid = userInfo.openid;
					const tenant_id = userInfo.tenant_id;
					
					if (!userId) {
						uni.showToast({
							title: '用户信息不完整，请重新登录',
							icon: 'none'
						});
						return false;
					}
					
					const response = await uni.request({
						url: `${apiBaseUrl}/api/system/resume-parsing-tasks/upload_resume/`,
						method: 'POST',
						data: {
							openid: openid,
							tenant_id: tenant_id,
							user_id: userId,
							file: fileUrl,
							description: '候选人简历'
						},
						header: {
							'content-type': 'application/json'
						}
					});
					
					if (response.statusCode === 200 && response.data.code === 2000) {
						return true;
					} else {
						throw new Error(response.data.msg || '简历解析失败');
					}
				} catch (error) {
					console.error('简历解析失败:', error);
					uni.showToast({
						title: error.message || '简历解析失败',
						icon: 'none'
					});
					return false;
				}
			}, */
			
			clearFile() {
				uni.showModal({
					title: '提示',
					content: '确定要删除已上传的文件吗？',
					success: (res) => {
						if (res.confirm) {
							this.uploadedFile = null;
							uni.showToast({
								title: '文件已删除',
								icon: 'success'
							});
						}
					}
				});
			},
			
			formatFileSize(size) {
				if (size < 1024) {
					return size + 'B';
				} else if (size < 1024 * 1024) {
					return (size / 1024).toFixed(2) + 'KB';
				} else {
					return (size / (1024 * 1024)).toFixed(2) + 'MB';
				}
			},
			
			chooseFile() {
				if (this.uploadedFile) {
					uni.showToast({
						title: '请先删除已上传的文件',
						icon: 'none'
					});
					return;
				}
				
				// #ifdef H5
				uni.chooseFile({
					count: 1,
					type: 'file',
					extension: this.fileType,
					success: (res) => {
						if (res.tempFiles[0].size > this.maxSize) {
							uni.showToast({
								title: '文件大小不能超过30MB',
								icon: 'none'
							})
							return
						}
						this.uploadFile(res.tempFiles[0])
					}
				})
				// #endif
				
				// #ifdef APP-PLUS || MP
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					extension: this.fileType,
					success: (res) => {
						if (res.tempFiles[0].size > this.maxSize) {
							uni.showToast({
								title: '文件大小不能超过30MB',
								icon: 'none'
							})
							return
						}
						this.uploadFile(res.tempFiles[0])
					}
				})
				// #endif
			},
			
			async uploadFile(file) {
				try {
					uni.showLoading({
						title: '上传中...'
					});
					
					// 获取用户信息
					const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
					console.log(userInfo);
					const openid = userInfo.openid || '';
					const tenant_id =uni.getStorageSync('tenant_id') || userInfo.tenant_id || 1;
					const userId = userInfo.id;
					
					console.log(openid, tenant_id);
					if (!openid || !tenant_id || !userId) {
						uni.hideLoading();
						uni.showToast({
							title: '用户信息不完整，请重新登录',
							icon: 'none'
						});
						return;
					}
					
					// 直接上传到简历解析接口
					uni.uploadFile({
						url: `${apiBaseUrl}/api/system/resume-parsing-tasks/upload_resume/`,
						filePath: file.path,
						name: 'file',
						formData: {
							openid: openid,
							tenant_id: tenant_id,
							user_id: userId,
							description: '候选人简历'
						},
						success: (uploadRes) => {
							try {
								const res = JSON.parse(uploadRes.data);
								console.log(res);
								if (res.code === 2000) {
									// 保存上传文件信息
									this.uploadedFile = {
										name: file.name || '未命名文件',
										size: file.size,
										uploadTime: new Date().toLocaleString(),
										url: res.data.url || ''
									};
									
									// 显示上传成功提示
									uni.showToast({
										title: '上传成功',
										icon: 'success',
										duration: 2000
									});
									
									// 显示30秒的loading
									let seconds = 30;
									uni.showLoading({
										title: `正在处理中，请稍候...(${seconds}秒)`,
										mask: true
									});
									
									const timer = setInterval(() => {
										seconds--;
										if (seconds > 0) {
											uni.showLoading({
												title: `正在处理中，请稍候...(${seconds}秒)`,
												mask: true
											});
										} else {
											clearInterval(timer);
											uni.hideLoading();
											uni.showToast({
												title: '处理完成',
												icon: 'success',
												duration: 2000,
												success: () => {
													uni.navigateTo({
														url: '/pages/Personal/Personal'
													});
												}
											});
										}
									}, 1000);
									
								} else {
									uni.showToast({
										title: res.msg || '上传失败',
										icon: 'none'
									});
								}
							} catch (error) {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							console.error('上传失败:', err);
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						},
						complete: () => {
							// 注意：这里不隐藏loading，因为成功后会显示30秒的loading
							if (!this.uploadedFile) {
								uni.hideLoading();
							}
						}
					});
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '系统错误，请重试',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="scss">
.upload-container {
	padding: 30rpx;
	background-color: #f5f6fa;
	min-height: 100vh;
	
	.header-notice{
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		line-height: 1.5;
	}
	
	.illustration {
		text-align: center;
		margin: 40rpx auto;
		padding: 20rpx;
		border-radius: 12rpx;
		
		image {
			width: 650rpx;
			height: 550rpx;
		}
	}
	
	.file-info {
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin: 30rpx auto;
		width: 90%;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.file-info-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
		}

		.file-info-title {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
		}

		.file-delete {
			padding: 10rpx;
			.delete-icon {
				width: 32rpx;
				height: 32rpx;
			}
		}

		.file-info-content {
			.file-name {
				font-size: 26rpx;
				color: #666;
				margin-bottom: 10rpx;
				word-break: break-all;
			}

			.file-size {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 10rpx;
			}

			.file-time {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
	
	.instructions {
		padding: 0 30rpx;
		
		.title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 30rpx;
		}
		
		.instruction-list {
			.instruction-item {
				font-size: 26rpx;
				color: #666;
				line-height: 44rpx;
				margin-bottom: 20rpx;
			}
		}
		
		.privacy-notice {
			margin-top: 40rpx;
			font-size: 24rpx;
			color: #999;
			line-height: 1.5;
		}
	}
	
	.upload-btn {
		width: 90%;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #2b4acb;
		color: #ffffff;
		border-radius: 8rpx;
		font-size: 32rpx;
		margin: 60rpx auto;
		text-align: center;
		
		&::after {
			border: none;
		}

		&[disabled] {
			background-color: #cccccc;
			color: #ffffff;
		}
	}
	
	.skip-btn {
		width: 90%;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #ffffff;
		color: #666666;
		border-radius: 8rpx;
		font-size: 32rpx;
		margin: 20rpx auto;
		text-align: center;
		border: 1px solid #dddddd;
		
		&::after {
			border: none;
		}
	}
}
</style>
