<template>
	<view class="page-container" :class="AppStyle">
		<!-- 状态栏安全区域 -->
		<view
			class="safe-area-inset-top"
			:style="{ height: statusBarHeight + 'px' }"
		></view>

		<!-- 导航栏 -->
		<view class="nav-header">
			<view class="nav-bar">
				<view class="nav-left">
					<text class="nav-icon cuIcon-back" @tap="back"></text>
				</view>
				<view class="nav-title-wrapper">
					<text class="nav-title-text">短视频</text>
				</view>
				<view class="nav-right">
					<text class="nav-icon cuIcon-upload" @tap="goUpload"></text>
				</view>
			</view>

			<!-- 搜索栏 -->
			<view class="search-wrapper">
				<view class="search-bar">
					<text class="search-icon cuIcon-search"></text>
					<input
						type="text"
						v-model="searchKeyword"
						placeholder="搜索感兴趣的视频"
						placeholder-class="placeholder"
						confirm-type="search"
						@confirm="searchVideos"
					/>
				</view>
			</view>
		</view>

		<!-- 内容区域 -->
		<scroll-view
			class="content-scroll"
			scroll-y
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="handleRefresh"
			@scrolltolower="loadMore"
			:style="{
				paddingTop: `${navigationHeight}px`
			}"
		>
			<view class="video-grid">
				<view
					class="video-card"
					v-for="(item, index) in videoList"
					:key="item.id"
					@tap="goDetail(item.id)"
				>
					<view class="video-cover">
						<image :src="item.cover_url" mode="aspectFill"></image>
						<view class="video-duration">{{item.duration_text || formatDuration(item.duration)}}</view>
						<view class="play-count">
							<view class="play-icon">
								<text class="cuIcon-video"></text>
							</view>
							<text class="count-text">{{formatNumber(item.view_count)}}</text>
						</view>
					</view>
					<view class="video-info">
						<view class="video-title">{{item.title}}</view>
						<view class="author-info">
							<image class="author-avatar" :src="item.author_avatar" mode="aspectFill"></image>
							<text class="author-name">{{item.author_name}}</text>
							<view class="stats">
								<text class="like-count">
									<text class="cuIcon-appreciatefill"></text>
									{{formatNumber(item.like_count)}}
								</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view class="loading-more" v-if="loading">
				<view class="loading-spinner"></view>
				<text>加载中...</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { localStorage } from '../../../js_sdk/mp-storage/mp-storage/index.js'

export default {
	data() {
		return {
			statusBarHeight: 0,
			navigationHeight: 0,
			StatusBar: this.StatusBar,
			CustomBar: this.CustomBar,
			NavBar: this.StatusBar + this.CustomBar,
			AppStyle: this.$store.state.AppStyle,
			token: '',
			isLogin: false,
			loading: true,
			videoList: [],
			page: 1,
			limit: 12,
			hasMore: true,
			submitStatus: false,
			isRefreshing: false,
			refreshTimer: null,
			searchKeyword: ''
		}
	},
	onLoad() {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight;
		this.navigationHeight = this.statusBarHeight + 44 + 56; // 状态栏 + 导航栏 + 搜索栏

		// 获取token
		this.token = localStorage.getItem('token') || '';
		this.isLogin = !!this.token;

		// 加载视频列表
		this.getVideoList();
	},
	onPullDownRefresh() {
		this.handleRefresh();
	},
	onReachBottom() {
		// 上拉加载更多
		if (this.hasMore && !this.loading) {
			this.loadMore();
		}
	},
	methods: {
		// 返回上一页
		back() {
			uni.navigateBack({
				delta: 1
			});
		},

		// 获取视频列表
		getVideoList() {
			return new Promise((resolve, reject) => {
				if (this.submitStatus) {
					resolve();
					return;
				}

				if (!this.hasMore && this.page > 1) {
					resolve();
					return;
				}

				const that = this;
				that.loading = true;
				that.submitStatus = true;

				uni.request({
					url: that.$API.PluginLoad('xqy_video'),
					data: {
						action: 'getVideoList',
						plugin: 'xqy_video',
						page: that.page,
						limit: that.limit,
						status: 1,
						token: that.token,
						keyword: that.searchKeyword
					},
					method: 'GET',
					success: function(res) {
						that.loading = false;
						that.submitStatus = false;

						if (res.data.code === 200) {
							const videos = res.data.data.videos || [];

							if (that.page === 1) {
								that.videoList = videos;
							} else {
								that.videoList = [...that.videoList, ...videos];
							}

							that.hasMore = videos.length >= that.limit;
							resolve();
						} else {
							uni.showToast({
								title: res.data.msg || '获取视频列表失败',
								icon: 'none'
							});
							reject(new Error(res.data.msg));
						}
					},
					fail: function(err) {
						that.loading = false;
						that.submitStatus = false;

						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
						reject(err);
					},
					complete: function() {
						// 确保在完成时重置刷新状态
						that.isRefreshing = false;
						uni.stopPullDownRefresh();
					}
				});
			});
		},

		// 加载更多
		loadMore() {
			if (!this.hasMore || this.loading) return;
			this.page++;
			this.getVideoList();
		},

		// 跳转到视频详情页
		goDetail(id) {
			uni.navigateTo({
				url: `/pages/plugins/xqy_video/detail?id=${id}`
			});
		},

		// 跳转到视频上传页
		goUpload() {
			if (!this.isLogin) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return;
			}

			uni.navigateTo({
				url: '/pages/plugins/xqy_video/upload'
			});
		},

		// 格式化数字
		formatNumber(num) {
			if (!num) return '0';
			if (num < 1000) return num.toString();
			if (num < 10000) return (num / 1000).toFixed(1) + 'K';
			return (num / 10000).toFixed(1) + 'W';
		},

		// 格式化时长
		formatDuration(seconds) {
			if (!seconds) return '00:00';
			const minutes = Math.floor(seconds / 60);
			const remainingSeconds = Math.floor(seconds % 60);
			return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
		},

		// 添加搜索视频方法
		searchVideos(e) {
			const keyword = e.detail.value.trim();
			if (!keyword) {
				uni.showToast({
					title: '请输入搜索关键词',
					icon: 'none'
				});
				return;
			}

			this.searchKeyword = keyword;
			this.page = 1;
			this.videoList = [];
			this.hasMore = true;
			this.getVideoList();
		},

		// 添加新的刷新处理方法
		async handleRefresh() {
			if (this.isRefreshing) return;

			this.isRefreshing = true;
			this.page = 1;
			this.videoList = [];
			this.hasMore = true;

			try {
				await this.getVideoList();
			} catch (error) {
				console.error('刷新失败:', error);
			} finally {
				// 延迟结束刷新状态，提供更好的视觉反馈
				setTimeout(() => {
					this.isRefreshing = false;
					uni.stopPullDownRefresh();
				}, 500);
			}
		}
	},
	mounted() {
		// 确保样式正确应用
		this.$nextTick(() => {
			// 强制更新视图
			this.$forceUpdate();
		});
	},
	beforeDestroy() {
		if (this.refreshTimer) {
			clearTimeout(this.refreshTimer);
		}
	}
}
</script>

<style lang="scss">
.page-container {
	min-height: 100vh;
	background: #f8f8f8;
	position: relative;
}

/* 状态栏安全区域 */
.safe-area-inset-top {
	width: 100%;
	background: #fff;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 100;
}

/* 导航头部区域 */
.nav-header {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 99;
	background: #fff;
	box-shadow: 0 1px 0 rgba(0, 0, 0, 0.05);

	/* 导航栏 */
	.nav-bar {
		padding: 0 16px;
		height: 44px;
		margin-top: var(--status-bar-height);
		display: flex;
		align-items: center;
		justify-content: space-between;

		.nav-left, .nav-right {
			min-width: 32px;
			height: 32px;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.nav-icon {
			font-size: 24px;
			color: #333;
			opacity: 0.9;
		}

		.nav-title-wrapper {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;

			.nav-title-text {
				/* 重置所有默认样式 */
				all: unset;
				display: inline-block;

				/* 基础样式设置 */
				font-size: 17px !important;
				font-weight: 500 !important;
				color: #333 !important;
				text-align: center !important;
				line-height: 1 !important;

				/* 移动端特定样式重置 */
				text-transform: none !important;
				text-decoration: none !important;
				text-shadow: none !important;
				letter-spacing: 0 !important;
				word-spacing: normal !important;
				white-space: nowrap !important;

				/* 字体设置 */
				font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue',
							 Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC',
							 'miui', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif !important;

				/* 确保每个字符样式一致 */
				&::first-letter,
				&::first-line,
				& > text,
				& > span {
					font-size: inherit !important;
					font-weight: inherit !important;
					color: inherit !important;
					font-family: inherit !important;
					letter-spacing: inherit !important;
					text-transform: inherit !important;
					text-decoration: inherit !important;
					text-shadow: inherit !important;
				}

				/* 移动端特定样式覆盖 */
				/* #ifdef APP-PLUS */
				&,
				&::first-letter,
				&::first-line,
				& > text,
				& > span {
					font-size: 17px !important;
					font-weight: 500 !important;
					color: #333 !important;
					letter-spacing: 0 !important;
				}
				/* #endif */
			}
		}
	}

	/* 搜索区域 */
	.search-wrapper {
		padding: 8px 16px 12px;

		.search-bar {
			height: 36px;
			background: #f5f5f5;
			border-radius: 18px;
			display: flex;
			align-items: center;
			padding: 0 12px;
			transition: all 0.3s ease;

			&:active {
				background: #ebebeb;
			}

			.search-icon {
				font-size: 16px;
				color: #999;
				margin-right: 8px;
			}

			input {
				flex: 1;
				height: 36px;
				color: #333;
				font-size: 15px;

				&::placeholder {
					color: #999;
				}
			}
		}
	}
}

/* 内容滚动区域 */
.content-scroll {
	flex: 1;
	height: 100vh;
	background: #f8f8f8;

	&::-webkit-scrollbar {
		display: none;
	}
}

/* 暗黑模式适配 */
.dark {
	.page-container {
		background: #000;
	}

	.safe-area-inset-top {
		background: #1c1c1e;
	}

	.nav-header {
		background: #1c1c1e;
		box-shadow: 0 1px 0 rgba(255, 255, 255, 0.05);

		.nav-bar {
			.nav-icon {
				color: #fff;
			}

			.nav-title-wrapper {
				.nav-title-text {
					color: #fff !important;

					/* 移动端暗黑模式特定样式 */
					/* #ifdef APP-PLUS */
					&,
					&::first-letter,
					&::first-line,
					& > text,
					& > span {
						color: #fff !important;
					}
					/* #endif */
				}
			}

			.search-wrapper .search-bar {
				background: rgba(255, 255, 255, 0.1);

				&:active {
					background: rgba(255, 255, 255, 0.15);
				}

				input {
					color: #fff;

					&::placeholder {
						color: rgba(255, 255, 255, 0.6);
					}
				}

				.search-icon {
					color: rgba(255, 255, 255, 0.6);
				}
			}
		}

		.content-scroll {
			background: #000;
		}
	}
}

/* iOS风格动画 */
@keyframes scale-up {
	from {
		transform: scale(0.95);
		opacity: 0;
	}
	to {
		transform: scale(1);
		opacity: 1;
	}
}

/* 视频网格样式 */
.video-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 10px;
	padding: 10px;

	.video-card {
		background: #fff;
		border-radius: 12px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		transform: translateY(0);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(2px);
		}

		.video-cover {
			position: relative;
			padding-top: 56.25%; // 16:9 比例

			image {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.video-duration {
				position: absolute;
				bottom: 8px;
				right: 8px;
				background: rgba(0, 0, 0, 0.6);
				color: #fff;
				padding: 2px 6px;
				border-radius: 4px;
				font-size: 12px;
			}

			.play-count {
				position: absolute;
				bottom: 8px;
				left: 8px;
				color: #fff;
				font-size: 12px;
				display: flex;
				align-items: center;
				background: rgba(0, 0, 0, 0.5);
				padding: 2px 6px;
				border-radius: 12px;

				.play-icon {
					display: flex;
					align-items: center;
					margin-right: 4px;

					.cuIcon-video {
						font-size: 14px;
						color: #fff;
					}
				}

				.count-text {
					font-size: 12px;
					color: #fff;
					font-weight: 500;
				}
			}
		}

		.video-info {
			padding: 10px;

			.video-title {
				font-size: 14px;
				font-weight: 500;
				line-height: 1.3;
				margin-bottom: 8px;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
			}

			.author-info {
				display: flex;
				align-items: center;

				.author-avatar {
					width: 24px;
					height: 24px;
					border-radius: 50%;
					margin-right: 6px;
				}

				.author-name {
					flex: 1;
					font-size: 12px;
					color: #666;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.stats {
					font-size: 12px;
					color: #999;

					.like-count {
						display: flex;
						align-items: center;

						.cuIcon-appreciatefill {
							margin-right: 2px;
							font-size: 14px;
						}
					}
				}
			}
		}
	}
}

/* 加载更多样式 */
.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 16px 0;
	opacity: 0;
	transition: opacity 0.3s ease;

	&.visible {
		opacity: 1;
	}

	.loading-spinner {
		width: 18px;
		height: 18px;
		border: 2px solid #f3f3f3;
		border-top: 2px solid #FF6B6B;
		border-radius: 50%;
		animation: spin 0.8s linear infinite;
	}
}
</style>

