<template>
	<view class="english-journal-page">
		<!-- 顶部导航栏 -->
		<uni-nav-bar
			left-icon="left"
			:title="isEditMode ? '选择期刊' : '英文期刊'"
			@clickLeft="goBack"
			fixed
			color="#8B2316"
			height="180rpx"
			: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="journal-list"
			refresher-enabled
			@refresherrefresh="onRefresh"
			:refresher-triggered="refreshing"
			@scrolltolower="onLoadMore"
			:lower-threshold="100"
		>
			<view class="journal-item" v-for="(item, index) in journalList" :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="content">
					<view class="title">{{ item.title }}</view>
					<view class="subtitle">{{ item.subtitle }}</view>
				</view>
			</view>
			
			<!-- 加载更多提示 -->
			<view v-if="loading" class="loading-more">
				<text>加载中...</text>
			</view>
			
			<!-- 空数据状态 -->
			<view v-if="!loading && journalList.length === 0" class="empty-state">
				<text>暂无英文期刊</text>
			</view>
			
			<!-- 没有更多数据提示 -->
			<view v-if="noMore && journalList.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';
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 journalList = 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/qikan?id=${item.id}&title=${encodeURIComponent(item.title)}&subtitle=${encodeURIComponent(item.subtitle)}&path=${encodeURIComponent(item.path)}&libraryUuid=${encodeURIComponent(item.libraryUuid)}`
	});
};

// 切换选择状态
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 === journalList.value.length) {
		// 取消全选
		selectedItems.value = [];
	} else {
		// 全选
		selectedItems.value = journalList.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.deleteCollect({
					uuid: selectedItems.value.join(',')
				}).then(res => {
					if (res.code === 200) {
						// 从本地列表中移除
						journalList.value = journalList.value.filter(item => !selectedItems.value.includes(item.id));
						selectedItems.value = [];
						isEditMode.value = false;
						
						uni.showToast({ 
							title: '删除成功', 
							icon: 'none' 
						});
					} else {
						uni.showToast({ 
							title: res.message || '删除失败', 
							icon: 'none' 
						});
					}
				}).catch(err => {
					console.error('删除失败:', err);
					uni.showToast({ 
						title: '删除失败，请重试', 
						icon: 'none' 
					});
				});
			}
		}
	});
};

// 获取期刊列表
const getJournalList = () => {
	api.getCollectList({
		page: page.value,
		pageSize: pageSize.value,
		type: 3
	}).then(res => {
		console.log(res);
		if (res.code === 200 && res.data) {
			const { list, totalRow, totalPage, pageNumber } = res.data;
			
			// 如果是第一页，清空列表
			if (page.value === 1) {
				journalList.value = [];
			}
			
			// 处理期刊数据
			const processedList = list.map(item => ({
				id: item.uuid,
				title: item.title || '未知标题',
				subtitle: item.secondTitle || '未知副标题',
				libraryUuid: item.libraryUuid,
				path: item.path,
				createDate: item.createDate,
				isCollect: item.isCollect,
				status: item.status
			}));
			
			// 添加到列表
			journalList.value.push(...processedList);
			
			// 更新分页状态
			noMore.value = pageNumber >= totalPage;
			
			// 如果是第一页且有数据，显示总数
			if (page.value === 1 && totalRow > 0) {
				uni.showToast({ 
					title: `共找到 ${totalRow} 条记录`, 
					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刷新数据
	getJournalList();
};

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

onMounted(() => {
	getJournalList();
});
</script>

<style lang="scss" scoped>
.english-journal-page {
	min-height: 100vh;
	background: #ffffff;
}

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

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

.journal-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	background: #ffffff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.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;
			}
		}
	}
	
	.content {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		
		.title {
			font-size: 28rpx;
			color: #333333;
			line-height: 1.4;
			margin-bottom: 8rpx;
		}
		
		.subtitle {
			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>
