<template>
	<view class="page-container" v-if="detail">
		<!-- 内容区域 -->
		<view class="content-box">
			<view class="content-container">
				<!-- 主体内容 -->
				<view class="post-content">
					<view class="post-image">
						<view class="image-list-box">
							<up-swiper indicatorInactiveColor="#CCCCCC" indicatorActiveColor="#F8C008" bgColor="#fff"
								:imgMode="swiperList[currentIndex]?.mode" :autoplay="false" @click="clickSwiper"
								@change="({current})=>currentIndex = current" height="263" :list="detail.imageUrlList"
								keyName="url"></up-swiper>
						</view>
						<!-- <view v-else class="image-box">
              <image :src="detail.imageUrlList[0]" mode="widthFix" />
            </view> -->
					</view>
					<view class="post-indicator">
						<view class="post-indicator-list">
							<view :class="{active:index == currentIndex}" class="post-indicator-li"
								v-for="(item,index) in detail.imageUrlList" :key="index"></view>
						</view>
					</view>
					
					<view class="post-box">
						<view class="post-box-main">
							<view class="post-title">
								<text>{{ detail.title }}</text>
							</view>
							<view class="post-text">
								<text>{{ detail.content }}</text>
							</view>
							<view class="post-info">
								<text class="post-time">{{ detail.publishTime }}</text>
								<!-- <text class="post-views">共{{ detail.commentCount }}条评论</text> -->
							</view>
						</view>
						
					</view>
				</view>
				<view class="fixed-view"></view>
				<!-- 评论区 -->
				<view class="comment-section" ref="commentSection">
					<view class="comment-title">
						<text>全部评论 ({{ detail.commentCount }})</text>
					</view>
					<!-- 评论列表 -->
					<Comment :commentType="commentType" ref="commentRef" @clickComment="clickComment"
						@moveMessageTop="clickMessageIcon" @inputDone="inputDone" />
				</view>
			</view>
		</view>
		<!-- 这里是底部input聚焦弹窗键盘时，真实输入框 -->
		<view :class="['keybord-input-box', keybordHeight > 0 ? 'keybord-fixed' : '']">
			<up-overlay :show="keybordOverlay" @click="keybordHeight = 0">
				<view class="overlay-input-box" :style="
            keybordHeight > 0 ? '--tabbar-bottom:' + keybordHeight + 'px' : ''
          ">
					<view class="comment-input-container">
						<input :focus="keybordFocus" border="none" :adjustPosition="false" class="comment-input"
							type="text" confirm-type="send" :auto-blur="true" :confirm-hold="confirmHold"
							v-model="commentText" :placeholder="commentInputPl" @focus="commentInputFocus"
							@blur="commentInputBlur" @confirm="handleInputConfirm" />
					</view>
					<view class="right-box" @click="handleInputConfirm">
						<button type="default">发送</button>
					</view>
				</view>
			</up-overlay>
		</view>

		<!-- 底部互动栏 -->
		<up-tabbar class="u-bottom-tabbar">
			<view class="toAPP">
				<wx-open-launch-app id="launch-btn" appid="wx5f33a4ace799b661"
					:extinfo="'/pages/goods_details/index?articleId=' + articleId" @error="goShuiBei">

					<component :is="'script'" v-bind="{type:'text/wxtag-template'}">
						<button class="storeAPP" style="background-color: #e9c279;
				color: #fff;
				border-radius: 50rpx;
				line-height:100rpx;
				padding: 20rpx 20rpx;
				z-index: 999;box-sizing: border-box;">

							打开水贝商城
						</button>
					</component>

				</wx-open-launch-app>
			</view>
			<view class="bottom-bar">
				<view @click.stop="clickFooterInput" class="comment-input-container">
					<input border="none" :adjustPosition="false" class="comment-input" type="text" :readonly="true"
						:disabled="true" confirm-type="发送" :auto-blur="true" placeholder="说点什么..." />
				</view>
				<view class="right-box">
					<view class="item" @click="handleLike">
						<uni-icons type="heart" size="24"></uni-icons>
						<text>{{ detail.likeCount }}</text>
					</view>
					<view class="item" @click="handleCollection">
						<uni-icons type="star" size="24"></uni-icons>
						<text>{{ detail.collectCount }}</text>
					</view>
					<view class="item" @click="clickMessageIcon">
						<uni-icons type="chat" size="24"></uni-icons>
						<text>{{ detail.commentCount }}</text>
					</view>
				</view>
			</view>
		</up-tabbar>

		<!-- 右上角操作popup -->
		<up-popup :show="showActionPopup" @close="showActionPopup = false">
			<view class="popup-box">
				<view class="close-box" @click="showActionPopup = false">
					<uni-icons type="closeempty" size="28"></uni-icons>
				</view>
				<view class="header">
					<view class="title">更多操作</view>
				</view>
				<view class="actions-menu">
					<view @click="handleDelete" class="item-action">
						<view class="icon-box">
							<uni-icons type="trash" size="28"></uni-icons>
						</view>
						<view class="icon-name">删除</view>
					</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		getCurrentInstance,
		nextTick,
		computed
	} from "vue";
	import {
		onLoad,
		onReady,
		onHide,
		onShow
	} from "@dcloudio/uni-app";
	import {
		useToast
	} from "@/hooks/useToast";
	import {
		getArticleDetailId,
		getGoodDetailId,
		getWechatConfig,
		setUserState
	} from "@/api/index.js"
	// import { setUserState } from "@/api/book.js"
	import {
		browser,
		openApp
	} from "@/utils/ifApp.js"
	
	import Comment from "@/components/comment/index";
	import FollowBtn from "@/components/followBtn/index";
	import wx from 'weixin-js-sdk'
	const {
		Toast
	} = useToast();
	const goShuiBei = () => {
		let url = `shuibei://`
		let errUrl = "https://a.app.qq.com/o/simple.jsp?pkgname=uni.app.UNI9DE338F"
		window.location.href = url;
		setTimeout(() => {
			window.location.href = errUrl;
		}, 3000);
		// window.location.href = ;
		// setTimeout(() => {
		// 	window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=uni.app.UNI9DE338F";
		// }, 3000);
		// if (browser.versions.android) {

		// }else{
		// 	uni.navigateTo({
		// 		url:"/pages/index/index"
		// 	})
		// }

	}
	const initwxlaunch = () => {
		getWechatConfig(encodeURIComponent(location.href.split('#')[0])).then(res => {

			wx.config({
				debug: res.data
					.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: res.data.appId, // 必填，公众号的唯一标识
				timestamp: res.data.timestamp, // 必填，生成签名的时间戳
				nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
				signature: res.data.signature, // 必填，签名,// 必填，签名
				jsapi_ticket: res.data.jsapi_ticket, // 必填，签名,// 必填，签名
				jsApiList: ['wx-open-subscribe',
					'wx-open-launch-app'
				], // 必填，需要使用的JS接口列表，这个地方必须至少写一个，即使你一个都不想用'updateTimelineShareData',
				openTagList: ['wx-open-subscribe', 'wx-open-launch-app']
				// 可选，需要使用的开放标签列表
			});

			wx.checkJsApi({
				jsApiList: ['wx-open-launch-app'], // 校验跳转APP的标签是否可用
				success: function(res) {
					console.log('可用')
				},
				fail: (err) => {
					console.log(err, '不可用')
				}
			})
		})

	}
	initwxlaunch()
	const instance = getCurrentInstance();

	const articleId = ref("");
	const detail = ref(null);
	
	const currentIndex = ref(0) //指示点下标
	const swiperList = ref([])

	const isOwner = computed(() => {

	});

	onLoad((options) => {

		if (!options.articleId) {
			Toast({
				title: "该文章不存在",
				icon: "none"
			});
			// uni.navigateTo({ url: "/pages/index/index" });
			return;
		}
		articleId.value = options.articleId || "";
		fetchArticleDetail();
	});

	onReady(() => {
		uni.onKeyboardHeightChange && uni.onKeyboardHeightChange(listenerKeybord);
	});

	onShow(() => {
		// 监听关注状态变更事件
		uni.$on("followStateChanged", handleFollowStateChanged);
	});

	onHide(() => {
		uni.offKeyboardHeightChange && uni.offKeyboardHeightChange(listenerKeybord);
		// 移除关注状态变更监听
		uni.$off("followStateChanged", handleFollowStateChanged);
	});

	// const preivewMap = computed(() => {
	//   if (detail?.imageUrlList.length > 0) {
	//     return detail.imageUrlList.map(v => v.)
	//   }
	//   return []
	// })
	const onListenLaunchError = () => {
		let errUrl = "https://a.app.qq.com/o/simple.jsp?pkgname=uni.app.UNI9DE338F"
	}

	function clickSwiper(index) {
		console.log("index", index);
		uni.previewImage({
			current: index,
			urls: detail.value?.imageUrlList || [],
		});
	}

	// 监听键盘高度变化
	function listenerKeybord(res) {
		if (res.height === 0) {
			keybordHeight.value = 0;
		} else {
			uni.getSystemInfo({
				success(systemRes) {
					const screenHeight = systemRes.screenHeight;
					const windowHeight = systemRes.windowHeight;
					const disHeight = screenHeight - windowHeight;
					keybordHeight.value = res.height - disHeight;
				},
			});
		}
	}

	async function fetchArticleDetail() {
		try {
			uni.showLoading({
				title: "加载中",
				mask: true
			});
			const {
				data
			} = await getGoodDetailId(articleId.value);
			detail.value = data;
			swiperList.value = []
			data.imageUrlList.forEach(async item => {
				const res = await uni.getImageInfo({
					src: item, // 图片路径，可以是本地路径、临时路径、网络URL
				});
				swiperList.value.push({
					url: item,
					mode: res.height > res.width ? 'aspectFit' : 'aspectFill',
					type: 'image',
					height:res.height
				})
			})
			// detail.value.followMark = true
			
			uni.hideLoading();
		} catch (error) {
			console.error("fetchArticleDetail", error);
			uni.hideLoading();
		}
	}

	const commentText = ref("");

	function rightClick() {}
	const goBack = () => {
		const pages = getCurrentPages();
		if (pages.length > 1) {
			uni.navigateBack();
		} else {
			uni.switchTab({
				url: "/pages/index/index"
			});
		}
	};

	const showActionPopup = ref(false);

	function handleActions() {
		showActionPopup.value = true;
	}

	function handleDelete() {
		showActionPopup.value = false;
		uni.showModal({
			title: "提示",
			content: "确认删除?",
			success: async function(res) {
				if (res.confirm) {
					try {

					} catch (error) {
						console.error("deleteArticle", error);
					}
				}
			},
		});
	}

	// 跳转用户详情页
	function toUserPage() {

		uni.navigateTo({
			url: `/pages/user/personal?id=${detail.value.userId}`
		});
	}
	// 点击某条评论时触发此事件
	const commentType = ref("add"); // 类型 - 新增评论/回复评论
	const commentInputPl = ref("说点什么...");

	function clickComment(comment) {
		const username = comment.userName;
		commentType.value = "reply";
		commentInputPl.value = `回复 @${username}`;
		keybordFocus.value = true;
	}

	// 确认发布评论 - 点击键盘的发送和输入框右侧的发送按钮
	const confirmHold = ref(true);
	const commentRef = ref();

	function handleInputConfirm(event) {
		// 如果发送的内容为空格 阻止键盘收起并提示
		if (commentText.value?.trim() === "") {
			confirmHold.value = true;
			return Toast({
				title: "有内容才能发送哦"
			});
		}

		confirmHold.value = false;
		commentRef.value.handleAddComment(commentText.value);
	}

	// 评论发布完成后触发
	function inputDone() {
		commentText.value = "";
	}

	/**
	 * 点击右下角聊天icon需要将评论区域滚动到顶部
	 * 这里计算滚动的距离
	 */
	const commentSection = ref();
	const commentOffsetTop = ref(0);
	watch(
		() => detail.value,
		async (val, oldVal) => {
			if (val && !oldVal) {
				await nextTick();
				const query = uni.createSelectorQuery().in(instance.proxy);
				query
					.select(".comment-section")
					.boundingClientRect((data) => {
						if (data.top) {
							commentOffsetTop.value =
								data.top - 60;
						}
					})
					.exec();
			}
		}
	);

	// 点击底部右下角消息事件
	function clickMessageIcon() {
		uni.pageScrollTo({
			scrollTop: commentOffsetTop.value,
			// selector: ".fixed-view",
			success() {
				console.log("success");
			},
			fail(e) {
				console.error(`scrollTo error ${e}`);
			},
		});
	}

	// 点击收藏
	const collectionLoading = ref(false);
	async function handleCollection() {
		try {
			if (collectionLoading.value) return;
			collectionLoading.value = true;
			await setUserState({
				type: 1,
				bookId: detail.value.id
			});

			detail.value.collectMark = !detail.value.collectMark;
			if (detail.value.collectMark) {
				detail.value.collectCount += 1;
			} else {
				detail.value.collectCount -= 1;
			}

			collectionLoading.value = false;
		} catch (error) {
			console.error("collection error", error);
			collectionLoading.value = false;
		}
	}

	// 点击喜欢
	const likeLoading = ref(false);
	const likeAnimation = ref(false);
	async function handleLike() {
		try {
			if (likeLoading.value) return;

			likeLoading.value = true;
			await setUserState({
				type: 0,
				bookId: detail.value.id
			});

			detail.value.likeMark = !detail.value.likeMark;
			if (detail.value.likeMark) {
				likeAnimation.value = true;
				detail.value.likeCount += 1;
			} else {
				likeAnimation.value = false;
				detail.value.likeCount -= 1;
			}

			likeLoading.value = false;
		} catch (error) {
			likeLoading.value = false;
			Toast({
				title: "点赞失败"
			});
			console.error("handleLike", error);
		}
	}

	// ------- 底部input和弹窗评论input相关事件 --------
	// 键盘高度
	const keybordHeight = ref(0);
	// 键盘弹同出时的遮罩状态
	const keybordOverlay = ref(true);
	// 真实input的聚焦状态
	const keybordFocus = ref(false);
	// input聚焦事件
	function commentInputFocus(event) {
		//   const height = event.detail.keybordHeight || 1000
		//   console.log('height',height)
		//   if (height) {
		//     keybordHeight.value = height;
		//     console.log('keybordHeight',keybordHeight.value)
		//   }
	}

	// input失焦事件
	function commentInputBlur() {
		keybordHeight.value = 0;
		keybordFocus.value = false;
	}
	// 点击底部input触发事件
	function clickFooterInput() {
		console.log("点击了底部Input");
		commentInputPl.value = "说点什么...";
		commentType.value = "add";
		keybordFocus.value = true;
	}

	// 处理关注状态变更
	function handleFollowStateChanged(data) {
		if (Number(data.userId) === Number(detail.value?.userId)) {
			detail.value.followMark = data.followMark;
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/uni_modules/uview-plus/theme.scss';

	.page-container {
		display: flex;
		flex-direction: column;

		.nav-bar {
			position: absolute;

			.u-navbar--fixed {
				// padding-top: 20rpx;
			}

			.user-box {
				display: flex;
				align-items: center;

				.user-avatar {}

				.username {
					margin-left: 20rpx;
				}
			}
		}

		.content-box {
			

			.content-container {

				.post-content {
					.post-indicator {
						&-list {
							height: 40rpx;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					
						&-li {
							width: 8rpx;
							height: 8rpx;
							margin-right: 4rpx;
							background: #CCCCCC;
							border-radius: 4rpx;
							transition: all 0.3s ease;
					
							&:last-child {
								margin-right: 0;
							}
						}
					
						.active {
							width: 32rpx;
							background: #F8C008;
						}
					}
					.post-box {
						padding: 0 16rpx;
						.post-box-main {
							border-bottom: 2rpx solid #F1F3F8;
						}
					}

					.post-title {

						margin-bottom: 16rpx;
						
						text {
							font-size: 32rpx;
							font-weight: bold;
							color: #333333;
							line-height: 48rpx;
						}
					}

					.post-image {
						

						// background-color: #f5f0ff;
						.image-box {
							width: 100%;
						}

						::v-deep .image-list-box {
							width: 100%;

							.coverImage {
								width: 100%;
								min-height: 65vh;
							}

							.u-swiper__wrapper__item__wrapper {
								height: 100%;
								display: flex;
								flex-direction: column;
								justify-content: center;

								.u-swiper__wrapper__item__wrapper__image {
									width: 100%;
									flex: 0 1 auto;
									border-radius: 0 !important;
									color: #e3e3e3;
									// height: 100% !important;
									// margin-top: 50%;
									// transform: translateY(-50%);
								}
							}
						}
					}

					

					.post-info {
						display: flex;
						justify-content: space-between;
						margin-top: 20rpx;

						.post-time,
						.post-views {
							font-size: 12px;
							color: #999;
						}
					}
				}

				.comment-section {
					// margin-top: 20rpx;
					background-color: #fff;
					border-radius: 20rpx;
					padding: 30rpx;
					// margin-bottom: 10rpx;

					.comment-title {
						margin-bottom: 30rpx;

						text {
							font-size: 16px;
							font-weight: bold;
							color: #333;
						}
					}

					.comment-list {
						.comment-item {
							padding: 20rpx 0;
							border-bottom: 1px solid #f5f5f5;

							.comment-user {
								display: flex;
								align-items: center;
								margin-bottom: 16rpx;

								.comment-avatar {
									width: 60rpx;
									height: 60rpx;
									border-radius: 30rpx;
									margin-right: 16rpx;
								}

								.comment-user-info {
									display: flex;
									flex-direction: column;

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

									.comment-time {
										font-size: 12px;
										color: #999;
										margin-top: 4rpx;
									}
								}
							}

							.comment-content {
								margin: 10rpx 0;

								text {
									font-size: 14px;
									color: #333;
									line-height: 1.5;
								}

								.at-user {
									color: #ff2442;
									font-weight: 500;
								}
							}

							.comment-actions {
								display: flex;
								margin-top: 16rpx;

								.like-btn,
								.reply-btn {
									display: flex;
									align-items: center;
									margin-right: 30rpx;

									text {
										font-size: 12px;
										color: #999;
										margin-left: 8rpx;
									}
								}
							}

							.nested-replies {
								margin-left: 76rpx;
								margin-top: 20rpx;
								background-color: #f8f8f8;
								border-radius: 16rpx;
								padding: 20rpx;

								.nested-reply-item {
									margin-bottom: 20rpx;

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



		.bottom-bar {
			width: 100%;
			background-color: #fff;
			padding: 20rpx 25rpx 20rpx;
			box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
			display: flex;
			align-items: center;
			justify-content: space-around;

			.interaction-btns {
				display: flex;
				justify-content: space-around;
				padding-bottom: 20rpx;

				.like-btn,
				.comment-btn,
				.share-btn {
					display: flex;
					flex-direction: column;
					align-items: center;

					text {
						font-size: 12px;
						color: #999;
						margin-top: 8rpx;
					}
				}
			}

			.right-box {
				display: flex;
				flex: 1;
				align-items: center;
				justify-content: space-between;

				.item {
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 40rpx;
					text-align: center;

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

					text {
						margin-left: 6rpx;
						white-space: nowrap;
					}
				}
			}
		}

		.keybord-input-box {
			position: fixed;
			z-index: -1;

			&.keybord-fixed {
				z-index: 99999;

				.overlay-input-box {
					// position: absolute;
					bottom: var(--tabbar-bottom, 350px) !important;
					// bottom: 500px;
				}
			}

			.overlay-input-box {
				position: fixed;
				left: 0;
				right: 0;
				bottom: 0;
				width: 100%;
				padding: 20rpx 20rpx;
				background-color: #fff;
				align-items: center;
				display: flex;
				transition: bottom 0.15s;
				z-index: 99;
			}

			.comment-input-container {
				margin: 0 20rpx 0 0;
				flex: 1;

				input {
					min-height: 0;
					height: 32rpx;
				}
			}

			.right-box {
				button {
					border-radius: 30rpx;
					padding: 10rpx 20rpx;
					background-color: #ff2442;
					color: #fff;
					font-size: 25rpx;
				}
			}
		}

		.comment-input-container {
			// width: 40%;
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 40rpx;
			padding: 16rpx 30rpx;
			margin: 0 30rpx 0 0;

			.comment-input {
				flex: 1;
				font-size: 14px;
				pointer-events: none;
			}
		}
	}

	.popup-box {
		position: relative;
		background-color: #f5f5f5;

		.close-box {
			position: absolute;
			right: 10rpx;
			top: 10rpx;
		}

		.header {
			text-align: center;
			padding: 15rpx 0;
		}

		.actions-menu {
			padding: 15rpx 30rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.item-action {
				display: flex;
				flex-direction: column;
				justify-self: center;
				align-items: center;

				.icon-box {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50rpx;
					background-color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-bottom: 10rpx;
				}

				.icon-name {
					font-size: 24rpx;
					color: #484848;
				}
			}
		}
	}

	::v-deep .u-bottom-tabbar {
		flex: 0;

		.toAPP {
			min-width: 30%;
			position: absolute;
			top: -100rpx;

			.storeAPP {
				background-color: #e9c279;
				color: #fff;
				border-radius: 50rpx;
				line-height: 50rpx;
				padding: 20rpx 20rpx;
				z-index: 999;

				.logoimg {
					display: inline-block;
					width: 50rpx;
					height: 50rpx;
					border-radius: 5rpx;
					vertical-align: middle;
				}
			}
		}

		.u-tabbar--fixed {
			z-index: 99 !important;
		}

		.u-tabbar__content__item-wrapper {
			height: 60px;
		}
	}

	::v-deep .u-modal__button-group__wrapper--confirm .u-modal__button-group__wrapper__text {
		color: $note-red !important;
	}

</style>