<template>
	<view class="container">
		<view class="search-container">
			<uni-search-bar class="uni-mt-10" radius="5" placeholder="搜索视频名称" clearButton="auto" cancelButton="none"
				@confirm="search">
			</uni-search-bar>
		</view>
		<view class="uni-list uni-common-mt">
			<view class="video-container">
				<video id="myVideo" :src="videoSrc" :poster="posterSrc" @error="videoErrorCallback"
					:danmu-list="danmuList" controls show-loading show-mute-btn></video>
			</view>
			<!-- #ifndef MP-ALIPAY -->
			<!-- <view class="uni-list uni-common-mt">
		        <view class="uni-list-cell">
		            <view>
		                <view class="uni-label">弹幕内容</view>
		            </view>
		            <view class="uni-list-cell-db">
		                <input v-model="danmuValue" class="uni-input" type="text" placeholder="在此处输入弹幕内容" />
		            </view>
		        </view>
		    </view> -->
			<!-- <view class="uni-btn-v">
		        <button @click="sendDanmu" class="page-body-button">发送弹幕</button>
		    </view> -->
			<!-- #endif -->
			<uni-section title="播放列表" type="line">
				<uni-list v-for="(v, k) in videoList" :key="k">
					<uni-list-item clickable @click="onPlayListClick(v)">
						<template v-slot:header>
							<view class="slot-box">
								<image class="slot-image" :src="v.imSrc"></image>
							</view>
						</template>
						<template v-slot:body>
							<text class="slot-box slot-text">{{v.title}}</text>
							<!-- <text class="slot-box slot-text"></text> -->
						</template>
						<template v-slot:footer>
							<text class="slot-box slot-text-play">立即载入</text>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-section>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				src: '',
				danmuList: [{
					text: '第 1s 出现的弹幕',
					color: '#ff0000',
					time: 1
				}],
				videoList: [{
						title: '鞠婧祎视频 1 ',
						viSrc: 'https://afanai.top:8088/video/982789760.mp4',
						imSrc: 'https://afanai.top:8088/video/982789760frame.jpg',
						video_id: ''
					},
					{
						title: '鞠婧祎视频 2 ',
						viSrc: 'https://afanai.top:8088/video/428743782.mp4',
						imSrc: 'https://afanai.top:8088/video/428743782frame.jpg',
						video_id: ''
					}
				],
				videoListDefault: [{
						title: '鞠婧祎视频 1 ',
						viSrc: 'https://afanai.top:8088/video/982789760.mp4',
						imSrc: 'https://afanai.top:8088/video/982789760frame.jpg',
						video_id: ''
					},
					{
						title: '鞠婧祎视频 2 ',
						viSrc: 'https://afanai.top:8088/video/428743782.mp4',
						imSrc: 'https://afanai.top:8088/video/428743782frame.jpg',
						video_id: ''
					}
				],
				danmuValue: '',
				videoSrc: '',
				posterSrc: ''
			}
		},
		onReady: function(res) {
			// #ifndef MP-ALIPAY
			this.videoContext = uni.createVideoContext('myVideo')
			// #endif
		},
		methods: {
			sendDanmu: function() {
				this.videoContext.sendDanmu({
					text: this.danmuValue,
					color: this.getRandomColor()
				});
				this.danmuValue = '';
			},
			videoErrorCallback: function(e) {
				// uni.showModal({
				// 	content: e.target.errMsg,
				// 	showCancel: false
				// })
			},
			getRandomColor: function() {
				const rgb = []
				for (let i = 0; i < 3; ++i) {
					let color = Math.floor(Math.random() * 256).toString(16)
					color = color.length == 1 ? '0' + color : color
					rgb.push(color)
				}
				return '#' + rgb.join('')
			},
			async search(res) {
				if (res.value == "") {
					this.videoList = this.videoListDefault;
				} else {
					let newVideoList = [];
					this.videoList = [];

					newVideoList = await this.fetchSearchResults(res.value);
					newVideoList.forEach((v, index) => {
						let videoItem = {
							title: v["video_name"],
							// viSrc: v["video_url"],
							viSrc: "",
							imSrc: v["cover_url"],
							video_id: v["video_id"]
						};
						this.videoList.push(videoItem);
					})
				}

				this.videoSrc = "";
				this.posterSrc = "";
			},
			async fetchSearchResults(query) {
				// 调用后端接口
				// 直接在URL后拼接查询参数
				const res = await uni.request({
					url: `https://afanai.top:8089/v1/video/search?query=${encodeURIComponent(query)}`,
					method: 'GET',
					header: {} // GET请求不需要content-type
				});

				if (res.statusCode === 200) {
					const data = res.data;

					// 检查数据是否为JSON格式
					if (typeof data === 'string') {
						data = JSON.parse(data);
					}

					// 假设后端返回的是一个名为'queryRes'的数组
					if (Array.isArray(data.queryRes)) {
						// 处理列表数据，例如更新组件数据
						return data.queryRes;
					} else {
						uni.showToast({
							title: '未搜索到相关视频',
							duration: 2000,
							icon: 'none'
						});
						return [];
					}
				} else {
					uni.showToast({
						title: '查找失败',
						duration: 2000,
						icon: 'none'
					});
					return [];
				}
			},
			// search: function(res) {
			// 	// 更新搜索列表
			// 	uni.showToast({
			// 		title: res.value,
			// 		icon: 'none'
			// 	})
			// },
			async onPlayListClick(res) {
				if (this.posterSrc == res.imSrc) {
					uni.showToast({
						title: "已载入",
						icon: 'success'
					})
					return;
				}

				if (res.video_id === '') {
					this.videoSrc = res.viSrc;
					this.posterSrc = res.imSrc;
					uni.showToast({
						title: res.title,
						icon: 'success'
					})
				} else {
					// 查询链接
					this.videoSrc = await this.fetchVideoUrl(res.video_id);
					this.posterSrc = res.imSrc;
					uni.showToast({
						title: res.title,
						icon: 'success'
					})
				}
			},
			async fetchVideoUrl(query) {
				// 调用后端接口
				// 直接在URL后拼接查询参数
				const res = await uni.request({
					url: `https://afanai.top:8089/v1/video/getBlobUrl?query=${encodeURIComponent(query)}`,
					method: 'GET',
					header: {} // GET请求不需要content-type
				});

				if (res.statusCode === 200) {
					const data = res.data;
					// 检查数据是否为JSON格式
					if (typeof data === 'string') {
						data = JSON.parse(data);
					}
					// 假设后端返回的是一个名为'queryRes'
					if (data.queryRes) {
						// 处理列表数据，例如更新组件数据
						return data.queryRes;
					} else {
						uni.showToast({
							title: '未搜索到相关视频',
							duration: 2000,
							icon: 'none'
						});
						return "";
					}
				} else {
					uni.showToast({
						title: '查找失败',
						duration: 2000,
						icon: 'none'
					});
					return "";
				}
			},
		}
	}
</script>

<style scoped>
	.video-container {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.video {
		width: 300px;
		height: 225px;
		line-height: 0;
		overflow: hidden;
		position: relative;
	}

	.slot-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
	}

	.slot-image {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		margin-right: 10px;
		width: 72px;
		height: 48px;
	}

	.slot-text {
		flex: 1;
		font-size: 16px;
		margin-right: 10px;
	}

	.slot-text-play {
		font-size: 14px;
		color: #008acf;
		margin-right: 5px;
	}
</style>