<template>
	<view class="container">
		<!-- 状态栏占位 -->
		<scroll-view class="content" scroll-y>
			<!-- 积分卡片 -->
			<view class="points-card">
				<view class="card-decoration">
					<image class="w194 h166" src="@/static/image/img_bg_card.png" mode=""></image>
				</view>
				<view class="card-content">
					<view class="card-label">积分账户</view>
					<view class="card-balance">{{ pointsData.creditNum || '0.00' }}</view>
					<view class="x-bc">
						<view class="card-pending">支出待入账: {{ pointsData.waitCreditNum || '0.00' }}</view>
						<view class="withdraw-btn x-c" @click="goWithdraw">去提现</view>
					</view>
					
				</view>
			</view>
			
			<!-- 筛选和汇总区域 -->
			<view class="filter-summary-section">
				<view class="filter-row">
					<picker mode="date" fields="month" :value="tempDate" @change="onDateChange">
						<view class="date-picker" @click="showDatePicker = true">
							<text>{{ selectedDate }}</text>
							<text class="arrow-down">▾</text>
						</view>
					</picker>
					<view class="total-amount">
						{{incomeType === 2?"收入":"支出"}}{{ summaryData.totalIncome || '0.00' }}
					</view>
				</view>
				<view class="x-bc">
					<view class="type-buttons">
						<view class="type-btn" :class="{ active: incomeType === 2 }" @click="switchType(2)">
							收入
						</view>
						<view class="type-btn" :class="{ active: incomeType === 1 }" @click="switchType(1)">
							支出
						</view>
					</view>
					<view class="type-filter" @click="openTypePicker">
						<text>{{ selectedType || '全部类型' }}</text>
						<text class="arrow-down">▾</text>
					</view>
				</view>
				<!-- 交易列表 -->
				<view class="transaction-list">
					<view class="transaction-item" v-for="(item, index) in transactionList" :key="index">
						<view class="item-left">
							<view class="item-title">{{ item.doctorName }}</view>
							<view class="item-time">{{ item.createAt }}</view>
						</view>
						<view class="item-amount" :class="item.type">
							{{ item.changeType === 2 ? '+' : '-' }}{{ item.changeMoney }}
						</view>
					</view>
					<view class="no-more" v-if="!hasMore && transactionList.length > 0">没有更多了~</view>
				</view>
			</view>
			
		
		</scroll-view>
		<!-- 任务类型筛选弹窗 -->
		<view class="type-picker-popup" v-if="showTypePicker" @click="closeTypePicker">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<view class="picker-title">任务类型</view>
					<view class="picker-close" @click="closeTypePicker">
						<image class="w44 h44" src="@/static/image/icon_cross.png" mode=""></image>
					</view>
				</view>
				<view class="picker-body">
					<view class="type-grid">
						<view class="type-btn-item" 
							:class="{ active: tempType === item.value }"
							v-for="(item, index) in typeOptions" 
							:key="index"
							@click="tempType = item.value">
							{{ item.label }}
						</view>
					</view>
				</view>
				<view class="picker-footer">
					<view class="footer-btn btn-reset" @click="resetType">重置</view>
					<view class="footer-btn btn-confirm" @click="confirmType">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getPointsList, getPointsInfo, getPointsTypeOptions, getPointsStatistics } from '@/api/points'
export default {
	data() {
		return {
			statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
			showDatePicker: false,
			showTypePicker: false,
			selectedDate: '2025-12',
			tempDate: '2025-12',
			incomeType: 2, // income: 收入, expense: 支出
			selectedType: '全部类型',
			tempType: '',
			typeOptions: [
			],
			pointsData: {
			},
			summaryData: {
				totalIncome: '0.00'
			},
			transactionList: [],
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			loading: false
		}
	},
	onLoad() {
		this.loadTypeOptions()
		this.initCurrentMonth()
	},
	onShow() {
		this.loadData()
	},
	onReachBottom() {
		this.loadMore()
	},
	methods: {
		  // 核心：初始化当前月份
		    initCurrentMonth() {
		      const now = new Date();
		      const year = now.getFullYear();
		      const month = (now.getMonth() + 1).toString().padStart(2, "0");
		      this.selectedDate = `${year}-${month}`;
		      this.tempDate = `${year}-${month}`;
		    },
		goBack() {
			uni.navigateBack()
		},
		goWithdraw() {
			uni.navigateTo({
				url: '/pages_user/withdraw'
			})
		},
		onDateChange(e) {
			this.selectedDate = e.detail.value
			this.pageNum = 1
			this.hasMore = true
			this.loadList()
		},
		closeTypePicker() {
			this.showTypePicker = false
		},
		resetType() {
			this.tempType = ''
		},
		confirmType() {
			// 根据 tempType 找到对应的选项
			const selectedOption = this.typeOptions.find(item => item.value === this.tempType)
			this.selectedType = selectedOption ? selectedOption.label : '全部类型'
			if (!selectedOption) this.tempType = ''
			this.showTypePicker = false
			this.pageNum = 1
			this.hasMore = true
			this.loadList()
		},
		switchType(type) {
			this.incomeType = type
			this.pageNum = 1
			this.hasMore = true
			this.loadList()
		},
		openTypePicker() {
			// 根据 selectedType 找到对应的 value 设置给 tempType
			const selectedOption = this.typeOptions.find(item => item.label === this.selectedType)
			this.tempType = selectedOption ? selectedOption.value : ''
			this.showTypePicker = true
		},
		async loadData() {
			try {
				this.pageNum = 1
				this.hasMore = true
				uni.showLoading({ title: '加载中...' })
				
				const [infoRes] = await Promise.all([
					getPointsInfo({}),
					this.loadList(true) // 不显示loading，因为外层已经显示了
				])
				uni.hideLoading()
				
				if (infoRes.code == 200 && infoRes.data) {
					this.pointsData = infoRes.data
				}
			} catch (e) {
				uni.hideLoading()
				console.error('加载数据失败', e)
			}
		},
		async loadList(silent = false) {
			try {
				if (!silent) {
					uni.showLoading({ title: '加载中...' })
				}
				
				// 获取选中的类型值
				const businessType = this.selectedType === '全部类型' ? '' : 
					(this.typeOptions.find(item => item.label === this.selectedType)?.value || '')
				
				const listRes = await getPointsList({
					selectTime:this.selectedDate,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					changeType: this.incomeType,
					...(businessType && { businessType })
				})
				
				if (!silent) {
					uni.hideLoading()
				}
				
				if (listRes.code == 200 && listRes.data) {
					if (this.pageNum == 1) {
						// 第一页，直接替换
						this.transactionList = listRes.data.doctorBalanceLogs || []
					} else {
						// 后续页，追加数据
						this.transactionList = [...this.transactionList, ...(listRes.data.doctorBalanceLogs || [])]
					}
					this.summaryData = {
						totalIncome: (listRes.data.total || 0).toFixed(2)
					}
					// 判断是否还有更多数据
					if (!listRes.data.doctorBalanceLogs || listRes.data.doctorBalanceLogs.length < this.pageSize) {
						this.hasMore = false
					}
				} else {
					if (this.pageNum == 1) {
						this.transactionList = []
					}
					this.hasMore = false
				}
			} catch (e) {
				if (!silent) {
					uni.hideLoading()
				}
				console.error('加载列表失败', e)
				if (this.pageNum === 1) {
					this.transactionList = []
				}
				this.hasMore = false
			}
		},
		async loadTypeOptions() {
			// 加载积分类型选项
			try {
				const res = await getPointsTypeOptions({dictType:"credit_flow_type"})
				if (res.code === 200 && res.data && Array.isArray(res.data)) {
					// 更新类型选项列表
					this.typeOptions = [
						{ label: '全部类型', value: '' },
						...res.data.map(item => ({
							label: item.dictLabel,
							value: item.dictValue
						}))
					]
				}
			} catch (e) {
				console.error('加载积分类型选项失败', e)
			}
		},
		async loadMore() {
			if (!this.hasMore || this.loading) return
			
			try {
				this.loading = true
				this.pageNum = this.pageNum + 1
				await this.loadList(true) // 静默加载，不显示loading
			} catch (e) {
				console.error('加载更多数据失败', e)
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.status-bar {
	width: 100%;
	background: #fff;
}

.header {
	position: relative;
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.back-btn {
		position: absolute;
		left: 24rpx;
		width: 40rpx;
		height: 40rpx;
		
		image {
			width: 100%;
			height: 100%;
		}
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.header-right {
		position: absolute;
		right: 24rpx;
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.more-icon {
			font-size: 32rpx;
			color: #333;
		}
	}
}

.content {
	flex: 1;
	background: #f5f5f5;
}

.points-card {
	position: relative;
	margin: 24rpx;
	height: 280rpx;
	background: linear-gradient( 81deg, #FFDF87 0%, #FFB042 100%);
	border-radius: 24rpx;
	padding: 48rpx 40rpx;
	overflow: hidden;
	.card-decoration {
		position: absolute;
		top: 0;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.star-icon {
			font-size: 60rpx;
		}
	}
	
	.card-content {
		position: relative;
		z-index: 1;
		height: 100%;
		    display: flex;
		    flex-direction: column;
		    justify-content: space-around;
		.card-label {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #583504;
			
		}
		
		.card-balance {
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 48rpx;
			color: #583504;
			
		}
		
		.card-pending {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #583504;
			// margin-bottom: 32rpx;
		}
		
		.withdraw-btn {
			width: 164rpx;
			height: 64rpx;
			background: rgba(255,255,255,0.4);
			border-radius: 34rpx 34rpx 34rpx 34rpx;
			border: 2rpx solid #FFFFFF;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #583504;
		}
	}
}

.filter-summary-section {
	background: #fff;
	margin: 0 24rpx;
	border-radius: 16rpx;
	padding: 40rpx 32rpx;
	.type-buttons {
		display: flex;
		gap: 16rpx;
		
		.type-btn {
			padding: 12rpx 32rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			background: #F7F8FA;
			color:#666666;
			
			&.active {
				background: rgba(250,171,12,0.2);
				color:#F08112;
			}
		}
	}
	.filter-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 24rpx;
		
		.date-picker {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 28rpx;
			color: #333;
			
			.arrow-down {
				font-size: 20rpx;
				color: #999;
			}
		}
		
		
		
		.total-amount {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}
	}
	
	.type-filter {
		display: flex;
		align-items: center;
		gap: 8rpx;
		font-size: 28rpx;
		color: #333;
		
		.arrow-down {
			font-size: 20rpx;
			color: #999;
		}
	}
}

.transaction-list {
	background: #fff;
	// margin: 0 24rpx 24rpx;
	border-radius: 16rpx;
	padding: 24rpx;
	
	.no-more {
		text-align: center;
		padding: 48rpx 0;
		font-size: 24rpx;
		color: #999;
	}
}

.transaction-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	
	&:last-child {
		border-bottom: none;
	}
	
	.item-left {
		flex: 1;
		
		.item-title {
			font-size: 30rpx;
			color: #333;
			margin-bottom: 16rpx;
		}
		
		.item-time {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.item-amount {
		font-size: 32rpx;
		font-weight: 500;
		
		&.income {
			color: #333333;
		}
		
		&.expense {
			color: #333;
		}
	}
}

.date-picker-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: flex-end;
}

.type-picker-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: flex-end;
}

.picker-content {
	width: 100%;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	max-height: 80vh;
	display: flex;
	flex-direction: column;
	
	.picker-header {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 32rpx 24rpx;
		position: relative;
		
		.picker-cancel {
			font-size: 30rpx;
			color: #666;
		}
		
		.picker-title {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
		}
		
		.picker-close {
			position: absolute;
			right: 24rpx;
			top: 50%;
			transform: translateY(-50%);
			font-size: 48rpx;
			color: #999;
			width: 48rpx;
			height: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			line-height: 1;
		}
		
		.picker-confirm {
			font-size: 30rpx;
			color: #FF9800;
		}
	}
	
	.picker-body {
		flex: 1;
		padding: 32rpx 24rpx;
		overflow-y: auto;
		
		.type-grid {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			
			.type-btn-item {
				padding: 14rpx 0;
				border-radius:70rpx;
				font-size: 28rpx;
				color: #333;
				background: #F7F8FA;
				border: 2rpx solid transparent;
				width: calc((100% - 60rpx)/3);
				text-align: center;
				
				&.active {
					background: rgba(56,139,255,0.15);
					border-color: #388BFF;
					color: #388BFF;
				}
			}
		}
		
		.picker-item {
			padding: 24rpx 0;
			font-size: 30rpx;
			color: #333;
			border-bottom: 1rpx solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			&.active {
				color: #FF9800;
				font-weight: bold;
			}
		}
	}
	
	.picker-footer {
		display: flex;
		gap: 24rpx;
		padding: 24rpx;
		margin-bottom: 40rpx;
		.footer-btn {
			flex: 1;
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 200rpx 200rpx 200rpx 200rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #FFFFFF;
			
			&.btn-reset {
				background: #fff;
				border: 2rpx solid #388BFF;
				color: #388BFF;
			}
			
			&.btn-confirm {
				background: #388BFF;
				color: #fff;
			}
		}
	}
}
</style>
