<template>
	<view class="position-detail-page">
		<!-- 主内容区域 - 可滚动 -->
		<view class="content-wrapper">
			<!-- 顶部信息区域 -->
			<view class="header-section">
				<view class="factory-info">
					<text class="factory-name">{{positionData.factoryName || '默认工厂'}}</text>
					<!-- <text class="factory-type">{{positionData.factoryType || '电子厂'}}</text> -->
					<text v-if="positionData.distanceMeters"
						class="distance">{{`距你${Math.round(positionData.distanceMeters)}米`}}</text>
				</view>
			</view>

			<!-- 工作时间区域 -->
			<!-- <view class="work-time-section">
				<text class="time">{{positionData.workTime}}</text>
				<text class="business">{{positionData.jobName}}</text>
			</view> -->

			<!-- 薪资信息区域 -->
			<view class="salary-section">
				<!-- <view class="salary-item">
					<text class="item-title">小时工</text>
					<text class="salary-content">工资: 20+1元/小时（含1元满勤）+绩效奖金高达500，月薪6500-7500</text>
				</view> -->
				<text class="salary-content">工作岗位：{{positionData.jobName}}</text>
				<text class="salary-content">工作时间：{{positionData.workTime}}</text>
				<text class="salary-content">时薪：{{positionData.hourlyWage}}/时</text>
				<text class="salary-content">年龄要求：{{positionData.ageRange}}</text>
				<text class="salary-content">包饭：{{positionData.mealPlan}}餐</text>
				<text class="salary-content">住宿环境：{{positionData.dorm}}人间</text>
				<text class="salary-content" v-for="item in positionData.tags">{{item.tagName}}</text>
			</view>

			<!-- 福利信息区域 -->
			<!-- <view class="benefits-section">
				<text class="benefits-content">转正满2个月体检费196元企业报销(凭发票)</text>
				<text class="benefits-content">有部分为显微镜工作，显微镜工作额外有0-300的岗位补贴（具体以厂区发放为准抱拳）</text>
			</view> -->

			<!-- 分隔线 -->
			<view class="divider"></view>

			<!-- 用户评价区域 -->
			<view class="comments-section">
				<view class="section-title">
					<text>用户评价</text>
					<view class="add-comment-container" @click="showCommentBox">
						<text>写一个评论</text>
						<image class="comment-icon" src="/static/comment.png" mode=""></image>
					</view>
				</view>

				<!-- 动态渲染评价列表 -->
				<view class="comment-item" v-for="(comment, index) in comments" :key="comment.id" @longpress="longpress(comment)">
					<view class="user-info">
						<view class="avatar">
							<image style="width: 100%;" :src="comment.avatarUrl" mode="widthFix"></image>
						</view>
						<text class="username">{{ comment.nickname }}</text>
					</view>
					<text class="comment-content">{{ comment.content }}</text>
					<view class="like-section">
						<!-- <text class="like-count">{{ comment.likes }}</text> -->
						<!-- <text class="like-icon" :class="{ active: comment.isLiked }"
							@click="toggleLike(index)">👍</text> -->
					</view>
				</view>

				<!-- 如果评价数量大于1，显示分隔线 -->
				<view class="comment-divider" v-if="comments.length > 1"></view>
			</view>

			<!-- 底部空间，确保内容不被底部按钮遮挡 -->
			<view class="bottom-space"></view>
		</view>

		<!-- 底部固定操作按钮 -->
		<view class="bottom-action">
			<button class="apply-btn" @click="makeCall">拨打电话</button>
		</view>
		
		<!-- 评论输入框 -->
		<view class="comment-input-wrapper" v-if="showCommentInput">
			<input 
						v-model="commentContent" 
						class="comment-input" 
						placeholder="请输入评论内容" 
						auto-focus
						@blur="handleInputBlur"
					/>
			<button class="send-btn" @click="submitComment">发送</button>
		</view>
	</view>
</template>

<script>
import { commentAdd, commentDelete, commentGetFirstLevelComment } from '../../api';
import { isLoggedIn } from '../../utils';
import { useUserStore } from '../../stores/user.js';

	export default {
		data() {
			return {
				// 职位数据
				positionData: {},
				comments: [/* {
						id: 1,
						username: '网友120489',
						content: '工作很轻松，基本都是手上的活',
						likes: 6,
						isLiked: false
					},
					{
						id: 2,
						username: '网友120489',
						content: '工作很轻松，基本都是手上的活',
						likes: 6,
						isLiked: true
					} */
				],
				// 评论相关数据
				showCommentInput: false,
				// commentList: [
				commentContent: ''
			}
		},
		// 页面加载时获取参数
		onLoad(options) {
			// 检查是否有dataSource参数
			if (options && options.dataSource) {
				try {
					// 解码并解析JSON字符串
					this.positionData = JSON.parse(decodeURIComponent(options.dataSource));
					console.log('接收到的职位数据:', this.positionData);
					this.handleGetFirstComment(this.positionData.jobId)
				} catch (e) {
					console.error('解析dataSource参数失败:', e);
				}
			}
		},
		methods: {
			longpress(item) {
				console.log("长按")
				console.log(item)
				const menu = ['举报']
				// 获取用户store实例
				const userStore = useUserStore();
				console.log(item.appUserId, userStore, userStore.loginRes.appUserId)
				// 检查用户是否已登录且评论是当前用户发表的
				if (userStore.loginRes.appUserId && item.appUserId === userStore.loginRes.appUserId) {
					menu.unshift('删除评论')
				}
				uni.vibrateShort()
				uni.showActionSheet({
					itemList: menu,
					success: (res) => {
						console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
						if (res.tapIndex === 0 && menu[0] === '删除评论') {
							// 删除评论逻辑
							this.deleteComment(item.id);
						}
					},
					fail: function (res) {
						console.log(res.errMsg);
					},
					})
			},
			async handleGetFirstComment(jobId) {
				const params = {
					jobId
				}
				const res = await commentGetFirstLevelComment(params)
				console.log(res)
				this.comments = res.data.records
			},
			
			// 删除评论
			deleteComment(commentId) {
				// 显示确认对话框
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这条评论吗？',
					success: async (res) => {
						if (res.confirm) {
							// 找到要删除的评论的索引
							const index = this.comments.findIndex(comment => comment.id === commentId);
							if (index !== -1) {
								// 从评论数组中移除该评论
								this.comments.splice(index, 1);
								// 这里可以添加调用删除评论API的逻辑
								// await commentDelete(commentId);
								await commentDelete({ commentId })
								// 显示删除成功提示
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 2000
								});
							}
						}
					}
				});
			},
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			// 点赞/取消点赞
			toggleLike(index) {
				if (this.comments[index].isLiked) {
					// 取消点赞
					this.comments[index].likes--;
				} else {
					// 点赞
					this.comments[index].likes++;
				}
				// 切换点赞状态
				this.comments[index].isLiked = !this.comments[index].isLiked;
			},
			// 申请职位
			makeCall(e) {
				e.stopPropagation();
				uni.makePhoneCall({
					phoneNumber: this.positionData.phoneNumber
				});
			},
			// 显示评论输入框
			showCommentBox() {
				// 延迟一下，确保输入框已经渲染
				if(!isLoggedIn()) {
					uni.showToast({
						title: '用户未登录',
						icon: 'none'
					})
					return
				}
				this.showCommentInput = true;
				setTimeout(() => {
					// 页面滚动到底部，确保评论区可见
					uni.pageScrollTo({
						scrollTop: 9999,
						duration: 300
					});
					// 尝试主动聚焦输入框，确保输入法弹出
					const inputElement = document.querySelector('.comment-input');
					if (inputElement) {
						inputElement.focus();
					}
				}, 100);
			},
			// 处理输入框失焦事件
			handleInputBlur() {
				// 延迟一下再隐藏，避免点击发送按钮时输入框过早消失
				setTimeout(() => {
					// 隐藏输入框
					this.showCommentInput = false;
					// 清空输入内容
					this.commentContent = '';
				}, 200);
			},
			// 提交评论
			async submitComment() {
				if (this.commentContent.trim()) {
					// 创建新评论对象
					/* const newComment = {
						id: Date.now(), // 使用时间戳作为临时ID
						username: '我',
						content: this.commentContent.trim(),
						likes: 0,
						isLiked: false
					}; */
					const params = {
						jobId: this.positionData.jobId,
						content: this.commentContent.trim(),
						parentId: 0,
					}
					const res = await commentAdd(params)
					const newComment = res.data;
					// 将新评论添加到评论列表开头
					this.comments.unshift(newComment);
					
					// 这里可以添加评论提交的API调用逻辑
					// console.log('提交评论:', this.commentContent);
					
					// 显示成功提示
					uni.showToast({
						title: '评论成功',
						icon: 'success',
						duration: 2000
					});
					
					// 重置输入框并隐藏
					this.commentContent = '';
					this.showCommentInput = false;
					
					// 失焦输入框，收起输入法
					const inputElement = document.querySelector('.comment-input');
					if (inputElement) {
						inputElement.blur();
					}
				} else {
					// 提示用户输入内容
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none',
						duration: 2000
					});
				}
			}
		}
	}
</script>

<style lang="scss">
	.position-detail-page {
		// 页面背景色
		background-color: #f5f5f5;
		height: 100vh;
		overflow: hidden;

		// 导航栏
		.nav-bar {
			height: 44px;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 16px;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 100;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

			.back-btn {
				width: 40px;
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 20px;
				color: #333;
			}

			.nav-title {
				font-size: 16px;
				font-weight: 500;
				color: #333;
			}

			.nav-right {
				width: 40px;
			}
		}

		// 内容包装器
		.content-wrapper {
			overflow-y: auto;
			max-height: calc(100vh);
			padding-bottom: 70px; // 为底部操作按钮留出空间
		}

		// 底部空间，确保内容不被底部按钮遮挡
		.bottom-space {
			height: 20px;
		}

		// 头部信息区域
		.header-section {
			background-color: #fff;
			padding: 16px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.factory-info {
				.factory-name {
					font-size: 18px;
					font-weight: 600;
					color: #333;
				}

				.factory-type {
					font-size: 14px;
					color: #0099ff;
					background-color: #e6f7ff;
					padding: 2px 6px;
					border-radius: 4px;
					margin-left: 8px;
				}

				.distance {
					font-size: 14px;
					color: #999;
					margin-left: 12px;
				}
			}

			.call-btn {
				height: 36px;
				padding: 0 16px;
				background-color: #ff4757;
				color: white;
				font-size: 14px;
				border: none;
				border-radius: 18px;
			}
		}

		// 工作时间区域
		.work-time-section {
			background-color: #fff;
			padding: 12px 16px;
			margin-top: 8px;

			.time,
			.business {
				font-size: 14px;
				color: #666;
				margin-right: 16px;
			}
		}

		// 薪资信息区域
		.salary-section {
			background-color: #fff;
			padding: 16px;
			display: flex;
			flex-direction: column;
			gap: 6rpx;
			// margin-top: 8px;

			.salary-item {
				margin-bottom: 16px;

				&:last-child {
					margin-bottom: 0;
				}

				.item-title {
					font-size: 16px;
					font-weight: 500;
					color: #333;
					margin-bottom: 8px;
					display: block;
				}

				.salary-content {
					font-size: 14px;
					color: #666;
					line-height: 1.6;
					white-space: pre-wrap;
				}
			}
		}

		// 福利信息区域
		.benefits-section {
			background-color: #fff;
			padding: 16px;
			margin-top: 8px;

			.benefits-content {
				font-size: 14px;
				color: #666;
				line-height: 1.6;
				margin-bottom: 8px;
				display: block;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}

		// 分隔线
		.divider {
			height: 12px;
			background-color: #f5f5f5;
			margin-top: 8px;
		}
		.add-comment-container {
			display: flex;
			gap: 6rpx;
			padding: 6rpx;
			background-color: #eee;
			border-radius: 4rpx;
			align-items: baseline;
			font-size: 24rpx;
			color: #999;
			.comment-icon {
				width: 24rpx;
				height: 24rpx;
			}
		}

		// 用户评价区域
		.comments-section {
			background-color: #fff;
			padding-top: 12px;

			.section-title {
				font-size: 16px;
				font-weight: 500;
				color: #333;
				padding: 0 16px 12px;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.comment-item {
					padding: 16px;
					transition: background-color 0.2s ease;

					/* 移动端触摸效果，仅在触摸时激活 */
					&:active {
						background-color: #f5f5f5;
					}
					
					/* 仅在支持hover的设备上(如桌面端)应用悬停效果 */
					@media (hover: hover) {
						&:hover {
							background-color: #f5f5f5;
						}
					}

					.user-info {
						display: flex;
						align-items: center;
						margin-bottom: 12px;

						.avatar {
							width: 36px;
							height: 36px;
							border-radius: 8rpx;
							background-color: #ddd;
							margin-right: 12px;
							overflow: hidden;
						}

						.username {
							font-size: 14px;
							color: #333;
						}
					}

				.comment-content {
					font-size: 15px;
					color: #333;
					line-height: 1.6;
					margin-bottom: 12px;
					display: block;
				}

				.image-container {
					display: flex;
					margin-bottom: 12px;

					.comment-image {
						width: 80px;
						height: 80px;
						background-color: #eee;
						border-radius: 4px;
						margin-right: 12px;

						&:last-child {
							margin-right: 0;
						}
					}
				}

				.like-section {
					display: flex;
					align-items: center;
					justify-content: flex-end;

					.like-count {
						font-size: 14px;
						color: #999;
						margin-right: 4px;
					}

					.like-icon {
						font-size: 16px;
						cursor: pointer;

						&.active {
							color: #ff4757;
						}
					}
				}
			}

			.comment-divider {
				height: 1px;
				background-color: #eee;
				margin: 0 16px;
			}
		}

		// 底部固定操作按钮
		.bottom-action {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 50px;
			background-color: #fff;
			padding: 8px 16px;
			box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 99;

			.apply-btn {
				height: 40px;
				width: 100%;
				background-color: #ff4757;
				color: white;
				font-size: 16px;
				font-weight: 500;
				border: none;
				border-radius: 20px;
			}
		}
		
		// 评论输入框样式
		.comment-input-wrapper {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			padding: 10px 16px;
			padding-bottom: 28rpx;
			display: flex;
			align-items: center;
			z-index: 101;
			transform: translateZ(0);
			will-change: transform;
			/* 关键样式：确保在输入法弹出时能正确显示 */
			transition: transform 0.3s ease;
			/* 适配iOS和Android */
			padding-bottom: calc(10px + env(safe-area-inset-bottom, 0));
			
			.comment-input {
				flex: 1;
				height: 36px;
				padding: 0 12px;
				background-color: #f5f5f5;
				border: 1px solid #ddd;
				border-radius: 18px;
				font-size: 14px;
				/* 强制输入法弹出 */
				:-webkit-autofill {
					-webkit-text-fill-color: #333;
				}
				/* 确保输入框可以获取焦点并弹出输入法 */
				:-webkit-input-placeholder {
					color: #999;
				}
				user-select: text;
			}
			
			.send-btn {
				height: 36px;
				padding: 0 16px;
				margin-left: 12px;
				background-color: #ff4757;
				color: white;
				font-size: 14px;
				border: none;
				border-radius: 6px;
				/* 按钮交互效果 */
			}
		}
		
		/* 适配安全区域，特别是iPhone底部横条 */
		@supports (padding-bottom: env(safe-area-inset-bottom)) {
			.comment-input-wrapper {
				padding-bottom: calc(10px + env(safe-area-inset-bottom));
			}
		}
	}
</style>