<template>
	<view class="video-history-page">
		<!-- 顶部导航栏 -->
		<uni-nav-bar
			left-icon="left"
			:title="isEditMode ? '选择视频' : '观看历史'"
			@clickLeft="goBack"
			fixed
			color="#8B2316"
			height="140rpx"
			:border="false"
			backgroundColor="#eeeeee"
		>
			<template v-slot:right>
				<text class="edit-btn" @click="onEdit">{{ isEditMode ? '取消' : '编辑' }}</text>
			</template>
		</uni-nav-bar>

		<!-- 观看历史列表 -->
		<scroll-view 
			scroll-y 
			class="history-list"
			refresher-enabled
			@refresherrefresh="onRefresh"
			:refresher-triggered="refreshing"
			@scrolltolower="onLoadMore"
			:lower-threshold="100"
		>
			<view class="history-item" v-for="(item, index) in historyList" :key="item.id" @click="onItemClick(item)">
				<!-- 选择框 -->
				<view v-if="isEditMode" class="checkbox-wrapper" @click.stop="toggleSelect(item)">
					<view class="checkbox" :class="{ 'checked': selectedItems.includes(item.id) }">
						<text v-if="selectedItems.includes(item.id)" class="check-icon">✓</text>
					</view>
				</view>
				
				<view class="thumbnail">
					<image :src="item.thumbnail" width="200rpx" height="120rpx" mode="aspectFill" class="thumb-img"></image>
				</view>
				<view class="content">
					<view class="title">{{ item.title }}</view>
					<view class="author">{{ item.author }}</view>
				</view>
			</view>
			
			<!-- 加载更多提示 -->
			<view v-if="loading" class="loading-more">
				<text>加载中...</text>
			</view>
			
			<!-- 空数据状态 -->
			<view v-if="!loading && historyList.length === 0" class="empty-state">
				<text>暂无观看历史</text>
			</view>
			
			<!-- 没有更多数据提示 -->
			<view v-if="noMore && historyList.length > 0" class="no-more">
				<text>没有更多数据了</text>
			</view>
		</scroll-view>
		
		<!-- 底部操作栏 -->
		<view v-if="isEditMode" class="bottom-action-bar">
			<view class="action-left">
				<text class="select-all-btn" @click="toggleSelectAll">全选</text>
			</view>
			<view class="action-right">
				<text class="delete-btn" @click="deleteSelected" :class="{ 'disabled': selectedItems.length === 0 }">删除</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '@/api/api.js';
import docUrl from "@/utils/docUrl.js";
const refreshing = ref(false);
const loading = ref(false);
const noMore = ref(false);
const page = ref(1);
const pageSize = ref(10);
const isEditMode = ref(false);
const selectedItems = ref([]);
const historyList = ref([]);

const goBack = () => {
	uni.navigateBack();
};

const onEdit = () => {
	if (isEditMode.value) {
		// 退出编辑模式
		isEditMode.value = false;
		selectedItems.value = [];
	} else {
		// 进入编辑模式
		isEditMode.value = true;
	}
};

const onItemClick = (item) => {
	// 编辑模式下不跳转
	if (isEditMode.value) {
		return;
	}
	
	// 跳转到视频详情页面
	uni.navigateTo({
		url: `/pages_app/videoDetail/videoDetail?id=${item.id}&title=${encodeURIComponent(item.title)}&author=${encodeURIComponent(item.author)}&videoPath=${encodeURIComponent(item.videoPath)}&polyvUuid=${encodeURIComponent(item.polyvUuid)}`
	});
};

// 切换选择状态
const toggleSelect = (item) => {
	const index = selectedItems.value.indexOf(item.id);
	if (index > -1) {
		selectedItems.value.splice(index, 1);
	} else {
		selectedItems.value.push(item.id);
	}
};

// 全选/取消全选
const toggleSelectAll = () => {
	if (selectedItems.value.length === historyList.value.length) {
		// 取消全选
		selectedItems.value = [];
	} else {
		// 全选
		selectedItems.value = historyList.value.map(item => item.id);
	}
};

// 删除选中的视频
const deleteSelected = () => {
	if (selectedItems.value.length === 0) {
		uni.showToast({ title: '请选择要删除的视频', icon: 'none' });
		return;
	}
	
	
	uni.showModal({
		title: '确认删除',
		content: `确定要删除选中的 ${selectedItems.value.length} 个视频吗？`,
		success: (res) => {
			if (res.confirm) {
				// 这里可以调用删除API
				api.deleteRecord({
					video_uuid: selectedItems.value.join(',')
				}).then(res => {
					console.log(res);
				});
				// 暂时从本地列表中移除
				historyList.value = historyList.value.filter(item => !selectedItems.value.includes(item.id));
				selectedItems.value = [];
				isEditMode.value = false;
				
				
				uni.showToast({ 
					title: '删除成功', 
					icon: 'none' 
				});
			}
		}
	});
};

onMounted(() => {
	getVideoHistoryList();
});

const getVideoHistoryList = () => {
	api.getVideoHistory({
		page: page.value,
		pageSize: pageSize.value
	}).then(res => {
		console.log(res);
		if (res.code === '200' && res.data) {
			const { list, isLastPage, total } = res.data;
			
			// 如果是第一页，清空列表
			if (page.value === 1) {
				historyList.value = [];
			}
			
			// 处理视频数据
			const processedList = list.map(item => ({
				id: item.video_uuid,
				thumbnail: docUrl + item.imgpath || '/static/bo_bg.png',
				title: item.video_name || '未知标题',
				author: item.public_name || item.user_name || '未知作者',
				videoPath: item.path,
				polyvUuid: item.polyv_uuid,
				content: item.content,
				videoType: item.video_type,
				status: item.status
			}));
			
			// 添加到列表
			historyList.value.push(...processedList);
			
			// 更新分页状态
			noMore.value = isLastPage;
			
			// 如果是第一页且有数据，显示总数
			if (page.value === 1 && total > 0) {
				uni.showToast({ 
					title: `共找到 ${total} 条记录`, 
					icon: 'none',
					duration: 2000
				});
			}
		} else {
			uni.showToast({ 
				title: res.message || '获取数据失败', 
				icon: 'none' 
			});
		}
	}).catch(err => {
		console.error('获取视频历史失败:', err);
		uni.showToast({ 
			title: '网络错误，请重试', 
			icon: 'none' 
		});
	}).finally(() => {
		loading.value = false;
		refreshing.value = false;
	});
};

const onRefresh = () => {
	refreshing.value = true;
	page.value = 1;
	noMore.value = false;
	
	// 调用API刷新数据
	getVideoHistoryList();
};

const onLoadMore = () => {
	if (loading.value || noMore.value) return;
	
	loading.value = true;
	page.value++;
	
	// 调用API加载更多数据
	getVideoHistoryList();
};
</script>

<style lang="scss" scoped>
.video-history-page {
	min-height: 100vh;
	background: #f9f9f9;
}

.history-list {
	height: calc(100vh - 140rpx);
	position: fixed;
	top:140rpx;
	bottom:0;
	width:100%;
	padding-bottom: 100rpx; /* 为底部操作栏留出空间 */
}

.edit-btn {
	color: #8B2316;
	font-size: 28rpx;
	padding: 10rpx;
}

.history-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	background: #ffffff;
	margin-bottom: 2rpx;
	
	.checkbox-wrapper {
		margin-right: 20rpx;
		
		.checkbox {
			width: 40rpx;
			height: 40rpx;
			border: 2rpx solid #ddd;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #fff;
			
			&.checked {
				background: #8B2316;
				border-color: #8B2316;
			}
			
			.check-icon {
				color: #fff;
				font-size: 24rpx;
				font-weight: bold;
			}
		}
	}
	
	.thumbnail {
		margin-right: 20rpx;
		border-radius: 8rpx;
		overflow: hidden;
		
		.thumb-img {
			width: 200rpx;
			height: 120rpx;
			border-radius: 8rpx;
		}
	}
	
	.content {
		flex: 1;
		display: flex;
		height: 120rpx;
		flex-direction: column;
		justify-content: space-between;
		margin-right: 20rpx;
		
		.title {
			font-size: 28rpx;
			color: #333333;
			line-height: 1.4;
			margin-bottom: 10rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
		}
		
		.author {
			font-size: 24rpx;
			color: #666666;
		}
	}
}

.loading-more, .no-more, .empty-state {
	text-align: center;
	padding: 30rpx;
	color: #999999;
	font-size: 26rpx;
}

.empty-state {
	padding: 100rpx 30rpx;
	color: #999999;
}

.bottom-action-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background: #fff;
	border-top: 1rpx solid #eee;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	z-index: 100;
	
	.action-left {
		.select-all-btn {
			color: #333;
			font-size: 28rpx;
			padding: 20rpx;
		}
	}
	
	.action-right {
		.delete-btn {
			color: #ff4757;
			font-size: 28rpx;
			padding: 20rpx;
			
			&.disabled {
				color: #ccc;
			}
		}
	}
}
</style>
