<template>
	<view class="container">
		<!-- 日期范围筛选 -->
		<view class="date-filter-card">
			<view class="date-filter-header">
				<!-- <text class="filter-title">日期筛选</text> -->
				<view class="date-range-display" @click="showCalendarFun">
					<text class="date-text">{{ formatDateRange() }}</text>
					<text class="calendar-icon">📅</text>
				</view>
			</view>
		</view>
		<!-- 搜索栏 -->
		<view class="search-card">
			<u-search v-model="searchKeyword" placeholder="搜索顾客的姓名或者电话" @search="handleSearch" @clear="handleClear"
				@custom="handleSearch" class="search-input">
			</u-search>
		</view>

		<!-- 日历组件 -->
		<uni-calendar
			:range="true"
			ref="calendar"
			@confirm="handleDateConfirm"
			:insert="false"
		></uni-calendar>

		<!-- 数据列表 -->
		<view class="list-card">
			<view class="list-header">
				<text class="header-text">退卡记录</text>
				<text class="total-count">共 {{ totalCount }} 条</text>
			</view>

			<scroll-view scroll-y class="list-content" @scrolltolower="loadMore">
				<view v-for="(item, index) in dataList" :key="index" class="list-item" @click="goToDetail(item)">
					<view class="item-header">
						<view class="member-name">{{ item.hymc || item.hy || '未知会员' }}</view>
						<view class="refund-time">{{ formatTime(item.tksj) }}</view>
					</view>
					<view class="item-details">
						<view class="detail-item">
							<text class="detail-label">退款金额:</text>
							<text class="detail-value">¥{{ item.tkje || 0 }}</text>
						</view>
						<view class="detail-item" v-if="item.actualRefundAmount">
							<text class="detail-label">实际退款金额:</text>
							<text class="detail-value">¥{{ item.actualRefundAmount || 0 }}</text>
						</view>
					</view>
					<view class="item-status">
						<view class="status-badge" :class="item.isEffective !='1'?'pending':'normal'">
							<!-- :class="getStatusClass(item)" -->
							{{ getStatusText(item) }}
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!loading && dataList.length === 0" class="empty-state">
					<view class="empty-icon">💳</view>
					<view>暂无退卡数据</view>
					<view v-if="searchKeyword" class="empty-search-tip">未找到匹配"{{ searchKeyword }}"的记录</view>
				</view>

				<!-- 加载状态 -->
				<view v-if="loading && dataList.length === 0" class="loading">正在加载数据...</view>

				<!-- 加载更多 -->
				<u-loadmore v-if="dataList.length > 0" :status="loadmoreStatus" :load-text="loadText"></u-loadmore>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import refundApi from '@/apis/modules/refund.js'
	import uniCalendar from '@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue'

	export default {
		components: {
			uniCalendar
		},
		data() {
			return {
				loading: false,
				searchKeyword: '',
				dataList: [],
				currentPage: 1,
				pageSize: 10,
				totalCount: 0,
				hasMore: true,
				searchTimer: null,
				loadmoreStatus: 'loadmore',
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '正在加载...',
					nomore: '没有更多了'
				},
				userInfo: uni.getStorageSync('userInfo'),
				// 日期范围筛选相关
				showCalendar: false,
				startDate: this.getTodayString(),
				endDate: this.getTodayString(),
				dateRange: this.getTodayRange()
			}
		},

		onLoad() {
			this.initializePage()
		},
		onShow() {
			// 页面显示时刷新数据
			// this.refreshData()
		},

		onUnload() {
			// 页面卸载时清理定时器
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
				this.searchTimer = null
			}
		},

		methods: {
			showCalendarFun(){
				this.$refs.calendar.open();
			},
			// 初始化页面
			async initializePage() {
				try {
					// 检查登录状态
					await this.checkLoginStatus()

					// 加载第一页数据
					await this.loadRefundList()
				} catch (error) {
					console.error('页面初始化失败:', error)
					this.showErrorState('页面初始化失败，请刷新重试')
				}
			},

			// 检查登录状态
			async checkLoginStatus() {
				const token = uni.getStorageSync('token')
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return
				}
			},

			// 加载退卡列表
			async loadRefundList() {
				if (this.loading) return

				try {
					this.loading = true
					this.showLoadingState()

					const params = {
						currentPage: this.currentPage,
						pageSize: this.pageSize
					}

					// 添加用户ID参数
					if (this.userInfo && this.userInfo.userId) {
						params.czry = this.userInfo.userId
					}

					// 添加搜索关键字
					if (this.searchKeyword) {
						// params.keyword = this.searchKeyword
						params.hy =  await this.utils.gethy(this.searchKeyword)
					}

					// 添加日期范围参数
					if (this.dateRange && this.dateRange.length === 2) {
						params.tksj = `${this.dateRange[0]},${this.dateRange[1]}`
					}

					const res = await this.API.getRefundList(params)

					if (res.code === 200) {
						const data = res.data
						this.totalCount = data.pagination?.total || 0
						const list = data.list || []

						if (this.currentPage === 1) {
							// 第一页，清空列表
							this.dataList = list
						} else {
							// 加载更多，追加到列表
							this.dataList = [...this.dataList, ...list]
						}

						// 判断是否还有更多数据
						this.hasMore = list.length === this.pageSize

						// 更新加载状态
						if (this.hasMore) {
							this.loadmoreStatus = 'loadmore'
						} else {
							this.loadmoreStatus = 'nomore'
						}
					} else {
						throw new Error(res.message || '获取数据失败')
					}

				} catch (error) {
					console.error('加载退卡列表失败:', error)
					if (this.currentPage === 1) {
						this.showErrorState('加载数据失败，请重试')
					} else {
						this.showMessage('加载更多数据失败', 'error')
					}
				} finally {
					this.loading = false
				}
			},

			// 搜索
			handleSearch() {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer)
				}

				// 设置新的定时器，延迟500ms执行搜索
				this.searchTimer = setTimeout(() => {
					this.resetAndSearch()
				}, 500)
			},

			// 清空搜索
			handleClear() {
				this.searchKeyword = ''
				this.resetAndSearch()
			},

			// 重置并搜索
			async resetAndSearch() {
				this.currentPage = 1
				this.hasMore = true
				this.loadmoreStatus = 'loadmore'
				this.dataList = []
				await this.loadRefundList()
			},

			// 刷新数据
			refreshData() {
				this.currentPage = 1
				this.hasMore = true
				this.loadmoreStatus = 'loadmore'
				this.dataList = []
				this.loadRefundList()
			},

			// 加载更多
			async loadMore() {
				if (this.loading || !this.hasMore || this.loadmoreStatus === 'nomore') return

				this.loadmoreStatus = 'loading'
				this.currentPage++
				await this.loadRefundList()
			},

			// 跳转到详情页
			goToDetail(item) {
				console.log('退卡详情:', item)
				uni.navigateTo({
					url: `/pages/refund-detail/refund-detail?id=${item.id}`
				})
			},

			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '无'
				const date = new Date(timestamp)
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				})
			},

			// 获取状态样式类
			getStatusClass(item) {
				// 根据业务逻辑判断状态
				if (item.tkzt === '已审核') {
					return 'approved' // 已审核
				} else if (item.tkzt === '待审核') {
					return 'pending' // 待审核
				} else {
					return 'normal' // 正常
				}
			},

			// 获取状态文本
			getStatusText(item) {
				if (item.isEffective == '1') {
					return '正常'
				} else {
					return '作废'
				}
			},

			// 显示加载状态
			showLoadingState() {
				// 加载状态由模板控制
			},

			// 显示错误状态
			showErrorState(message) {
				uni.showToast({
					title: message,
					icon: 'none'
				})
			},

			// 显示消息提示
			showMessage(message, type = 'info') {
				uni.showToast({
					title: message,
					icon: type === 'error' ? 'error' : 'none'
				})
			},

			// 获取今天的日期字符串
			getTodayString() {
				const today = new Date()
				return today.toISOString().split('T')[0]
			},

			// 获取今天的日期范围
			getTodayRange() {
				const today = new Date()
				const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate())
				const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999)
				return [startOfDay.getTime(), endOfDay.getTime()]
			},

			// 格式化日期范围显示
			formatDateRange() {
				if (!this.startDate || !this.endDate) {
					return '请选择日期'
				}
				
				const startDate = new Date(this.startDate)
				const endDate = new Date(this.endDate)
				
				return `${startDate.toLocaleDateString('zh-CN')} - ${endDate.toLocaleDateString('zh-CN')}`
			},

			// 处理日期确认
			handleDateConfirm(e) {
				console.log('日期选择结果:', e)
				
				// uni-calendar组件返回的是包含start和end的对象
				if (e && e.range && e.range.data) {
					// 更新dateRange用于API调用（时间戳格式）
					const startTime = new Date(e.range.data[0]).getTime()
					const endTime = new Date(e.range.data[e.range.data.length-1]).getTime()
					this.dateRange = [startTime, endTime]
					
					// 更新startDate和endDate用于显示
					this.startDate = e.range.data[0]
					this.endDate = e.range.data[e.range.data.length-1]
					
					// 日期变化时重新加载数据
					this.resetAndSearch()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 40rpx 40rpx;
		box-sizing: border-box;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40rpx;
	}

	.back-btn {
		background: #fff;
		border: none;
		border-radius: 24rpx;
		padding: 16rpx 24rpx;
		color: #388e3c;
		font-size: 28rpx;
		box-shadow: 0 4rpx 16rpx rgba(76, 175, 80, 0.15);
		transition: all 0.2s ease;
	}

	.header-title {
		text-align: center;
		color: #388e3c;
		font-size: 36rpx;
		font-weight: bold;
		letter-spacing: 4rpx;
		flex: 1;
	}

	.search-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		padding: 40rpx;
		margin-bottom: 40rpx;
	}

	.date-filter-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		padding: 40rpx;
		margin-bottom: 40rpx;
	}

	.date-filter-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.filter-title {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
	}

	.date-range-display {
		display: flex;
		align-items: center;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 24rpx 32rpx;
		cursor: pointer;
		transition: all 0.2s ease;
		justify-content: space-between;
		width: 100%;
		box-sizing: border-box;
	}

	.date-range-display:active {
		border-color: #43a047;
		background: #fff;
		transform: scale(0.98);
	}

	.date-text {
		font-size: 28rpx;
		color: #2e7d32;
		flex: 1;
	}

	.calendar-icon {
		font-size: 32rpx;
		margin-left: 16rpx;
	}

	.list-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		overflow: hidden;
		max-height: 70vh;
	}

	.list-header {
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		padding: 32rpx 40rpx;
		color: #fff;
		font-weight: 600;
		letter-spacing: 2rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.header-text {
		font-size: 32rpx;
	}

	.total-count {
		font-size: 28rpx;
		opacity: 0.9;
	}

	.list-content {
		max-height: calc(70vh - 120rpx);
		overflow-y: auto;
	}

	.list-item {
		padding: 32rpx 40rpx;
		border-bottom: 2rpx solid #f0f0f0;
		cursor: pointer;
		transition: all 0.2s ease;
		position: relative;
	}

	.list-item:hover {
		background: #f8fff8;
		transform: translateX(8rpx);
	}

	.list-item:last-child {
		border-bottom: none;
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.member-name {
		font-weight: 600;
		color: #2e7d32;
		font-size: 32rpx;
	}

	.refund-time {
		font-size: 24rpx;
		color: #6a9c6a;
	}

	.item-details {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 16rpx;
		margin-bottom: 16rpx;
	}

	.detail-item {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #555;
	}

	.detail-label {
		color: #6a9c6a;
		margin-right: 12rpx;
		font-size: 24rpx;
	}

	.detail-value {
		color: #2e7d32;
		font-weight: 500;
	}

	.item-status {
		display: flex;
		justify-content: flex-end;
		margin-top: 16rpx;
	}

	.status-badge {
		display: inline-block;
		padding: 8rpx 24rpx;
		border-radius: 40rpx;
		font-size: 24rpx;
		font-weight: 500;
		text-align: center;
	}

	.status-badge.normal {
		background: #e8f5e9;
		color: #2e7d32;
		border: 2rpx solid #c8e6c9;
	}

	.status-badge.pending {
		background: #fff3e0;
		color: #f57c00;
		border: 2rpx solid #ffcc02;
	}

	.status-badge.approved {
		background: #e3f2fd;
		color: #1976d2;
		border: 2rpx solid #bbdefb;
	}

	.loading {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #6a9c6a;
		font-size: 28rpx;
	}

	.empty-state {
		text-align: center;
		padding: 120rpx 40rpx;
		color: #6a9c6a;
	}

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 32rpx;
		opacity: 0.5;
	}

	.empty-search-tip {
		margin-top: 16rpx;
		font-size: 28rpx;
		opacity: 0.7;
	}

	/* #ifdef H5 */
	// 自定义搜索框样式
	:deep(.u-search) {
		background: #f9fff9;
		border-radius: 24rpx;
	}

	:deep(.u-search__content) {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 24rpx 32rpx;
		font-size: 28rpx;
		color: #2e7d32;
	}

	:deep(.u-search__content--focus) {
		border-color: #43a047;
		background: #fff;
	}

	:deep(.u-search__content__input) {
		color: #2e7d32;
	}

	:deep(.u-search__content__input::placeholder) {
		color: #6a9c6a;
	}

	/* #endif */
</style>
