<template>
	<view>
		<view class="cu-item">
			<view class="cu-list menu-avatar comment">
				<text class="copy-comment" v-if="item.text!='[图片]'" @tap="ToCopy(item.text)">
					复制
				</text>
				<view class="cu-item">
					<view class="cu-avatar round user-avatar-container" @tap="toUserContents(item.userJson)" :style="item.style">
						<!-- 小祈愿头像框 -->
						<image v-if="frameUrls[item.userJson.uid]" class="avatar-frame" :src="frameUrls[item.userJson.uid]" mode="aspectFit"></image>
						<!-- 小祈愿头像框 -->
					</view>
					<view class="content">
						<view class="text-grey">
						<block v-if="item.userJson.isvip>0">
							<block v-if="item.userJson.vip==1">
								<text class="text-red">
									{{item.userJson.name}}
								</text>
							</block>
							<block v-else>
								<text class="text-yellow">
									{{item.userJson.name}}
								</text>
							</block>
						</block>
						<block v-else>
							{{item.userJson.name}}
						</block>
						<block v-if="isHead">
							<image v-if="item.userJson.isvip>0" :src="vipImg" style="border-radius: 0px;margin-left: 6upx;margin-right: 0upx;width: 70upx;height: 35upx;" mode="widthFix"></image>
							<image :src="lvImg+getLv(item.userJson.experience)+'.png'" style="border-radius: 0px;margin-left: 6upx;margin-right: 0upx;width: 44upx;height: 22upx;" mode="widthFix"></image>
							<text class="userlv customize"
								style="border: 3upx solid black;color:black;padding: 2upx 10upx;border-radius: 40upx;background-color: transparent;"
								v-if="item.userJson.customize&&item.userJson.customize!=''">{{item.userJson.customize}}</text>
							<medal-item :uid="item.userJson.uid"/>  <!--小祈愿勋章组件引入 -->
						</block>
						</view>
						
						<view class="text-content text-df break-all">
							<rich-text v-if="item.text!='[图片]'" :nodes="markHtml(item.text)"></rich-text>
							<view class="pic-box" v-if="itemPicArray.length">
								<template>
									<view v-if="itemPicArray.length === 1" class="single-pic">
										<u-image :src="itemPicArray[0]"
											@tap="previewImage(itemPicArray,itemPicArray[0])" width="400rpx"
											height="300rpx" :fade="true" duration="450" :lazy-load="true"
											border-radius="20">
											<u-loading slot="loading"></u-loading>
										</u-image>
									</view>
									<view v-else class="son-grid-pic"
										:style="{ gridTemplateColumns: 'repeat(3, 1fr)' }">
										<u-image v-for="(pic, index) in itemPicArray.slice(0, 9)" :key="index"
											:src="pic" @tap="previewImage(itemPicArray,itemPicArray[index])"
											width="170rpx" height="170rpx" :fade="true" duration="450" :lazy-load="true"
											border-radius="20">
											<u-loading slot="loading"></u-loading>
										</u-image>
									</view>
								</template>
							</view>
						</view>
						<view class="bg-cyan light padding-sm radius margin-top-sm  text-sm"
							style="border-radius: 20upx;" v-if="item.parent>0&&isContent">
							<view class="flex">
								<view class="flex-sub break-all">
									<view class="tn-flex">{{item.parentJson.username}}：<rich-text
											v-if="item.parentJson.text!='[图片]'"
											:nodes="markHtml(item.parentJson.text)"></rich-text></view>
									<view class="son-pic-box" v-if="parentPicArray.length">
										<view v-if="parentPicArray.length === 1" class="single-pic">
											<u-image :src="parentPicArray[0]"
												@tap="previewImage(parentPicArray,parentPicArray[0])" width="300rpx"
												height="200rpx" :fade="true" duration="450" :lazy-load="true"
												border-radius="20">
												<u-loading slot="loading"></u-loading>
											</u-image>
										</view>
						
										<view v-else class="son-grid-pic"
											:style="{ gridTemplateColumns: 'repeat(3, 1fr)' }">
											<u-image v-for="(pic, index) in parentPicArray.slice(0, 9)" :key="index"
												:src="pic" @tap="previewImage(parentPicArray,parentPicArray[index])"
												width="130rpx" height="130rpx" :fade="true" duration="450"
												:lazy-load="true" border-radius="17">
												<u-loading slot="loading"></u-loading>
											</u-image>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="bg-cyan light padding-sm radius margin-top-sm  text-sm"
							style="border-radius: 20upx;" v-if="!isContent">
							<view class="flex" @tap="toInfo(item.cid,item.contenTitle)">
								<view class="break-all">{{replaceSpecialChar(item.contenTitle)}}</view>
						
							</view>
						</view>
						<view class="margin-top-sm flex justify-between">
							<view class="text-gray text-df" style="font-size: 26upx;">{{formatDate(item.created)}}
							 <text class="margin-left-sm" v-if="$API.localOf()">{{getLocal(item.userJson.local)}}</text>
							</view>
							<view>
								<text class="tn-icon-praise" :class="item.isLikes==1?'text-cyan':''"  @tap="toLike(item.id),item.isLikes=1">
									<block v-if="item.likes>0">
										{{formatNumber(item.likes)}}
									</block>
								</text>
								<text class="tn-icon-comment margin-left-sm" @tap="handleTap(item.userJson.name,item.id)"></text>
							</view>
						</view>
						<view class="comment-operation"  v-if="group=='administrator'||group=='editor'">
							<text class="text-black" @tap="toBan(item.userJson.uid)">封禁</text>
							<text class="text-red" @tap="toDelete(item.id)">删除</text>
						</view>
					</view>
				</view>
				<u-divider :use-slot="false" half-width="40%"></u-divider>
							
				
			</view>
		</view>
	</view>
</template>

<script>
	import { localStorage } from '../../js_sdk/mp-storage/mp-storage/index.js'
	// #ifdef APP-PLUS
	import owo from '../../static/app-plus/owo/OwO.js'
	// #endif
	// #ifdef H5
	import owo from '../../static/h5/owo/OwO.js'
	// #endif
	// #ifdef MP
	var owo = [];
	// #endif
	import MedalItem from '@/pages/components/medalItem.vue'
	export default {
		components: {
			MedalItem
		},
	    props: {
	        item: {
			  type: Object,
			  default: () => ({})
			},
			isHead: {
			  type: Boolean,
			  default: true
			},
			isContent: {
			  type: Boolean,
			  default: false
			}
	    },
		name: "commentItem",
		data() {
			return {
				owo:owo,
				vipImg: this.$API.SPvip(),
				lvImg: this.$API.SPLv(),
				
				owoList:[],
				group:"",
				frameUrls: {}, // 存储用户ID和对应的头像框URL
				fanstey_avatarframe: false
			};
		},
		computed: {
			itemPicArray() {
				return this.item.pic ? this.item.pic.split('||') : [];
			},
			parentPicArray() {
				return this.item.parentJson.pic ? this.item.parentJson.pic.split('||') : [];
			}
		},
		created(){
			var that = this;
			if(localStorage.getItem('userinfo')){
							
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.group = userInfo.group;
			}
			// #ifdef APP-PLUS || H5
			var owo = that.owo.data;
			var owoList=[];
			for(var i in owo){
				owoList = owoList.concat(owo[i].container);
			}
			that.owoList = owoList;
			// #endif
			
			// 检查头像框插件是否启用
			this.checkAvatarFramePlugin();
		},
		methods: {
			handleTap(author,coid) {
				this.$emit(
					'coAdd',
					'hf',
					author,
					coid,
				);
				
			},
			previewImage(imageList, image) {
				console.log(imageList);
				//预览图片
				uni.previewImage({
					urls: imageList,
					current: image
				});
			},
			subText(text,num){
				if(text.length < null){
					return text.substring(0,num)+"……"
				}else{
					return text;
				}
				
			},
			replaceSpecialChar(text) {
			  text = text.replace(/&quot;/g, '"');
			  text = text.replace(/&amp;/g, '&');
			  text = text.replace(/&lt;/g, '<');
			  text = text.replace(/&gt;/g, '>');
			  text = text.replace(/&nbsp;/g, ' ');
			  return text;
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				return result;
			},
			formatNumber(num) {
			    return num >= 1e3 && num < 1e4 ? (num / 1e3).toFixed(1) + 'k' : num >= 1e4 ? (num / 1e4).toFixed(1) + 'w' : num
			},
			goInfo(id){
				var that = this;
				uni.navigateTo({
					url: '/pages/forum/info?id='+id
				});
			},
			goAds(data){
				var that = this;
				var url = data.url;
				var type = data.urltype;
				// #ifdef APP-PLUS
				if(type==1){
					plus.runtime.openURL(url);
				}
				if(type==0){
					plus.runtime.openWeb(url);
				}
				// #endif
				// #ifdef H5
				window.open(url)
				// #endif
			},
			toUserContents(data){
				var that = this;
				var name = data.name;
				var title = data.name+"的信息";
				var id= data.uid;
				var type="user";
				uni.navigateTo({
				    url: '/pages/contents/userinfo?title='+title+"&name="+name+"&uid="+id+"&avatar="+encodeURIComponent(data.avatar)
				});
			},
			getUserLv(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var rankList = that.$API.GetRankList();
				return rankList[i];
			},
			
			getUserLvStyle(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var rankStyle = that.$API.GetRankStyle();
				var userlvStyle ="color:#fff;background-color: "+rankStyle[i];
				return userlvStyle;
			},
			getLv(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var lv  = that.$API.getLever(i);
				return lv;
			},
			getLvStyle(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var lv  = that.$API.getLever(i);
				var rankStyle = that.$API.GetRankStyle();
				var userlvStyle ="color:#fff;background-color: "+rankStyle[lv];
				return userlvStyle;
			},
			getLocal(local) {
				var that = this;
				if (local && local != '') {
					var local_arr = local.split("|");
					if (!local_arr[3] || local_arr[3] == 0) {
						return local_arr[2];
					} else {
						return local_arr[3];
					}
			
				} else {
					return "未知"
				}
			
			},
			commentsAdd(title,coid,reply,postid){
				var that = this;
				uni.navigateTo({
				    url: '/pages/forum/reply?postid='+postid+"&coid="+coid+"&title="+title+"&isreply="+reply
				});
			},
			markHtml(text){
				var that = this;
				text = that.replaceAll(text,"<","&lt;");
				text = that.replaceAll(text,">","&gt;");
				var owoList=that.owoList;
				// console.log(JSON.stringify(owoList));
				for(var i in owoList){
				
					if(that.replaceSpecialChar(text).indexOf(owoList[i].data) != -1){
						text = that.replaceAll(that.replaceSpecialChar(text),owoList[i].data,"<img src='/"+owoList[i].icon+"' class='tImg' />")
						
					}
				}
				return text;
			},
			replaceAll(string, search, replace) {
			  return string.split(search).join(replace);
			},
			toBan(uid){
				if(!uid){
					uni.showToast({
						title: "该用户不存在",
						icon: 'none'
					})
					return false;
				}
				uni.navigateTo({
					url: '/pages/manage/banuser?uid='+uid
				});
			},
			toDelete(id){
				var that = this;
				var token = "";
				
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				var data = {
					"id":id,
					"token":token
				}
				uni.showModal({
					title: '确定要删除该评论吗',
					success: function (res) {
						if (res.confirm) {
							uni.showLoading({
								title: "加载中"
							});
							
							that.$Net.request({
								url: that.$API.postCommentDelete(),
								data:data,
								header:{
									'Content-Type':'application/x-www-form-urlencoded'
								},
								method: "get",
								dataType: 'json',
								success: function(res) {
									setTimeout(function () {
										uni.hideLoading();
									}, 1000);
									uni.showToast({
										title: res.data.msg,
										icon: 'none'
									})
									that.$emit(
										'coDel'
									);
									
								},
								fail: function(res) {
									setTimeout(function () {
										uni.hideLoading();
									}, 1000);
									uni.showToast({
										title: "网络开小差了哦",
										icon: 'none'
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			ToCopy(text) {
				var that = this;
				// #ifdef APP-PLUS
				uni.setClipboardData({
					data: text,
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: "复制成功"
						})
					}
				});
				// #endif
				// #ifdef H5 
				let textarea = document.createElement("textarea");
				textarea.value = text;
				textarea.readOnly = "readOnly";
				document.body.appendChild(textarea);
				textarea.select();
				textarea.setSelectionRange(0, text.length);
				uni.showToast({ //提示
					title: "复制成功"
				})
				var result = document.execCommand("copy")
				textarea.remove();
			
				// #endif
			},
			toLike(id){
				var that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: "请先登录",
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				if(that.item.isLikes==1){
					uni.showToast({
						title: "你已经点赞过了",
						icon: 'none'
					});
					return false;
				}else{
					that.item.isLikes = 1;
				}
				
				
				var data = {
					token:token,
					id:id,
				}
				uni.showLoading({
					title: "加载中"
				});
				that.$Net.request({
					
					url: that.$API.postCommentLike(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						//console.log(JSON.stringify(res))
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if(res.data.code==0){
							that.item.isLikes = 0;
						}else{
							that.item.likes += 1;
						}
						
					},
					fail: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
						
					}
				})
			},
			// 检查头像框插件是否启用
			checkAvatarFramePlugin() {
				try {
					const cachedPlugins = uni.getStorageSync('getPlugins');
					if (cachedPlugins) {
						const pluginList = JSON.parse(cachedPlugins);
						this.fanstey_avatarframe = pluginList.includes('xqy_avatar_frame');
						if (this.fanstey_avatarframe && this.item && this.item.userJson && this.item.userJson.uid) {
							this.loadUserFrame(this.item.userJson.uid);
						}
					}
				} catch (error) {
					console.error('检查插件状态失败:', error);
				}
			},
			
			// 加载用户头像框
			loadUserFrame(uid) {
				if (!uid || !this.fanstey_avatarframe) return;
				
				const that = this;
				that.$Net.request({
					url: that.$API.PluginLoad('xqy_avatar_frame'),
					data: {
						"action": "get_user_frames",
						"op": "list",
						"type": "view",
						"uid": uid
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						if (res.data && res.data.code === 200 && res.data.data && res.data.data.awarded && res.data.data.awarded.length > 0) {
							const wearingFrame = res.data.data.awarded.find(frame => frame.is_wearing);
							if (wearingFrame) {
								// 使用Vue的响应式更新
								that.$set(that.frameUrls, uid, wearingFrame.frame_url);
							}
						}
					}
				});
			},
		}
	}
</script>

<style scoped>
	.single-pic u-image {
		width: 100%;
		height: auto;
	}

	.double-pic {
		display: flex;
		gap: 10rpx;
		justify-content: space-around;
	}

	.son-grid-pic {
		display: flex;
		gap: 10rpx;
		justify-items: center;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.grid-pic {
		display: grid;
		gap: 10rpx;
	}

	.pic-box {
		margin: 20rpx 0;
	}

	.son-pic-box {
		margin: 15rpx 0;
	}

	.bg-cyan.light {
		color: #767676;
		background-color: #eeeeee;
		border-left: 10rpx solid #d5d5d5;
	}
/* 小祈愿勋章样式 */	
	.text-grey {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 6rpx;
	}

	.medal-display {
		display: inline-flex;
		margin-left: 8rpx;
	}

	/* 头像框样式 */
	.user-avatar-container {
		position: relative;
		overflow: visible !important;
	}
	
	.avatar-frame {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 90;
		transform: scale(1.05);
		transform-origin: center center;
	}
</style>