<template>
	<view>
		<view class="dynamic-item" @click="toDynamicDetailPage">
			<view class="user-info-box" style="position: relative;">
				<image class="avatar" v-if="form.faceImg" :src="form.faceImg" @error="imgLoadFail"></image>
				<!-- <image class="avatar" v-else src="/static/images/default-avatar.png"></image> -->
				<view class="user-name">{{form.nickName}}</view>
				<view class="top-icon" v-if="form.isTop==1">
					<image class="icon" src="/static/images/is-top.png"></image>
				</view>
				
				<image v-if="deleteable || userInfo.bbsAdmin || form.isSelf==1" class="more-icon"
					@click.stop="handleDelDynamics" src="/static/images/more-icon.png"></image>
				<image v-else class="more-icon" src="/static/images/more-icon.png"></image>
				<!-- 删除按钮 -->
				<view class="del-btn" v-if="showDelBtn" @click.stop="handleDel"
					:style="'left:' + clientX + 'rpx;' +'top:' + clientY + 'rpx'">
					删除动态</view>
			</view>
			<view class="topics-box" v-if="form.topicNames && form.topicNames.length >0">
				<template v-for="(name,index) in form.topicNames">
					<view class="topic-box-common" @click.stop="toTopicDetailPage(name,index)"># {{name}}</view>
				</template>
			</view>
			<view class="dynamic-content-box">

				<rich-text v-if="preNodes.length > 0" :nodes="preNodes" class="text"></rich-text>
				<view class="imgs" v-if="form.type=='IMAGE'&&form.attachments && form.attachments.length > 0">
					<template v-for="(item,index) in form.attachments">
						<image class="item" :src="item.url" @click.stop="preview(form.attachments,index)"></image>
					</template>
				</view>
				<view class="imgs" v-if="form.type=='VIDEO'&&form.attachments && form.attachments.length > 0">
					<template v-for="(item,index) in form.attachments">
						<video class="item" :src="item.url" :show-fullscreen-btn="false" :show-center-play-btn="false"
							@click.stop="videoPreview(item.url)"></video>
					</template>
				</view>
			</view>
			<view class="datetime-box">{{form.createTime}}</view>
			<view class="operation-box">
				<view class="flex-layout">
					<view class="favorite-box">
						<image src="/static/images/favorite.png" v-if="form.isLike==0" class="icon"
							@click.stop="handleUpdateLikeStatus(1)"></image>
						<image src="/static/images/favorite-active.png" v-if="form.isLike==1"
							@click.stop="handleUpdateLikeStatus(0)" class="icon"></image>
						<view class="num">{{form.likeCount}}</view>
					</view>
					<view class="favorite-box ml-10">
						 <image src="/static/images/comment.png" class="icon"></image>
						<view class="num">{{form.commentCount}}</view>
					</view>
				</view>
				<view class="comment-box" v-if="displayComment" @click.stop="handleOpenComment">
					<image class="icon" src="/static/images/comment-icon.png"></image>
					<view class="text">评论</view>
				</view>
			</view>
			<!-- pk -->
			<view class="pk-box" v-if="form.isEnableVote==1">
				<view class="pk-title-box">
					<image src="/static/images/pk-icon.png" class="pk-icon"></image>
					<view class="pk-title-text">{{form.voteTitle}}</view>
				</view>
				<view class="pk-imgs" v-if="form.voteOptionType=='IMAGE'&&form.voteOptions&&form.voteOptions.length>0 ">
					<template v-for="(item,index) in form.voteOptions">
						<image :src="item.imageUrl" @click.stop="preview(form.voteOptions,index)" class="img"></image>
					</template>
				</view>
				<!-- 未投票 -->
				<view v-if="form.isVote==0">
					<view class="pk-btns" v-if="form.voteOptions&&form.voteOptions&&form.voteOptions.length>0 ">
						<view class="btns red-btn" @click.stop="handleVote(form.voteOptions[0])">
							{{form.voteOptions[0].name}}
						</view>
						<image src="/static/images/pk-img.png" class="img"></image>
						<view class="btns blue-btn" @click.stop="handleVote(form.voteOptions[1])">
							{{form.voteOptions[1].name}}
						</view>
					</view>
					<view class="pk-tips">点击上方按钮，选择你的观点</view>
				</view>
				<!-- 已投票，显示投票结果 -->
				<view v-if="form.isVote==1">
					<view class="pk-results">
						<view class="left" @click.stop="toPKDetailPage(0)">
							<view class="left-num">{{form.voteOptions[0].name}} {{form.voteOptions[0].voteCount}}</view>
						</view>
						<view class="left" :style="'width:' + ((form.voteOptions[0].voteCount/(form.voteOptions[0].voteCount+form.voteOptions[1].voteCount))*100)+'%'"
							@click.stop="toPKDetailPage(0)">
							<view class="results-item left-item"></view>
						</view>
						
					</view>
					<view class="pk-results">
						<view class="right" @click.stop="toPKDetailPage(1)">
							<view class="right-num">{{form.voteOptions[1].name}} {{form.voteOptions[1].voteCount}}
							</view>
						</view>
						<view class="right" :style="'width:' + ((form.voteOptions[1].voteCount/(form.voteOptions[0].voteCount+form.voteOptions[1].voteCount))*100)+'%'"
							@click.stop="toPKDetailPage(1)">
							<view class="results-item right-item"></view>
						</view>
					</view>
					<view class="results-sum" @click.stop="toPKDetailPage(0)">
						<view>{{form.voteCount}}人参与</view>
						<image src="/static/images/detail-icon.png" class="icon"></image>
					</view>
				</view>
			</view>
			<!-- 评论区 -->
			<!-- <view class="comment-box" v-if="form.isEnableComment==1">
				<view class="comment-display-box" v-if="form.comments&& form.comments.length>0">
					<view class="comment-item" v-for="(item,index) in form.comments">
						<view class="user-info">
							<view style="display: flex;align-items: center;">
								<view class="username">{{item.nickName}}</view>
								<view class="datetime">{{item.createTime}}</view>
							</view>
							<view class="operation-text">
								<view v-if="item.isFeatured==1" style="color: #F2AC39;margin-right: 10rpx;">精选</view>
								<view style="color: #bbb;" v-if="item.isSelf==1 || userInfo.bbsAdmin"
									@click.stop="handleDelete(item)">删除</view>
							</view>
						</view>
						<view class="content">
							<view class="text" v-if="!item.replyNickName" @click.stop="handleReplayComment(item)">
								{{item.content}}
							</view>

							<view class="text" v-else @click.stop="handleReplayComment(item)">
								回复<span style="color: #0058B6;">{{item.replyNickName}}</span>{{item.content}}
							</view>
						</view>
					</view>
				</view>
			</view> -->
		</view>
		<!-- 发布评论区 -->
		<publish-comment :form="form" ref="publishCommentRef" @refresh="$emit('refresh')"></publish-comment>
		<!-- 视频预览 -->
		<video-preview ref="videoPreviewRef"></video-preview>
	</view>
</template>

<script>
	import {
		dynamicLikeUnlike,
		delMonment,
		dynamicVote,
		delComment
	} from '@/api/api.js'
	import PublishComment from './PublishComment.vue';
	import VideoPreview from './VideoPreview.vue';
	import emotions from '@/utils/emjo';
	import defalutAvatar from '/static/images/default-avatar.png'
	import {
		getUserInfo
	} from '@/utils/auth';
	import {generateSignature} from '@/utils/common.js';
	export default {
		name: "Dynamic-Item",
		data() {
			return {
				commentList: [],
				showComment: false,
				commentContent: '',
				clientX: 0,
				clientY: 0,
				showDelBtn: false,
				preNodes: [],
				emotions,
				userInfo: {}
			};
		},
		components: {
			PublishComment,
			VideoPreview
		},
		props: {
			form: {
				type: Object,
				default: {}
			},
			deleteable: {
				type: Boolean,
				default: false
			},
			displayComment:{
				type: Boolean,
				default: false
			}
		},
		watch: {
			// 当内容变化时自动更新预览
			"form.content": {
				immediate: true,
				handler(val, oldVal) {
					if (val === oldVal) {
						return;
					}
					this.userInfo = JSON.parse(JSON.parse(getUserInfo()))
					this.form.faceImg = generateSignature(this.userInfo.userName)
					console.log(this.form.faceImg)
					this.preNodes = this.formatContent(val)
				}
			}
		},

		methods: {
			// 点赞/取消点赞
			handleUpdateLikeStatus(likeStatus) {
				let data = {
					momentId: this.form.id,
					likeStatus
				}
				if (likeStatus == '1') {
					this.form.likeCount = this.form.likeCount + 1
					this.form.isLike = 1
				}
				if (likeStatus == '0') {
					this.form.likeCount = this.form.likeCount - 1
					this.form.isLike = 0
				}
				dynamicLikeUnlike(data).then(res => {
					if (res.code == 200) {
						// this.$emit('refresh')
					}
				})

			},
			formatContent(content) {
				const nodes = [];
				const emotionMap = {};

				// 创建表情符号到iconfont的映射
				this.emotions.forEach(emotion => {
					emotionMap[emotion.symbol] = emotion.code;
				});

				// 提取所有表情符号并按长度排序
				const emotionSymbols = Object.keys(emotionMap).sort((a, b) => b.length - a.length);

				while (content.length > 0) {
					let found = false;

					// 查找是否有表情符号
					for (const symbol of emotionSymbols) {
						if (content.startsWith(symbol)) {
							// 添加表情节点
							nodes.push({
								name: 'span',
								attrs: {
									class: `iconfont ${emotionMap[symbol]} emotion-icon`
								},
							});
							content = content.slice(symbol.length);
							found = true;
							break;
						}
					}

					// 如果没有找到表情，提取普通文本
					if (!found) {
						// 找到下一个表情的位置
						let nextEmotionIndex = content.length;
						for (const symbol of emotionSymbols) {
							const index = content.indexOf(symbol);
							if (index !== -1 && index < nextEmotionIndex) {
								nextEmotionIndex = index;
							}
						}

						// 提取文本并按换行符分割
						const text = content.slice(0, nextEmotionIndex);
						if (text) {
							const textParts = text.split('\n'); // 按换行符分割
							textParts.forEach((part, idx) => {
								if (part) {
									// 添加普通文本节点
									nodes.push({
										type: 'text',
										text: part
									});
								}
								// 除了最后一部分，每个分割后都加<br/>
								if (idx < textParts.length - 1) {
									nodes.push({
										name: 'br' // 添加<br/>标签实现换行
									});
								}
							});
						}
						content = content.slice(nextEmotionIndex);
					}
				}

				return nodes;
			},
			// 打开评论区
			handleOpenComment() {
				// this.showComment = true
				const {isEnableVote,isVote} = this.form;
				// 如果开启pk，则必须先已经投票才可以评论
				if(isEnableVote == 1){
					if(isVote == 1){
						this.$refs.publishCommentRef.openModal()
					}else{
						uni.showToast({
							title: '请先点击上方PK按钮，选择你的观点后才可进行评论',
							icon:'none',
							duration:3000
							
						})
						return;
					}
				}else{
					this.$refs.publishCommentRef.openModal()
				}
				
			},
			// 回复评论
			handleReplayComment(item) {
				console.log(item)
				this.$refs.publishCommentRef.openModal(item)
			},
			// 展示删除动态按钮
			handleDelDynamics(e) {
				this.showDelBtn = !this.showDelBtn
				this.clientX = (e.target.offsetLeft * 2 - 148);
				this.clientY = ((e.target.offsetTop * 2) + 34);
			},
			// 删除动态
			handleDel() {
				let _this = this;
				uni.showModal({
					title: '提示',
					content: '是否确认删除动态？',
					success: function(res) {
						if (res.confirm) {
							delMonment(_this.form.id).then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: '删除成功',
									})
									_this.$emit('deleteSuccess');
									uni.$emit('hanldeDynamicRefresh')
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 投票
			handleVote(item) {
				let data = {
					momentId: this.form.id,
					optionCode: item.code
				}
				dynamicVote(data).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '投票成功'
						})
						uni.$emit('hanldeDynamicRefresh')
						this.$emit('refreshCurrent', this.form.id)
					}
				})
			},
			// 删除评论
			handleDelete(item) {
				let _this = this;
				uni.showModal({
					title: '提示',
					content: `是否确认删除评论：${item.content}？`,
					success: function(res) {
						if (res.confirm) {
							delComment(item.id).then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: `删除成功`
									})
									_this.$emit('refresh');

								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 预览图片
			preview(list, index) {
				console.log(list, index)
				let urls = list.map((item) => {
					return item.imageUrl;
				})
				if (urls.length > 0) {
					uni.previewImage({
						urls: urls,
						current: index
					});
				}
			},
			imgLoadFail() {
				this.form.faceImg = defalutAvatar
			},
			//预览视频
			videoPreview(url) {
				this.$refs.videoPreviewRef.openModal(url)
			},
			toDynamicDetailPage() {
				let pathName = window.location.pathname
				if (pathName.indexOf('/pages/dynamic-detail/dynamic-detail') > -1) {
					return;
				}
				uni.navigateTo({
					url: '/pages/dynamic-detail/dynamic-detail?momentId=' + this.form.id
				})
			},
			toTopicDetailPage(name, index) {
				let topicId = this.form.topicIds[index]
				uni.navigateTo({
					url: `/pages/topic-detail/topic-detail?topicId=${topicId}&topicName=${name}`
				})
			},
			toPKDetailPage(index) {
				let item = this.form.voteOptions[index];
				let options = JSON.stringify(this.form.voteOptions)
				uni.navigateTo({
					url: `/pages/pk-detail/pk-detail?momentId=${this.form.id}&index=${index}&voteOptions=${options}`
				})
			}
		}
	}
</script>

<style lang="scss">
	@import '@/static/styles/index.scss';

	.del-btn {
		position: absolute;
		width: 168rpx;
		height: 68rpx;
		line-height: 68rpx;
		border-radius: 6rpx;
		background-color: rgba(255, 255, 255, 1);
		color: rgba(102, 102, 102, 1);
		font-size: 26rpx;
		text-align: center;
		box-shadow: 0px 2px 12rpx 0px rgba(0, 0, 0, 0.2);
	}

	.emotion-icon {
		font-size: 22px;
		margin: 0 2px;
		vertical-align: middle;
		color: #333;
	}
</style>