
<!-- 自选股页面 -->
<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-content">
				<view class="navbar-left">
					<view class="back-btn" @click="goBack">
						<image class="back-icon" src="https://d31zlh4on95l9h.cloudfront.net/images/e5c501fd23303533622fadce8dedd6a0.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="navbar-center">
					<text class="navbar-title">我的自选</text>
				</view>
				<view class="navbar-right">
					<image 
						class="navbar-btn" 
						src="https://d31zlh4on95l9h.cloudfront.net/images/ba5c8a2eda065274e868bcd9b2d7d914.png"
						@click="onFirstButtonClick"
						mode="aspectFit"
					></image>
					<image 
						class="navbar-btn" 
						src="https://d31zlh4on95l9h.cloudfront.net/images/a4ae8952aeae90dac6d2b4c221c65fa9.png"
						@click="onSecondButtonClick"
						mode="aspectFit"
					></image>
				</view>
			</view>
		</view>
		
		<!-- 页面内容 -->
		<view class="page-content">
			<!-- 分组标签 -->
			<view class="group-tabs" v-if="stockGroups.length > 0">
				<scroll-view class="tabs-scroll" scroll-x="true" show-scrollbar="false">
					<view class="tabs-container">
						<view 
							v-for="group in stockGroups" 
							:key="group.id"
							:class="['tab-item', { 'active': currentGroupId === group.id }]"
							@click="switchGroup(group.id)"
						>
							<text class="tab-text">{{ group.name }}</text>
						</view>
					</view>
				</scroll-view>
			</view>
			
			<!-- 股票列表 -->
			<view class="stock-list">
				<view v-if="loading" class="loading-container">
					<text class="loading-text">加载中...</text>
				</view>
				<view v-else-if="stockList.length === 0" class="empty-container">
					<image 
						class="empty-image" 
						src="https://d31zlh4on95l9h.cloudfront.net/images/f5a9bd32c81bc7cca47252b51357c12f.png"
						mode="aspectFit"
					></image>
					<text class="empty-text">暂无数据~</text>
				</view>
				<view v-else>
					<view 
						v-for="stock in stockList" 
						:key="stock.id"
						class="stock-item"
						@click="handleStockClick(stock)"
					>
						<!-- 多选模式下显示复选框 -->
						<view v-if="isMultiSelectMode" class="checkbox-container">
							<view 
								:class="['checkbox', selectedStockIds.includes(stock.id) ? 'checked' : '']"
								@click.stop="toggleStockSelection(stock.id)"
							>
								<text v-if="selectedStockIds.includes(stock.id)" class="checkbox-icon">✓</text>
							</view>
						</view>
						
						<view class="stock-info">
							<text class="stock-name">{{ stock.name || stock.code }}</text>
							<text class="stock-code">{{ stock.code }}</text>
						</view>
						<view class="stock-price">
							<text class="price">{{ stock.price || '--' }}</text>
							<text :class="['change', stock.change >= 0 ? 'up' : 'down']">
								{{ stock.change >= 0 ? '+' : '-' }}{{ stock.change || '--' }}
							</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 多选模式下的底部操作栏 -->
		<view v-if="isMultiSelectMode" class="bottom-toolbar">
			<view class="toolbar-left">
				<text class="selected-count">已选择 {{ selectedStockIds.length }} 只股票</text>
				<text class="select-all-btn" @click="toggleSelectAll">
					{{ isAllSelected ? '取消全选' : '全选' }}
				</text>
			</view>
			<view class="toolbar-right">
				<button 
					class="add-to-group-btn" 
					:disabled="selectedStockIds.length === 0"
					@click="showGroupSelectModal = true"
				>
					添加至分组
				</button>
			</view>
		</view>
		
		<!-- 分组选择弹窗 -->
		<view v-if="showGroupSelectModal" class="modal-overlay" @click="closeGroupSelectModal">
			<view class="group-select-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">编辑分组</text>
					<text class="modal-close" @click="closeGroupSelectModal">✕</text>
				</view>
				<view class="modal-content">
					<view class="group-grid">
						<view 
							v-for="group in stockGroups" 
							:key="group.id"
							:class="['group-item', group.id === currentGroupId ? 'current-group' : '']"
							@click="selectTargetGroup(group)"
						>
							<text class="group-name">{{ group.name }}</text>
						</view>
						<view class="group-item new-group" @click="createNewGroupInModal">
							<text class="new-group-text">+ 新建分组</text>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<button class="confirm-btn" @click="confirmMoveToGroup">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getUserStockGroupList, addUserStockGroup, getUserStockList, updateUserStockGroup } from '@/api/home/mySelections.js'
	
	export default {
		data() {
			return {
				// 分组数据
				stockGroups: [],
				// 当前选中的分组ID
				currentGroupId: null,
				// 当前分组下的股票列表
				stockList: [],
				// 加载状态
				loading: false,
				// 多选模式状态
				isMultiSelectMode: false,
				// 选中的股票ID列表
				selectedStockIds: [],
				// 显示分组选择弹窗
				showGroupSelectModal: false,
				// 选中的目标分组
				selectedTargetGroup: null
			}
		},
		computed: {
			// 是否全选
			isAllSelected() {
				return this.stockList.length > 0 && this.selectedStockIds.length === this.stockList.length
			}
		},
		onLoad() {
			this.loadStockGroups()
		},
		methods: {
			// 加载股票分组
			async loadStockGroups() {
				this.loading = true
				try {
					getUserStockGroupList(
						(response) => {
							console.log('获取分组成功:', response)
							if (response.code === 200 && response.data) {
								// 按ID排序，ID小的排在前面
								this.stockGroups = response.data.sort((a, b) => a.id - b.id)
								// 如果有分组，默认选中第一个
								if (this.stockGroups.length > 0) {
									this.currentGroupId = this.stockGroups[0].id
									this.loadStocksByGroup(this.currentGroupId)
								} else {
									// 如果没有分组，创建默认分组
									this.createDefaultGroup()
								}
							}
						},
						(error) => {
							console.error('获取分组失败:', error)
							// 如果获取失败，也尝试创建默认分组
							this.createDefaultGroup()
						}
					)
				} catch (error) {
					console.error('加载分组异常:', error)
				} finally {
					this.loading = false
				}
			},
			
			// 创建默认分组
			createDefaultGroup() {
				addUserStockGroup(
					(response) => {
						console.log('创建默认分组成功:', response)
						// 重新加载分组列表
						this.loadStockGroups()
					},
					(error) => {
						console.error('创建默认分组失败:', error)
					},
					{ name: '默认分组' }
				)
			},
			
			// 根据分组ID加载股票列表
			loadStocksByGroup(groupId) {
				if (!groupId) return
				
				getUserStockList(
				(response) => {
					console.log('获取股票列表成功:', response)
					if (response.code === 200 && response.data && response.data.records) {
						// 股票列表在data.records中，根据groupId过滤
						this.stockList = response.data.records.filter(stock => stock.groupId === groupId)
					} else {
						this.stockList = []
					}
				},
				(error) => {
					console.error('获取股票列表失败:', error)
					this.stockList = []
				},
				{ groupId: groupId }
			)
			},
			
			// 切换分组
			switchGroup(groupId) {
				if (this.currentGroupId === groupId) return
				
				this.currentGroupId = groupId
				this.loadStocksByGroup(groupId)
			},
			
			// 创建新分组
			async createNewGroup(groupName) {
				if (!groupName) {
					uni.showToast({
						title: '分组名称不能为空',
						icon: 'none'
					})
					return
				}
				
				uni.showLoading({
					title: '创建中...'
				})
				console.log('开始请求创建分组接口')
				try {
					const response = await addUserStockGroup(null, null, {
						name: groupName
					})
					console.log('创建分组接口返回:', response)
					
					if (response.code === 200) {
						uni.showToast({
							title: '创建成功',
							icon: 'success'
						})
						// 重新加载分组列表
						await this.loadStockGroups()
						// 切换到新创建的分组
						if (response.data && response.data.id) {
							this.switchGroup(response.data.id)
						}
					} else {
						uni.showToast({
							title: response.message || '创建失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('创建分组失败:', error)
					uni.showToast({
						title: '创建失败，请重试',
						icon: 'none'
					})
				} finally {
					// 确保在所有情况下都隐藏加载状态
					uni.hideLoading()
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 第一个按钮点击事件 - 创建分组
			onFirstButtonClick() {
				uni.showModal({
					title: '创建分组',
					content: '请输入分组名称',
					editable: true,
					placeholderText: '请输入分组名称',
					success: (res) => {
						if (res.confirm && res.content) {
							this.createNewGroup(res.content.trim())
						}
					}
				})
			},
			
			// 第二个按钮点击事件 - 切换多选模式
			onSecondButtonClick() {
				this.isMultiSelectMode = !this.isMultiSelectMode
				// 退出多选模式时清空选中状态
				if (!this.isMultiSelectMode) {
					this.selectedStockIds = []
				}
				console.log('多选模式:', this.isMultiSelectMode)
			},
			
			// 处理股票点击事件
			handleStockClick(stock) {
				if (this.isMultiSelectMode) {
					// 多选模式下切换选中状态
					this.toggleStockSelection(stock.id)
				} else {
					// 普通模式下可以添加其他逻辑，比如跳转到股票详情
					console.log('点击股票:', stock)
				}
			},
			
			// 切换股票选中状态
			toggleStockSelection(stockId) {
				const index = this.selectedStockIds.indexOf(stockId)
				if (index > -1) {
					// 已选中，取消选中
					this.selectedStockIds.splice(index, 1)
				} else {
					// 未选中，添加到选中列表
					this.selectedStockIds.push(stockId)
				}
			},
			
			// 全选/取消全选
			toggleSelectAll() {
				if (this.isAllSelected) {
					// 取消全选
					this.selectedStockIds = []
				} else {
					// 全选
					this.selectedStockIds = this.stockList.map(stock => stock.id)
				}
			},
			
			// 关闭分组选择弹窗
			closeGroupSelectModal() {
				this.showGroupSelectModal = false
				this.selectedTargetGroup = null
			},
			
			// 选择目标分组
			selectTargetGroup(group) {
				this.selectedTargetGroup = group
			},
			
			// 在弹窗中创建新分组
			createNewGroupInModal() {
				uni.showModal({
					title: '创建分组',
					content: '请输入分组名称',
					editable: true,
					placeholderText: '请输入分组名称',
					success: (res) => {
						if (res.confirm && res.content) {
							this.createNewGroupAndSelect(res.content.trim())
						}
					}
				})
			},
			
			// 创建新分组并选中
			async createNewGroupAndSelect(groupName) {
				try {
					uni.showLoading({
						title: '创建中...'
					})
					
					const response = await addUserStockGroup(null, null, {
						name: groupName
					})
					
					if (response.code === 200) {
						uni.showToast({
							title: '创建成功',
							icon: 'success'
						})
						// 重新加载分组列表
						await this.loadStockGroups()
						// 选中新创建的分组作为目标分组
						if (response.data && response.data.id) {
							this.selectedTargetGroup = this.stockGroups.find(g => g.id === response.data.id)
						}
					} else {
						uni.showToast({
							title: response.message || '创建失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('创建分组失败:', error)
					uni.showToast({
						title: '创建失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			
			// 确认移动到分组
			confirmMoveToGroup() {
				if (!this.selectedTargetGroup) {
					uni.showToast({
						title: '请选择目标分组',
						icon: 'none'
					})
					return
				}
				
				if (this.selectedStockIds.length === 0) {
					uni.showToast({
						title: '请选择要移动的股票',
						icon: 'none'
					})
					return
				}
				
				// 调用移动股票的API
				this.moveStocksToGroup(this.selectedTargetGroup.id)
			},
			
			// 移动股票到指定分组
			async moveStocksToGroup(targetGroupId) {
				try {
					uni.showLoading({
						title: '移动中...'
					})
					
					// 调用API来更新股票的分组ID
					const promises = this.selectedStockIds.map(stockId => {
						return updateUserStockGroup(null, null, {
							stockId: stockId,
							groupId: targetGroupId
						})
					})
					
					await Promise.all(promises)
					
					uni.showToast({
						title: '移动成功',
						icon: 'success'
					})
					
					// 关闭弹窗
					this.closeGroupSelectModal()
					
					// 退出多选模式
					this.isMultiSelectMode = false
					this.selectedStockIds = []
					
					// 重新加载当前分组的股票列表
					this.loadStockList()
					
				} catch (error) {
					console.error('移动股票失败:', error)
					uni.showToast({
						title: '移动失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style>
.container {
	width: 100%;
	height: 100vh;
	background-color: #f5f5f5;
}

/* 自定义导航栏 */
.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: #ffffff;
	border-bottom: 1px solid #e5e5e5;
}

.navbar-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 44px;
	padding: 0 15px;
	/* 适配状态栏高度 */
	padding-top: var(--status-bar-height, 20px);
	min-height: calc(44px + var(--status-bar-height, 20px));
}

.navbar-left {
	flex: 0 0 auto;
	display: flex;
	align-items: center;
}

.back-btn {
	width: 40px;
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	width: 24px;
	height: 24px;
}

.navbar-center {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
}

.navbar-title {
	font-size: 18px;
	font-weight: 500;
	color: #333333;
}

.navbar-right {
	flex: 0 0 auto;
	display: flex;
	align-items: center;
	gap: 10px;
}

.navbar-btn {
	width: 24px;
	height: 24px;
}

/* 页面内容 */
.page-content {
	padding-top: calc(44px + var(--status-bar-height, 20px) + 20px);
	min-height: calc(100vh - 44px - var(--status-bar-height, 20px) - 20px);
}

/* 分组标签样式 */
.group-tabs {
	background-color: #ffffff;
	padding: 10px 0;
}

.tabs-scroll {
	width: 100%;
}

.tabs-container {
	display: flex;
	padding: 0 15px;
	white-space: nowrap;
}

.tab-item {
	flex-shrink: 0;
	padding: 8px 16px;
	margin-right: 10px;
	border-radius: 20px;
	background-color: #f5f5f5;
	border: 1px solid #e0e0e0;
	transition: all 0.3s ease;
	cursor: pointer;
}

.tab-item:hover {
	background-color: #e8e8e8;
}

.tab-item.active {
	background-color: #ff3b30;
	border-color: #ff3b30;
	box-shadow: 0 2px 8px rgba(255, 59, 48, 0.3);
}

.tab-text {
	font-size: 14px;
	color: #666666;
	white-space: nowrap;
	font-weight: 400;
	transition: all 0.3s ease;
}

.tab-item.active .tab-text {
	color: #ffffff;
	font-weight: 500;
}

/* 股票列表样式 */
.stock-list {
	flex: 1;
	padding: 15px;
}

.loading-container,
.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
}

.loading-text {
	font-size: 16px;
	color: #666666;
}

.empty-image {
	width: 120px;
	height: 120px;
	margin-bottom: 20px;
}

.empty-text {
	font-size: 16px;
	color: #999999;
}

.stock-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 0;
	border-bottom: 1px solid #f0f0f0;
	background-color: #ffffff;
	margin-bottom: 8px;
	border-radius: 8px;
	padding: 15px;
}

.stock-item:last-child {
	margin-bottom: 0;
}

.stock-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.stock-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	margin-bottom: 4px;
}

.stock-code {
	font-size: 12px;
	color: #999999;
}

.stock-price {
	display: flex;
	flex-direction: row;
	align-items: center;
	gap: 8px;
}

.price {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.change {
	font-size: 12px;
	font-weight: 500;
}

.change.up {
	color: #ff3b30;
}

.change.down {
	color: #34c759;
}

/* 复选框样式 */
.checkbox-container {
	margin-right: 12px;
}

.checkbox {
	width: 20px;
	height: 20px;
	border: 2px solid #ddd;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #fff;
}

.checkbox.checked {
	background-color: #ff3b30;
	border-color: #ff3b30;
}

.checkbox-icon {
	color: #fff;
	font-size: 12px;
	font-weight: bold;
}

/* 底部操作栏样式 */
.bottom-toolbar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	border-top: 1px solid #f0f0f0;
	padding: 12px 16px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	z-index: 1000;
}

.toolbar-left {
	display: flex;
	align-items: center;
	gap: 16px;
}

.selected-count {
	font-size: 14px;
	color: #333;
}

.select-all-btn {
	font-size: 14px;
	color: #ff3b30;
	padding: 4px 8px;
}

.toolbar-right {
	display: flex;
	align-items: center;
}

.add-to-group-btn {
	background-color: #ff3b30;
	color: #fff;
	border: none;
	border-radius: 6px;
	padding: 8px 16px;
	font-size: 14px;
}

.add-to-group-btn:disabled {
	background-color: #ccc;
	color: #999;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 1000;
}

.group-select-modal {
	background-color: white;
	border-radius: 20rpx 20rpx 0 0;
	width: 100%;
	max-height: 80vh;
	overflow: hidden;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 40rpx;
	border-bottom: 1px solid #f0f0f0;
}

.modal-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
}

.modal-close {
	font-size: 40rpx;
	color: #999999;
	padding: 10rpx;
}

.modal-content {
	padding: 40rpx;
	max-height: 60vh;
	overflow-y: auto;
}

.group-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
}

.group-item {
	background-color: #f8f8f8;
	border-radius: 16rpx;
	padding: 30rpx 20rpx;
	text-align: center;
	border: 2rpx solid transparent;
	transition: all 0.3s ease;
}

.group-item.current-group {
	background-color: #fff2f0;
	border-color: #ff4d4f;
}

.group-item:active {
	background-color: #e6f7ff;
	border-color: #1890ff;
}

.group-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
}

.group-item.new-group {
	background-color: #fff;
	border: 2rpx dashed #d9d9d9;
}

.new-group-text {
	font-size: 28rpx;
	color: #ff4d4f;
	font-weight: 500;
}

.modal-footer {
	padding: 30rpx 40rpx;
	border-top: 1px solid #f0f0f0;
}

.confirm-btn {
	width: 100%;
	height: 88rpx;
	background-color: #ff4d4f;
	color: white;
	border: none;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: 500;
}
</style>
