<style lang="scss">
.hqs-popup {
	z-index: 999999;
	
	.hidden { visibility: hidden; }
	.qs-side {
		min-width: 60px;
		padding: 15px 20px 10rpx;
		color: #888;
		flex-shrink: 0;
		&:active { opacity: .8; }
	}
}
@import 'player.scss';
</style>

<template>
<uni-popup ref="popup" 
	:mask-click="maskClick" @change="onChange"
	:type="from" class="hqs-popup">
	<view class="qs-con" 
		:style="conStyle" 
		@mousedown="onTouch" @mousemove="onTouch" @mouseup="onTouch"
		@touchstart="onTouch" @touchmove="onTouch" @touchend="onTouch">
		<view class="topBody">
			
		</view>
			<view class="play_header">
				<view class="bar">
					<view class="left" @click="close();">
						<image class="backup" mode="widthFix" src="../../static/icon/play_music_close_img.png"></image>
					</view>
					<view class="downline">
						当前播放
					</view>
					<view class="right" @click="collectionIt('story',storyInfo.id)"><!-- @click="share_this = true"-->
						<!-- <image class="backup" mode="widthFix" src="../../static/icon/ic_share_black.png" style="opacity: 0;"></image> -->
						<image class="backup" mode="widthFix" src="../../static/icon/ic_coll_no.png" v-if="!collection_story"></image>
						<image class="backup" mode="widthFix" src="../../static/icon/ic_coll_yes.png" v-else></image>
					</view>
				</view>
			</view>
			<view class="yuanjiao">
				
			</view>
			<view class="contBody">
				<view class="img">
					<image class="iconStop" mode="widthFix" :src="storyInfo.image" v-if="!isPlayingState"></image>
					<image class="iconPlay" mode="widthFix" :src="storyInfo.image" v-else></image>
				</view>
				<view class="title">
					{{storyInfo.title}}
				</view>
			</view>
			<view class="playSlider">
				<slider :value="playSliderNum" @change="sliderChange" @changing="sliderChanging" activeColor="#ff6b4d" backgroundColor="#cbcbcb80" block-color="#ff4845" block-size="12" />
			</view>
			<view class="playSlider2">
				<view class="left">{{convertSecondsToMinutesSeconds(currentTime)}}</view>
				<view class="right">{{convertSecondsToMinutesSeconds(durationTime)}}</view>
			</view>
			<view class="control">
				<view class="loop" @click="SetLoopType()">
					<image class="icon" mode="widthFix" src="../../static/icon/ic_list.png"></image>
					<text class="num" v-if="isLoopOne">1</text>
				</view>
				<view class="last" @click="playLastNext('last')">
					<image class="icon" mode="widthFix" src="../../static/icon/ic_play_music_last_on.png"></image>
				</view>
				<view class="play" @click="playOrPause">
					<image class="iconP" mode="widthFix" src="../../static/icon/ic_play_music_play.png" v-if="!isPlayingState"></image>
					<image class="iconP" mode="widthFix" src="../../static/icon/ic_play_music_pause.png" v-else></image>
				</view>
				<view class="next" @click="playLastNext('next')">
					<image class="icon" mode="widthFix" src="../../static/icon/ic_play_music_next_on.png"></image>
				</view>
				<view class="plist" @click="showStoryList = true;">
					<image class="icon" mode="widthFix" src="../../static/icon/ic_play_music_list_on.png"></image>
				</view>
			</view>
			
			<view class="blankHei"></view>
			
			<view class="bgAlpha" v-if="shopPlayTime" @click="shopPlayTime = false"></view>
			<view class="pop_time" v-if="shopPlayTime">
				<view class="close" @click="shopPlayTime = false"><image class="icon" mode="widthFix" src="../../static/icon/ic_close.png"></image></view>
				<view class="title">按时长</view>
				<view class="list">
					<view class="item" v-for="(item,index2) in time1_list" :key="index2" @click="selTimer(1,index2)" :class="time_sel1==index2?'active':''">
						<text>{{item.name}}</text>
					</view>
				</view>
				<view class="title">按集数</view>
				<view class="list">
					<view class="item" v-for="(item,index2) in 10" :key="index2" @click="selTimer(2,index2)" :class="time_sel2==index2?'active':''">
						<text>{{index2+1}}集</text>
					</view>
				</view>
			</view>
			
			<view class="pop_story_list" v-if="showStoryList">
				<view class="content">
					<image class="close" mode="widthFix" src="../../static/icon/ic_close.png" @click="showStoryList = false;"></image>
					<view class="title">播放列表</view>
					
					<view class="story_list2">
						<scroll-view style="width: 100%; height: 43vh;" :scroll-y="true">
						<!-- #ifdef APP-NVUE -->
						<list>
							<cell>
						<!-- #endif -->
						<view class="item" @click="playIt2(item)" v-for="(item,index2) in StoryList" :key="index2"  style="overflowY:auto;">
							<view class="imgR">
								<image class="icon" mode="widthFix" :src="item.image"></image>
								<view class="play" v-if="false"><image class="img" mode="widthFix" src="../../static/icon/story_detail_video_stop.png"></image></view>
							</view>
							<view class="right">
								<view class="title1">{{item.title}}</view>
								<view class="desc">{{item.introduction}}</view>
								<view class="stat">
									<view class="stat1"><image class="img1" mode="widthFix" src="../../static/icon/ic_view.png"></image> {{item.view_num}}</view>
									<!-- <view class="line"></view> -->
									<view class="stat1"><image class="img1" mode="widthFix" src="../../static/icon/ic_time.png"></image> {{item.duration}}</view>
								</view>
							</view>
							<view class="replay" v-if="item.istry > 0 && false">
								试听
							</view>
						</view>
						<!-- #ifdef APP-NVUE -->
						</cell>
						</list>
						<!-- #endif -->
						</scroll-view>
					</view>
				</view>
			</view>
			
			<slot name="sub-header"></slot>
			<scroll-view
				@scroll="onScroll">
				<view>
					<slot></slot>
				</view>
			</scroll-view>
			<slot name="bottom"></slot>
		
		
	</view>
</uni-popup>
</template>

<script>
import UniPopup from './uni-popup.vue'
	import pubc from '@/common/public.js'

export default {
	components: {
		UniPopup,
	},
	props: {
		// 弹窗显示可通过v-model控制
		value: Boolean,

		// 弹窗打开开始方向
		from: {
			type: String,
			default: 'bottom',
		},
		// storyInfo: {
		// 	type: Object,
		// 	default () {
		// 		return {}
		// 	}
		// },
		
		// 内容区边缘圆角大小
		round: {
			type: Number,
			default: 10,
		},
		// 弹窗内容宽度(当from=left或right时起作用)
		width: {
			type: String,
			default: '60vw',
		},
		// 弹窗内容高度(当from=top或bottom时起作用)
		height: {
			type: String,
			default: '100vh',
		},
		
		// 显示默认头部标题栏（仅在底部弹出时有）
		showHeader: {
			type: Boolean,
			default: true,
		},
		// 弹窗标题
		title: String,

		// 显示左侧（返回）按钮，如果v-slot:back存在时，也会显示此按钮
		showBack: Boolean,

		// 显示关闭按钮，如果是字符串，将作为uview（需另外引入）的u-icon组件的name（如showClose="close"，会显示close图标）
		showClose: {
			type: [Boolean, String],
			default: true,
		},

		// 是否可点击模态背景关闭弹窗
		maskClick: {
			type: Boolean,
			default: true,
		},
	},
	data() {
		return {
			scrollTop: 0,
			panStyle: '',
			showPopup: false,
				cate_id:0,
				StoryCate:{},
				StoryList:[],
				collection_theme:'false',
				collection_story:'false',
				story: {
					title:'----------------------',
					id:0
				},
				storyInfo:{},
				current:0,
				offsetY: 0,
				share_this:false,
				scrollEnabled: true, // 控制item的滚动
				showPlay:false,
				shopPlayTime:false,
				showStoryList:false,
				time_sel1:0,
				time_sel2:-1,
				overflowh:'auto',
				currentTime: 0, // 用于存储当前播放进度
				durationTime:0,
				playSliderNum:0,
				time1_list:[
					{name:'不限时',time:0},
					{name:'10分钟',time:10},
					{name:'20分钟',time:20},
					{name:'30分钟',time:30},
					{name:'40分钟',time:40},
					{name:'50分钟',time:50},
					{name:'60分钟',time:60}
				],
				isPlayingState:false,
				isChangeSlider:false,
				isLoopOne:false,
		}
	},
	computed: {
		closeIcon() {
			if(typeof this.showClose == 'string') return this.showClose
			return false
		},
		isVertical() {
			return ['bottom', 'top'].includes(this.from)
		},
		conStyle() {
			return ""
		},
	},
	onLoad() {
	},
	watch: {
		value(val) {
			console.log("watch",val);
			if(val == this.showPopup) return
			if(val) this.open()
			else this.close()
		},
		showPopup(val) {
			// this.$emit('input', val)
		},
	},
	created() {
		uni.$on('info', (data)=>{
			console.log("on-info",data);
			this.storyInfo = data;
		})
		uni.$on('isplay', (data)=>{
			console.log("isplay:",data);
			this.isPlayingState = data.isplay;
		})
	},
	mounted() {
		if(this.value) this.open()
		
		let that = this;
		
		try {
			this.$audio.onTimeUpdate(() => {
			  that.currentTime = that.$audio.currentTime;
			  that.durationTime = that.$audio.duration;
			  if(!that.isChangeSlider) {
					that.playSliderNum = (that.$audio.currentTime / that.$audio.duration) * 100;
			  }
			  // console.log("this.durationTime",this.durationTime + ";" + this.playSliderNum);
			});
		} catch (e) {
		} finally {
		}
	},
	beforeDestroy() {
		try {
			// 在组件销毁前移除事件监听器
			this.$audio.offTimeUpdate();
		} catch (e) {
		} finally {
		}
	},
	methods: {
		onScroll(e) {
			this.scrollTop = e.detail.scrollTop
		},
		onTouch(ev) {
			// if(!this.maskClick) return
			const { pageX, pageY } = ev.changedTouches[0] || ev
			if(['touchstart', 'mousedown'].includes(ev.type)) {
				this.startX = pageX
				this.startY = pageY
				this.startTime = ev.timeStamp
			} else {
				if(!this.startTime) return
				const orien = this.isVertical ? 'Y' : 'X'
				let moveDis = pageY - this.startY
				if(this.from == 'left') moveDis = this.startX - pageX
				else if(this.from == 'right') moveDis = pageX - this.startX
				else if(this.from == 'top') moveDis = -moveDis
				if(!this.maskClick) moveDis /= 3
				const duration = (ev.timeStamp - this.startTime)
				const speed = moveDis/duration
				if(['touchend', 'mouseup'].includes(ev.type)) {
					if(this.panStyle) {
						if(this.maskClick && (moveDis > 120 || speed > 0.25)) {
							this.close()
						}
						else {
							this.panStyle = `transform: translate${orien}(0); transition: all ease 200ms;`
						}
						setTimeout(() => {
							this.panStyle = ''
						}, 300)
					}
					// conScrollTop = 0
					this.startTime = 0
					return
				}
				// if(this.scrollTop > 0) return
				
				if(moveDis > 0) {
					if(this.from == 'left' || this.from == 'top') moveDis *= -1
					this.panStyle = `transform: translate${orien}(${moveDis}px); transition: none;`
				}
			}
		},
		onChange({ show }) {
			this.showPopup = show
		},
		open() {
			this.$refs.popup.open()
			this.showPopup = true;
			let plstory = uni.getStorageSync('playing_story_to');
			if(plstory) {
				this.storyInfo = JSON.parse(plstory);
			}
			this.playItStart();
		},
		close() {
			this.$refs.popup.close();
			this.showPopup = false;
			uni.$emit('closePop')
		},
		onBack() {
			this.$emit('back')
		},
		
		playItStart() {
			console.log("playIt",this.storyInfo);
			if(this.storyInfo.id > 0) {
				this.$nextMax = 0;//初始化集数
				this.$nextMaxTime = 0;//初始化时长
				this.offsetY = 0;
				let plstory = uni.getStorageSync('playing_story');
				if(plstory) {
					this.story = JSON.parse(plstory);
				}
				this.$audio.singer = '故事花园';
				this.$audio.lrc = '';
				this.$audio.coverImgUrl = this.storyInfo.image;
				this.$audio.pre_url = this.storyInfo.filename;
				this.$audio.title = this.storyInfo.title;
				this.$audio.epname = this.storyInfo.cate_name;
				this.$audio.src = this.storyInfo.filename;
				// console.log("item",item.story_id);
				console.log("this.story.story_id",this.story.story_id);
				let fileNow = "";
				if(this.storyInfo.story_id == this.story.story_id) {
					this.showPlay = true;
					fileNow = pubc.Decrypt(this.storyInfo.filename);
					console.log("filename",this.storyInfo.filename);
					console.log("Decrypt",fileNow);
					// fileNow = "https://duoxiaoduoxue.com/media/mp3/6473.mp3";
					this.$audio.src = fileNow;
					// if(this.$audio.poused) {
					// 	this.$audio.play();
					// }
					// this.$audio.play();
					this.isPlaying();
				}else {
					this.showPlay = true;
					// console.log("play-pubc",item);
					fileNow = pubc.Decrypt(this.storyInfo.filename);
					console.log("filename",this.storyInfo.filename);
					console.log("Decrypt",fileNow);
					// fileNow = "https://duoxiaoduoxue.com/media/mp3/6473.mp3";
					// this.overflowh = 'hidden';
					this.$audio.src = fileNow;
					this.$audio.play();
					this.isPlaying();
				}
				this.isCollection("story",this.storyInfo.story_id);
				this.storyInfo.filename = fileNow;
				// this.story = item;
				this.cate_id = this.storyInfo.cate_id;
				
				
				// this.$musicInfo.title = '音乐标题';
				// backgroundAudioManager.epname = '专辑名称';
				// backgroundAudioManager.singer = '演唱者';
				// backgroundAudioManager.coverImgUrl = '封面图片地址'; // 推荐本地路径
				// backgroundAudioManager.src = '音乐文件地址';
				console.log("this.musicInfo",this.$musicInfo);
				
				let self = this;
				let dataString = uni.getStorageSync('story_list_all_' + this.storyInfo.cate_id);
				if(dataString) {
					let dataMsg = JSON.parse(dataString);
					this.StoryCate = dataMsg.StoryCate;
					this.StoryList = dataMsg.story;
				}else {
					this.loadData(1);
				}
				let that = this;
				setTimeout(function() {
					that.historyIt(that.storyInfo.story_id);
				},2000)
				
				let dataStringPlay = JSON.stringify(this.storyInfo);
				uni.setStorageSync('playing_story', dataStringPlay);
			}
		},
			handleChildBtnClick(event) {
			    event.stopPropagation(); // 阻止事件冒泡
			    console.log('子按钮被点击');
			},
			doNothing() {
			    event.stopPropagation(); // 阻止事件冒泡
			    console.log('子按钮被点击');
			},
			init() {
				this.offsetY = 0;
				this.showPlay = true;
			},
			SetLoopType() {
				if(this.isLoopOne) {
					this.isLoopOne = false;
					let nxt = {
						next1:0,
						next2:0
					}
					this.isLoopOne = true;
					uni.setStorageSync('next', nxt);
				}else {
					let nxt = {
						next1:0,
						next2:1
					}
					this.isLoopOne = true;
					uni.setStorageSync('next', nxt);
				}
			},
			selTimer(type,index) {
				if(type == 1) {
					this.time_sel1 = index
					this.time_sel2 = -1
					this.$nextMax = 0;
					this.$nextMaxTime = index * 10;
				}else if(type == 2) {
					this.time_sel2 = index
					this.time_sel1 = -1
					this.$nextMax = index + 1;
					this.$nextMaxTime = 0;
				}
				this.shopPlayTime = false;
			},
		  //   onChange(e) {
				// this.current = e.detail.current;
		  //   },
			convertSecondsToMinutesSeconds(seconds) {
				if(seconds > 0) {
					seconds = parseInt(seconds);
					var minutes = Math.floor(seconds / 60);
					var remainingSeconds = seconds % 60;
					return (minutes<10?'0'+minutes:minutes) + ":" + (remainingSeconds<10?'0'+remainingSeconds:remainingSeconds) + "";
				}else {
					return '00:00';
				}
			},
			playLastNext(type) {
				let dataString = uni.getStorageSync('story_list_all_' + this.storyInfo.cate_id);
				if(dataString) {
					let dataMsg = JSON.parse(dataString);
					let StoryList = dataMsg.story;
					let useNext = 0;
					let storyNext = '';
					if(type == 'last') {
						for (const item of StoryList) {
							if(parseInt(item.id) == parseInt(this.storyInfo.id)) {
								break;
							}
							storyNext = item;
						}
					}else {
						for (const item of StoryList) {
							if(useNext > 0) {
								storyNext = item;
								break;
							}
							// console.log("itemID:",parseInt(item.id) + "," + parseInt(story.id));
							if(parseInt(item.id) == parseInt(this.storyInfo.id)) {
								useNext = 1;
							}
						}
					}
					if(storyNext != "") {
						this.playIt2(storyNext);
					}
				}
			},
			playIt2(item) {
				this.offsetY = 0;
				this.story.title = item.title;
				item.story_id = item.id;
				this.story = item;
				this.isCollection("story",item.id);
				let that = this;
				setTimeout(function() {
					that.historyIt(that.story.story_id);
				},2000)
				this.storyInfo = item;
				this.$audio.singer = '故事花园';
				this.$audio.lrc = '';
				this.$audio.coverImgUrl = this.storyInfo.image;
				this.$audio.pre_url = this.storyInfo.filename;
				this.$audio.title = this.storyInfo.title;
				this.$audio.epname = this.storyInfo.cate_name;
				
				let fileNow = pubc.Decrypt(item.filename);
				console.log("filename",item.filename);
				console.log("Decrypt",fileNow);
				// fileNow = "https://duoxiaoduoxue.com/media/mp3/6473.mp3";
				// this.overflowh = 'hidden';
				this.$audio.src = fileNow;
				this.$audio.play();
				this.showStoryList = false;
				let dataStringPlay = JSON.stringify(this.story);
				uni.setStorageSync('playing_story', dataStringPlay);
				// let dataString = uni.getStorageSync('story_list_' + item.cate_id);
				// if(dataString) {
				// 	let dataMsg = JSON.parse(dataString);
				// 	this.StoryCate = dataMsg.StoryCate;
				// 	this.StoryList = dataMsg.story;
				// }else {
				// 	this.loadData(1);
				// }
			},
			playOrPause() {
				console.log("----playOrPause");
				try {
					if(this.$audio.paused) {
						this.isPlayingState = true;
						this.$audio.play();
					}else {
						this.isPlayingState = false;
						this.$audio.pause();
					}
				} catch (e) {
					// error
				}
			},
			isPlaying() {
				try {
					if(this.$audio.paused) {
						this.isPlayingState = false;
					}else {
						this.isPlayingState = true;
					}
				} catch (e) {
					// error
				}
				return !this.$audio.paused;
			},
			sliderChange(e) {
				console.log('value 发生变化：' + e.detail.value)
				let toTime = this.$audio.duration * e.detail.value / 100;
				// 计算目标播放时间（秒）
				// let targetTime = this.$audio.duration * 0.38;
				// 跳转到目标播放时间
				this.$audio.pause();
				this.$audio.seek(toTime);
				let that = this;
				setTimeout(function() {
					that.isChangeSlider = false;
					that.$audio.play();
				},200);
			  // this.playSliderNum = (this.$audio.currentTime / this.$audio.duration) * 100;
				// this.$audio.
			},
			sliderChanging(e) {
				this.isChangeSlider = true;
			},
			collectionIt(type,tid) {
				console.log("collectionIt");
				let obj2 = {
					cate_id:parseInt(tid)
				}
				if(type == 'story') {
					obj2 = {
						story_id:parseInt(tid)
					}
				}
				const postData = Object.assign({}, getApp().globalData.postHeader, obj2);
				
				console.log(postData);
				let self = this;
				uni.request({
				    url: this.$apiHost + '/Member/collection_edit', //仅为示例，并非真实接口地址。
				    data: postData,
					method:'POST',
				    header: {
				        'content-type': 'application/json' ,//自定义请求头信息
						'Access-Control-Allow-Origin':'*'
				    },
				    success: (res) => {
						console.log('data:', res.data);
						uni.showToast({
							title: res.data.msg
						});
						this.isCollection(type,tid)
				    }
				});
			},
			loadData(is_first) {
				console.log("this.globalData",getApp().globalData);
				let obj2 = {
					cate_id:""+this.cate_id+"",
					is_first:is_first
				}
				const postData = Object.assign({}, getApp().globalData.postHeader, obj2);
				
				console.log(postData);
				let self = this;
				uni.request({
				    url: this.$apiHost + '/Story/list', //仅为示例，并非真实接口地址。
				    data: postData,
					method:'POST',
				    header: {
				        'content-type': 'application/json' ,//自定义请求头信息
						'Access-Control-Allow-Origin':'*'
				    },
				    success: (res) => {
						console.log('data:', res.data);
						if(is_first == 0) {
							let dataString = JSON.stringify(res.data.msg);
							uni.setStorageSync('story_list_' + this.cate_id, dataString);
						}else if(is_first == 1) {
							this.StoryCate = res.data.msg.StoryCate;
							this.StoryList = res.data.msg.story;
							if(res.data.status) {
								setTimeout(function() {
									self.loadData(2);
								},1000);
							}
						}else if(is_first == 2) {
							this.StoryList = this.StoryList.concat(res.data.msg.story);
							let obj2 = {
								StoryCate:this.StoryCate,
								story:this.StoryList
							}
							let dataString = JSON.stringify(obj2);
							
							// console.log('dataString2:', dataString);
							uni.setStorageSync('story_list_all_' + this.cate_id, dataString);
						}
						
				    }
				});
			},
			isCollection(type,tid) {
				let obj2 = {
					type:""+type+"",
					cate_id:parseInt(tid)
				}
				if(type == 'story') {
					obj2 = {
						type:""+type+"",
						story_id:parseInt(tid)
					}
				}
				const postData = Object.assign({}, getApp().globalData.postHeader, obj2);
				let self = this;
				uni.request({
				    url: this.$apiHost + '/Story/isFavorite', //仅为示例，并非真实接口地址。
				    data: postData,
					method:'POST',
				    header: {
				        'content-type': 'application/json' ,//自定义请求头信息
						'Access-Control-Allow-Origin':'*'
				    },
				    success: (res) => {
						console.log('isCollection:', res.data);
						if(type == 'story') {
							this.collection_story = res.data.status;
						}else {
							this.collection_theme = res.data.status;
						}
						console.log("this.collection_theme",this.collection_theme);
				    }
				});
			},
			historyIt(tid) {
				let obj2 = {
					story_id:parseInt(tid)
				}
				const postData = Object.assign({}, getApp().globalData.postHeader, obj2);
				console.log(postData);
				let self = this;
				uni.request({
				    url: this.$apiHost + '/Member/history_edit', //仅为示例，并非真实接口地址。
				    data: postData,
					method:'POST',
				    header: {
				        'content-type': 'application/json' ,//自定义请求头信息
						'Access-Control-Allow-Origin':'*'
				    },
				    success: (res) => {
						console.log('historyIt:', res.data);
				    }
				});
			},
	}
}
</script>
