<template>
	<view class="container">
		<!-- 会员信息卡片 -->
		<view class="member-card" v-if="memberName || memberPhone">
			<view class="member-info">
				<text class="member-label">会员姓名:</text>
				<text class="member-value">{{ memberName || '无' }}</text>
			</view>
			<view class="member-info">
				<text class="member-label">会员手机:</text>
				<text class="member-value">{{ memberPhone || '无' }}</text>
			</view>
		</view>

		<!-- Tab 切换 -->
		<view class="tab-container">
			<view class="tab-list">
				<view 
					v-for="(tab, index) in tabList" 
					:key="index"
					class="tab-item"
					:class="{ active: currentTab === index }"
					@click="onTabChange(index)"
				>
					{{ tab.name }}
				</view>
			</view>
		</view>

		<!-- 开单记录 -->
		<view v-if="currentTab === 0" class="list-container">
			<view class="list-header">
				<text class="header-text">开单记录</text>
				<text class="total-count">共 {{ billingTotalCount }} 条</text>
			</view>
			<scroll-view scroll-y class="list-content" @scrolltolower="loadMoreBilling">
				<view v-for="(item, index) in billingList" :key="index" class="list-item" @click.stop="handleBillingClick(item)">
					<view class="item-header">
						<view class="order-no">编号: {{ item.id || '无' }}</view>
						<view class="create-time">{{ formatDateTime(item.kdrq) }}</view>
					</view>
					<view class="item-details">
						<view class="detail-item">
							<text class="detail-label">开单金额:</text>
							<text class="detail-value amount">￥{{ formatMoney(item.zdyj) }}</text>
						</view>
						<view class="detail-item" v-if="item.bz">
							<text class="detail-label">备注:</text>
							<text class="detail-value remarks">{{ item.bz || '无' }}</text>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!billingLoading && billingList.length === 0" class="empty-state">
					<view class="empty-icon">📋</view>
					<view>暂无开单记录</view>
				</view>

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

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

		<!-- 耗卡记录 -->
		<view v-if="currentTab === 1" class="list-container">
			<view class="list-header">
				<text class="header-text">耗卡记录</text>
				<text class="total-count">共 {{ consumeTotalCount }} 条</text>
			</view>
			<scroll-view scroll-y class="list-content" @scrolltolower="loadMoreConsume">
				<view v-for="(item, index) in consumeList" :key="index" class="list-item" @click.stop="handleConsumeClick(item)">
					<view class="item-header">
						<view class="order-no">编号: {{ item.id || item.Id || '无' }}</view>
						<view class="create-time">{{ formatDateTime(item.usageDate || item.UsageDate) }}</view>
					</view>
					<view class="item-details">
						<view class="detail-item">
							<text class="detail-label">门店:</text>
							<text class="detail-value">{{ item.storeName || item.StoreName || '无' }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">消费金额:</text>
							<text class="detail-value amount">￥{{ formatMoney(item.totalAmount || item.TotalAmount) }}</text>
						</view>
						<!-- <view class="detail-item" v-if="item.remarks || item.Remarks">
							<text class="detail-label">备注:</text>
							<text class="detail-value remarks">{{ item.remarks || item.Remarks || '无' }}</text>
						</view> -->
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!consumeLoading && consumeList.length === 0" class="empty-state">
					<view class="empty-icon">💳</view>
					<view>暂无耗卡记录</view>
				</view>

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

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

		<!-- 退卡记录 -->
		<view v-if="currentTab === 2" class="list-container">
			<view class="list-header">
				<text class="header-text">退卡记录</text>
				<text class="total-count">共 {{ refundTotalCount }} 条</text>
			</view>
			<scroll-view scroll-y class="list-content" @scrolltolower="loadMoreRefund">
				<view v-for="(item, index) in refundList" :key="index" class="list-item" @click.stop="handleRefundClick(item)">
					<view class="item-header">
						<view class="order-no">编号: {{ item.id || item.Id || '无' }}</view>
						<view class="create-time">{{ formatDateTime(item.refundDate || item.RefundDate) }}</view>
					</view>
					<view class="item-details">
						<view class="detail-item">
							<text class="detail-label">门店:</text>
							<text class="detail-value">{{ item.storeName || item.StoreName || '无' }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">退卡金额:</text>
							<text class="detail-value amount">￥{{ formatMoney(item.refundAmount || item.RefundAmount) }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">实际退款:</text>
							<text class="detail-value amount">￥{{ formatMoney(item.actualRefundAmount || item.ActualRefundAmount) }}</text>
						</view>
						<view class="detail-item" v-if="item.refundReason || item.RefundReason">
							<text class="detail-label">退卡原因:</text>
							<text class="detail-value remarks">{{ item.refundReason || item.RefundReason || '无' }}</text>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!refundLoading && refundList.length === 0" class="empty-state">
					<view class="empty-icon">🔄</view>
					<view>暂无退卡记录</view>
				</view>

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

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

<script>
	import api from '@/apis/index.js'
	import request from '@/service/request.js'
	import config from '@/common/config.js'

	export default {
		data() {
			return {
				memberId: '',
				memberName: '',
				memberPhone: '',
				
				// Tab 相关
				currentTab: 0,
				tabList: [
					{ name: '开单' },
					{ name: '耗卡' },
					{ name: '退卡' }
				],
				
				// 开单记录
				billingList: [],
				billingCurrentPage: 1,
				billingPageSize: 10,
				billingTotalCount: 0,
				billingLoading: false,
				billingHasMore: true,
				billingLoadmoreStatus: 'loadmore',
				
				// 耗卡记录
				consumeList: [],
				consumeCurrentPage: 1,
				consumePageSize: 10,
				consumeTotalCount: 0,
				consumeLoading: false,
				consumeHasMore: true,
				consumeLoadmoreStatus: 'loadmore',
				
				// 退卡记录
				refundList: [],
				refundCurrentPage: 1,
				refundPageSize: 10,
				refundTotalCount: 0,
				refundLoading: false,
				refundHasMore: true,
				refundLoadmoreStatus: 'loadmore',
				
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '正在加载...',
					nomore: '没有更多了'
				}
			}
		},

		onLoad(options) {
			// 从页面参数获取会员信息
			if (options.memberId) {
				this.memberId = decodeURIComponent(options.memberId)
			}
			if (options.memberName) {
				this.memberName = decodeURIComponent(options.memberName)
			}
			if (options.memberPhone) {
				this.memberPhone = decodeURIComponent(options.memberPhone)
			}
			this.initializePage()
		},

		methods: {
			// 初始化页面
			async initializePage() {
				try {
					// 检查登录状态
					await this.checkLoginStatus()

					// 加载第一个 tab 的数据
					await this.loadBillingList()
				} catch (error) {
					console.error('页面初始化失败:', error)
					uni.showToast({
						title: '页面初始化失败，请刷新重试',
						icon: 'none'
					})
				}
			},

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

			// Tab 切换
			onTabChange(index) {
				this.currentTab = index
				// 切换到对应 tab 时加载数据
				if (index === 0 && this.billingList.length === 0) {
					this.loadBillingList()
				} else if (index === 1 && this.consumeList.length === 0) {
					this.loadConsumeList()
				} else if (index === 2 && this.refundList.length === 0) {
					this.loadRefundList()
				}
			},

			// 加载开单记录列表
			async loadBillingList() {
				if (this.billingLoading || !this.memberId) return

				try {
					this.billingLoading = true

					const params = {
						memberId: this.memberId,
						currentPage: this.billingCurrentPage,
						pageSize: this.billingPageSize
					}

					const res = await request.get(`${config.getApiBaseUrl()}/api/Extend/LqKdKdjlb/GetBillingRecordByMemberId`, params)

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

						if (this.billingCurrentPage === 1) {
							this.billingList = list
						} else {
							this.billingList = [...this.billingList, ...list]
						}

						this.billingHasMore = list.length === this.billingPageSize
						this.billingLoadmoreStatus = this.billingHasMore ? 'loadmore' : 'nomore'
					} else {
						throw new Error(res.msg || '获取数据失败')
					}

				} catch (error) {
					console.error('加载开单记录列表失败:', error)
					if (this.billingCurrentPage === 1) {
						uni.showToast({
							title: '加载数据失败，请重试',
							icon: 'none'
						})
					}
				} finally {
					this.billingLoading = false
				}
			},

			// 加载更多开单记录
			async loadMoreBilling() {
				if (this.billingLoading || !this.billingHasMore || this.billingLoadmoreStatus === 'nomore') return

				this.billingLoadmoreStatus = 'loading'
				this.billingCurrentPage++
				await this.loadBillingList()
			},

			// 加载耗卡记录列表
			async loadConsumeList() {
				if (this.consumeLoading || !this.memberId) return

				try {
					this.consumeLoading = true

					const params = {
						MemberId: this.memberId,
						currentPage: this.consumeCurrentPage,
						pageSize: this.consumePageSize
					}

					const res = await request.get(`${config.getApiBaseUrl()}/api/Extend/LqXhHyhk/GetMemberCardUsageRecord`, params)

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

						if (this.consumeCurrentPage === 1) {
							this.consumeList = list
						} else {
							this.consumeList = [...this.consumeList, ...list]
						}

						this.consumeHasMore = list.length === this.consumePageSize
						this.consumeLoadmoreStatus = this.consumeHasMore ? 'loadmore' : 'nomore'
					} else {
						throw new Error(res.msg || '获取数据失败')
					}

				} catch (error) {
					console.error('加载耗卡记录列表失败:', error)
					if (this.consumeCurrentPage === 1) {
						uni.showToast({
							title: '加载数据失败，请重试',
							icon: 'none'
						})
					}
				} finally {
					this.consumeLoading = false
				}
			},

			// 加载更多耗卡记录
			async loadMoreConsume() {
				if (this.consumeLoading || !this.consumeHasMore || this.consumeLoadmoreStatus === 'nomore') return

				this.consumeLoadmoreStatus = 'loading'
				this.consumeCurrentPage++
				await this.loadConsumeList()
			},

			// 加载退卡记录列表
			async loadRefundList() {
				if (this.refundLoading || !this.memberId) return

				try {
					this.refundLoading = true

					const params = {
						memberId: this.memberId,
						pageIndex: this.refundCurrentPage,
						pageSize: this.refundPageSize
					}

					const res = await request.get(`${config.getApiBaseUrl()}/api/Extend/MemberPortrait/refund-list`, params)

					if (res.code === 200) {
						const data = res.data
						this.refundTotalCount = data.total || data.Total || 0
						const list = data.list || data.List || []

						if (this.refundCurrentPage === 1) {
							this.refundList = list
						} else {
							this.refundList = [...this.refundList, ...list]
						}

						this.refundHasMore = list.length === this.refundPageSize
						this.refundLoadmoreStatus = this.refundHasMore ? 'loadmore' : 'nomore'
					} else {
						throw new Error(res.msg || '获取数据失败')
					}

				} catch (error) {
					console.error('加载退卡记录列表失败:', error)
					if (this.refundCurrentPage === 1) {
						uni.showToast({
							title: '加载数据失败，请重试',
							icon: 'none'
						})
					}
				} finally {
					this.refundLoading = false
				}
			},

			// 加载更多退卡记录
			async loadMoreRefund() {
				if (this.refundLoading || !this.refundHasMore || this.refundLoadmoreStatus === 'nomore') return

				this.refundLoadmoreStatus = 'loading'
				this.refundCurrentPage++
				await this.loadRefundList()
			},

			// 点击开单记录
			handleBillingClick(item) {
				const id = item.id || item.Id
				if (id) {
					uni.navigateTo({
						url: `/pagesA/lx-detail/lx-detail?id=${id}`
					})
				}
			},

			// 点击耗卡记录
			handleConsumeClick(item) {
				const id = item.id || item.Id
				if (id) {
					uni.navigateTo({
						url: `/pages/consume-detail/consume-detail?id=${id}`
					})
				}
			},

			// 点击退卡记录
			handleRefundClick(item) {
				const id = item.id || item.Id
				if (id) {
					uni.navigateTo({
						url: `/pages/refund-detail/refund-detail?id=${id}`
					})
				}
			},

			// 格式化日期时间
			formatDateTime(dateTime) {
				if (!dateTime) return '无'
				try {
					const date = new Date(dateTime)
					if (isNaN(date.getTime())) return '无'
					return this.utils.formatTime(date)
				} catch (error) {
					console.error('格式化日期失败:', error)
					return '无'
				}
			},

			// 格式化金额
			formatMoney(amount) {
				if (!amount && amount !== 0) return '0.00'
				return parseFloat(amount).toFixed(2)
			}
		}
	}
</script>

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

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

	.member-info {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.member-label {
		color: #388e3c;
		font-weight: 600;
		font-size: 28rpx;
		margin-right: 20rpx;
		min-width: 140rpx;
	}

	.member-value {
		color: #2e7d32;
		font-size: 30rpx;
		font-weight: 500;
		flex: 1;
	}

	.tab-container {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		margin-bottom: 40rpx;
		border: 2rpx solid #e8f5e9;
		overflow: hidden;
	}

	.tab-list {
		display: flex;
		background: linear-gradient(120deg, #f8fff8 0%, #f0f8f0 100%);
		border-bottom: 2rpx solid #e8f5e9;
	}

	.tab-item {
		flex: 1;
		padding: 32rpx 20rpx;
		text-align: center;
		font-weight: 600;
		color: #6a9c6a;
		transition: all 0.3s ease;
		position: relative;
		font-size: 28rpx;
	}

	.tab-item.active {
		color: #2e7d32;
		background: #fff;
		border-bottom: 6rpx solid #43e97b;
	}

	.list-container {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 40rpx 0 rgba(76, 175, 80, 0.12);
		border: 2rpx solid #e8f5e9;
		overflow: hidden;
	}

	.list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx 40rpx;
		border-bottom: 2rpx solid #e8f5e9;
		background: linear-gradient(135deg, #f8fdf8 0%, #ffffff 100%);
	}

	.header-text {
		font-size: 32rpx;
		font-weight: 600;
		color: #388e3c;
	}

	.total-count {
		font-size: 26rpx;
		color: #6a9c6a;
	}

	.list-content {
		max-height: calc(100vh - 400rpx);
		padding: 20rpx;
	}

	.list-item {
		background: #f8fdf8;
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		border: 2rpx solid #e8f5e9;
		transition: all 0.2s ease;

		&:active {
			transform: scale(0.98);
			background: #f0f9f0;
		}

		&:last-child {
			margin-bottom: 0;
		}
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #e8f5e9;
	}

	.order-no {
		font-size: 30rpx;
		font-weight: 600;
		color: #388e3c;
	}

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

	.item-details {
		margin-bottom: 20rpx;
	}

	.detail-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 16rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.detail-label {
		color: #388e3c;
		font-weight: 500;
		font-size: 26rpx;
		margin-right: 16rpx;
		min-width: 140rpx;
		white-space: nowrap;
	}

	.detail-value {
		color: #2e7d32;
		font-size: 26rpx;
		flex: 1;
		word-break: break-all;

		&.amount {
			color: #f56c6c;
			font-weight: 600;
		}

		&.remarks {
			color: #666;
		}
	}

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

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

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