<template>
	<view class="page">
		<!-- 引入FontAwesome -->
		<view>
			<link rel="stylesheet"
				href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		</view>



		<!-- 顶部导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left" @click="goBack">
				<text class="fa fa-angle-left"></text>
			</view>
			<view class="navbar-center">
				<view class="navbar-title">
					<image class="navbar-avatar" :src="author.avator" mode="aspectFill"></image>
					<text class="navbar-text">{{ author.nickname }}</text>
					<!-- <text class="navbar-badge" v-if="author.is_vip > 0">VIP</text> -->
				</view>
			</view>
			<view class="navbar-right">
				<text class="followTheAuthor followTheAuthor1" v-if="author.is_attention == 0"
					@click="followTheAuthor(1)">+关注</text>
				<text class="followTheAuthor followTheAuthor0" v-if="author.is_attention == 1"
					@click="followTheAuthor(0)">已关注</text>
				<image @click="showActionSheet" src="../../static/icon/sy_icon_fenxiang.png" mode="widthFix"></image>
			</view>
		</view>


		<!-- 灵感 -->
		<template v-if="articleInfo.task_type == 1">
			<view class="inspiration-content" v-if="home_image">
				<image v-if="home_image" src="../../static/makedetail/cz_img_zhanshi.png" mode="widthFix"></image>
				<image :src="home_image" class="inspirationPictures" mode="widthFix"></image>
			</view>

		</template>
		<!-- 音乐 -->
		<template v-else-if="articleInfo.task_type == 2">
			<view class="musicContentBox">
				<view class="headCard">
					<image :src="home_image" class="songCover"></image>
					<view class="songInfo">
						<view class="songTitle">{{ addBrackets(articleInfo.title) }}</view>
						<view class="songTag">
							<view class="tag" v-for="(item, index) in commaToArray(articleInfo.style)"
								:key="index + item">{{ item }}</view>
						</view>
					</view>
					<template v-if="articleInfo.task_type == 2">

						<image @click="toggleAudio" v-if="isPlaying" src="@/static/makedetail/cz_icon_zanting.png"
							class="playerButton"></image>
						<image @click="toggleAudio" v-else src="@/static/makedetail/cz_icon_bofang.png"
							class="playerButton"></image>
					</template>
				</view>
				<view class="contentHeader">
					<view class="musicContent">
						<text> {{ articleInfo.lyrics }}</text>
						<image class="roll" src="@/static/icon/roll.png"></image>
					</view>
					<view class="maskLayer"></view>
				</view>

			</view>

		</template>

		<!-- 作品描述 -->
		<view class="workDescription">
			<view class="workDescription-title">
				<view>创作说明 </view>
				<!-- <image class="pen" src="@/static/icon/wd_icon_bianji.png"></image> -->
			</view>
			<view class="workDescription-content">
				{{ content || '暂无内容' }}
			</view>
		</view>

		<view class="goCreate" @click="goCreate()">去创作</view>
		<DialogBox ref="customConfirm"></DialogBox>










		<!-- 文章头图区域 -->
		<view class="topUser" v-if="false">
			<image :src="home_image" class="home_image" mode="aspectFill"></image>
			<!-- 图片指示器 -->
			<view class="image-indicator" v-if="image_list.length > 1">
				<text>{{ selImg + 1 }}/{{ image_list.length }}</text>
			</view>
			<!-- 音乐类型时显示歌词 -->
			<view class="lyrics-overlay" v-if="articleInfo.task_type == 2">
				<text class="lyrics-text">{{ articleInfo.lyrics }}</text>
			</view>
			<!-- 音乐类型时显示播放按钮 -->
			<view class="play-button" v-if="articleInfo.task_type == 2 && articleInfo.result_audio"
				@click="toggleAudio">
				<text class="fa" :class="isPlaying ? 'fa-pause' : 'fa-play'"></text>
			</view>
			<!-- 缩略图列表 -->
			<view class="list">
				<view class="img" :class="selImg == index ? 'active' : ''" v-for="(item, index) in image_list"
					:key="index" @click="selPhoto(item, index)">
					<image :src="item" mode="aspectFill"></image>
				</view>
			</view>
		</view>

		<!-- 音频元素 -->
		<audio id="audioPlayer" :src="articleInfo.result_audio" style="display:none;" v-if="false"></audio>

		<!-- 文章内容区域 -->
		<view class="body" v-if="false">
			<!-- 文章标题与元信息 -->
			<view class="article-header">
				<view class="title">
					{{ articleInfo.title || '暂无标题' }}
				</view>
				<view class="meta-info">
					<view class="meta-item">
						<text class="fa fa-calendar"></text>
						<text class="meta-text">{{ articleInfo.create_time || '暂无时间' }}</text>
					</view>
					<view class="meta-item">
						<text class="fa fa-eye"></text>
						<text class="meta-text">{{ articleInfo.num_view || 0 }}次阅读</text>
					</view>
					<view class="meta-item" v-if="articleInfo.author">
						<text class="fa fa-user"></text>
						<text class="meta-text">{{ articleInfo.author }}</text>
					</view>
				</view>
			</view>

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

			<!-- 文章内容 -->
			<!-- <view class="article-content" v-if="articleInfo.type == 'user'">
				<view class="content">{{ articleInfo.content || '暂无内容' }}</view>
			</view> -->
			<view class="article-content">
				<view class="content">
					<rich-text :nodes="content" style="font-size: 14px;"></rich-text>
				</view>
			</view>

			<!-- 文章底部区域 -->
			<view class="article-footer">
				<view class="action-bar">
					<view class="action-item" @tap="likeArticle">
						<text class="fa" :class="articleInfo.is_like ? 'fa-thumbs-up liked' : 'fa-thumbs-o-up'"></text>
						<text class="action-text">{{ articleInfo.like_count || 0 }}</text>
					</view>
					<view class="action-item" @tap="openComment">
						<text class="fa fa-comment-o"></text>
						<text class="action-text">{{ tableTotal || 0 }}</text>
					</view>
					<view class="action-item" @tap="shareArticle">
						<text class="fa fa-share-alt"></text>
						<text class="action-text">分享</text>
					</view>
				</view>
			</view>

			<!-- 空白占位 -->
			<view class="list_info">
				<view class="blankHeight"></view>
			</view>

		</view>

		<!-- <view class="btn_submit" @click="chatTA()">
			<image class="icon" src="../../static/icon/icon_chat_white.png" mode="widthFix"></image>
			私聊
		</view> -->
		<view class="thread2"></view>
		<view class="thread2"></view>

		<previewImage ref="previewImage" :opacity="0.8" :circular="true" :imgs="imgs" :descs="descs"></previewImage>

		<!-- 评论区域 -->
		<CommentSection ref="commentSection" :myInfo="myInfo" :userInfo="userInfo" :articleId="arcID"
			@totalNumberOfComments="totalNumberOfComments"></CommentSection>

		<!-- 自定义 ActionSheet -->
		<ActionSheet ref="actionSheet" :items="[
			{ text: '分享作品', icon: '../../static/icon/cz_icon_fenxiangzuopin.png' },

		]" @select="handleActionSelect" @cancel="handleActionCancel" />
		<view class="thread2"></view>

	</view>
</template>

<script>
import htmlParser from '../../common/html-parser'
import previewImage from '@/components/kxj-previewImage/kxj-previewImage.vue'; //引用插件
import CommentSection from '@/components/CommentSection/CommentSection.vue';
import ActionSheet from '@/components/ActionSheet/ActionSheet.vue';
function parseImgs(nodes) {
	nodes.forEach(node => {
		if (
			node.name === 'img' &&
			node.attrs &&
			node.attrs['data-img-size-val']
		) {
			const sizes = node.attrs['data-img-size-val'].split(',')
			const width = uni.upx2px(720 * 0.9)
			const height = parseInt(width * (sizes[1] / sizes[0]))
			node.attrs.style = `width:${width};height:${height};`
		}
		if (Array.isArray(node.children)) {
			parseImgs(node.children)
		}
	})
	return nodes
}
export default {
	components: {
		previewImage,
		CommentSection,
		ActionSheet
	},
	data() {
		return {
			title: '',
			arcID: 0,
			selImg: 0,
			home_image: '',
			articleInfo: {},
			tag_list: [],
			image_list: [],
			imgs: [],
			descs: [],
			list_wish: [],
			content: '',
			author: {},
			// 添加文章信息字段
			articleInfo: {
				title: '',
				content: '',
				create_time: '',
				images: '',
				view_count: 0,
				author: '',
				like_count: 0,
				is_like: false
			},

			myInfo: {
				user_id: 1, // 用户id
				user_name: "cc", // 用户名
				user_avatar: "https://img0.baidu.com/it/u=2836960144,3650263035&fm=253&fmt=auto&app=138&f=JPEG?w=474&h=474", // 用户头像地址
			},
			// 文章作者信息(提示: 一般来自localstorage, 如果是实时获取的话, 那么获取到数据后再v-if显示评论组件)
			userInfo: {
				user_id: 2, // 用户id
				user_name: "ikun", // 用户名
				user_avatar: "https://pic1.zhimg.com/80/v2-a79071a705f55c5d88f6c74e6111fe84_720w.webp", // 用户头像地址
			},
			deleteMode: "all", //删除模式
			// 评论总数
			tableTotal: 4,
			// 评论表
			tableData: [],
			isPlaying: false, // 添加播放状态
			audioPlayer: null, // 添加音频播放器实例
		}
	},
	onLoad(parms) {
		let self = this;
		this.arcID = parms.id || 393;
	},
	onShow() {
		uni.$emit('check_update');
		this.loadData();
		this.$nextTick(() => {
			if (this.$refs.commentSection) {
				this.$refs.commentSection.loadCommentData();
			}
		});
	},
	onReady() {
		// 初始化音频播放器
		this.audioPlayer = uni.createInnerAudioContext();
		this.audioPlayer.onEnded(() => {
			this.isPlaying = false;
		});
	},
	onUnload() {
		// 页面卸载时停止音频播放
		if (this.audioPlayer) {
			this.audioPlayer.stop();
			this.audioPlayer.destroy();
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		totalNumberOfComments(tableTotal) {
			this.tableTotal = tableTotal;
		},
		onLinqu(item) {
			uni.navigateTo({
				url: '/pages/my/wishHelp?id=' + item.myid,
			})
		},
		selPhoto(item, sel) {
			this.selImg = sel;
			this.home_image = this.image_list[sel];
		},
		toArr(imgs) {
			let arr = imgs.split("|");
			return arr;
		},
		previewOpen(imgs1, index) {
			this.imgs = imgs1.split("|");
			setTimeout(() => this.$refs.previewImage.open(index), 0)
			// 传入当前选中的图片地址或序号
			return; //如需测试和uni原生预览差别可注释这两行
		},
		loadData() {
			uni.request({
				url: this.$apiHost + '/Work/getinfo',
				data: {
					uuid: getApp().globalData.uuid,
					id: this.arcID
				},
				header: {
					"content-type": "application/json",
					'sign': getApp().globalData.headerSign
				},
				success: (res) => {
					console.log("文章信息:", res.data);
					if (res.data.success === "yes") {
						console.log("文章信息:", res.data.data);

						// 更新文章信息
						this.articleInfo = res.data.data;
						this.content = res.data.data.content;
						this.home_image = res.data.data.images;
						this.author = res.data.author;
					} else {
						uni.showToast({
							title: '获取信息失败',
							icon: 'none'
						});
					}
				},
				complete: (com) => {
					// uni.hideLoading();
				},
				fail: (e) => {
					console.log("请求失败:", e);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		// 唤起新评论弹框
		openComment() {
			if (this.$refs.commentSection) {
				this.$refs.commentSection.openComment();
			}
		},
		// 文章点赞
		likeArticle() {
			uni.request({
				url: this.$apiHost + '/Work/zanTA',
				data: {
					uuid: getApp().globalData.uuid,
					id: this.arcID
				},
				header: {
					"content-type": "application/json",
					'sign': getApp().globalData.headerSign
				},
				success: (res) => {
					console.log("点赞结果:", res.data);
					if (res.data.success === "yes") {
						// 更新点赞状态
						if (!this.articleInfo.is_like) {
							this.articleInfo.like_count = (this.articleInfo.like_count || 0) + 1;
							this.articleInfo.is_like = true;
							uni.showToast({
								title: '点赞成功',
								icon: 'none'
							});
						} else {
							this.articleInfo.like_count = (this.articleInfo.like_count || 0) - 1;
							this.articleInfo.is_like = false;
							uni.showToast({
								title: res.data.str,
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: res.data.str,
							icon: 'none'
						});
					}
				},
				fail: (e) => {
					console.log("点赞失败:", e);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		// 关注作者
		followTheAuthor(n) {
			uni.request({
				url: this.$apiHost + '/Member/attention',
				data: {
					uuid: getApp().globalData.uuid,
					id: this.author.id
				},
				header: {
					"content-type": "application/json",
					'sign': getApp().globalData.headerSign
				},
				success: (res) => {
					console.log("点赞结果:", res.data);
					uni.showToast({
						title: res.data.str,
						icon: 'none'
					});
					if (res.data.success === "yes") {
						console.log("关注结果:", res.data, n);

						this.author.is_attention = n
					}
				},
				fail: (e) => {
					console.log("关注失败:", e);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		// 分享文章
		shareArticle() {
			// 如果在微信小程序环境
			if (uni.getSystemInfoSync().platform === 'mp-weixin') {
				uni.showShareMenu({
					withShareTicket: true,
					menus: ['shareAppMessage', 'shareTimeline']
				});
			} else {
				// 其他环境，如APP
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0,
					title: this.articleInfo.title,
					summary: this.articleInfo.content.substring(0, 40) + "...",
					imageUrl: this.home_image,
					success: function (res) {
						console.log("分享成功：" + JSON.stringify(res));
					},
					fail: function (err) {
						console.log("分享失败：" + JSON.stringify(err));
					}
				});
			}
		},
		// 切换音频播放状态
		toggleAudio() {
			if (!this.articleInfo.result_audio) return;

			if (this.isPlaying) {
				this.audioPlayer.pause();
				this.isPlaying = false;
			} else {
				this.audioPlayer.src = this.articleInfo.result_audio;
				this.audioPlayer.play();
				this.isPlaying = true;
			}
		},
		// 新增过滤器方法
		commaToArray(str) {
			if (!str) return '';
			return str.split(',');
		},

		// 新增过滤器方法
		addBrackets(str) {
			if (!str) return '';
			if (!str.startsWith('《')) {
				str = '《' + str;
			}
			if (!str.endsWith('》')) {
				str = str + '》';
			}
			return str;
		},
		getInfoData() {
			uni.request({
				url: this.$apiHost + '/Member/getinfoData',
				data: {
					uuid: getApp().globalData.uuid
				},
				header: {
					'content-type': 'application/json'
				},
				success: (res) => {
					console.log('用户信息', res.data);

				}
			});
		},
		showActionSheet() {
			this.$refs.actionSheet.show();
		},
		handleActionCancel() {
			console.log('ActionSheet cancelled');
		},
		
		goCreate() {
			uni.switchTab({
				url: '/pages/make/index'
			});
		},
	}
}
</script>

<style scoped lang="scss">
@import 'workDetail.scss';
</style>