<template>
	<view class="container">
		<!-- 日期范围筛选 -->
		<view class="date-filter-card">
			<view class="date-filter-header">
				<view class="date-range-display" @click="showCalendarFun">
					<text class="date-text">{{ formatDateRange() }}</text>
					<text class="calendar-icon">📅</text>
				</view>
			</view>
			<view class="status-filter">
				<text class="status-filter-label">审批状态</text>
				<picker mode="selector" :range="approveStatusOptions" :range-key="'label'" :value="approveStatusIndex" @change="handleStatusChange">
					<view class="status-picker">
						<text class="status-text">{{ approveStatusOptions[approveStatusIndex].label }}</text>
						<text class="picker-arrow">▼</text>
					</view>
				</picker>
			</view>
		</view>

		<!-- 添加按钮 -->
		<view class="add-btn-wrapper">
			<view class="add-btn" @click="goToAdd">
				<!-- <text class="add-icon">➕</text> -->
				<text class="add-text">添加</text>
			</view>
		</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">
					<view class="item-header">
						<view class="category-name">{{ item.reimbursementCategoryName || '无' }}</view>
						<view class="purchase-time">{{ utils.formatTime(item.purchaseTime) }}</view>
					</view>
					<view class="item-details">
						<!-- <view class="detail-item">
							<text class="detail-label">单价:</text>
							<text class="detail-value">¥{{ item.unitPrice || 0 }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">数量:</text>
							<text class="detail-value">{{ item.quantity || 0 }}</text>
						</view> -->
						<view class="detail-item">
							<text class="detail-label">总金额:</text>
							<text class="detail-value">¥{{ item.amount || 0 }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">创建人:</text>
							<text class="detail-value">{{ item.createUser || '无' }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">备注说明:</text>
							<text class="detail-value">¥{{ item.memo || 0 }}</text>
						</view>
					</view>
					<view class="item-footer">
						<view class="status-badge" :class="item.approveStatus=='已审批'?'approved':item.approveStatus=='待审批'?'pending':item.approveStatus=='未通过'?'rejected':'unapproved'">
							{{ item.approveStatus?item.approveStatus=='未审批'?'未提交':item.approveStatus :'未提交' }}
						</view>
						<view class="action-buttons">
							<view class="action-btn view-btn" @click.stop="handleView(item)">
							
								<text class="btn-text">查看</text>
							</view>
							<view v-if="item.approveStatus === '未审批' || item.approveStatus === '已退回'" class="action-btn edit-btn" @click.stop="handleEdit(item)">
							
								<text class="btn-text">编辑</text>
							</view>
							<view v-if="item.approveStatus === '未审批'" class="action-btn delete-btn" @click.stop="handleDelete(item)">
							
								<text class="btn-text">删除</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-if="!loading && dataList.length === 0" class="empty-state">
					<view class="empty-icon">🛒</view>
					<view>暂无购买记录</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 purchaseApi from '@/apis/modules/purchase.js'
	import uniCalendar from '@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue'

	export default {
		components: {
			uniCalendar
		},
		data() {
			// 初始化日期范围（本月1号到今天）
			const now = new Date()
			const year = now.getFullYear()
			const month = now.getMonth()
			const firstDay = new Date(year, month, 1)
			const today = new Date(year, now.getMonth(), now.getDate(), 23, 59, 59, 999)
			
			
			return {
				loading: false,
				dataList: [],
				currentPage: 1,
				pageSize: 10,
				totalCount: 0,
				hasMore: true,
				loadmoreStatus: 'loadmore',
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '正在加载...',
					nomore: '没有更多了'
				},
				userInfo: uni.getStorageSync('userInfo'),
				newuserInfo: uni.getStorageSync('newuserInfo'),
				// 日期范围筛选相关
				showCalendar: false,
				startDate: this.utils.formatTimeday(firstDay),
				endDate: this.utils.formatTimeday(now),
				dateRange: [firstDay.getTime(), today.getTime()],
				// 审批状态筛选
				approveStatusIndex: 0,
				approveStatusOptions: [
					{ label: '全部', value: '' },
					{ label: '未审批', value: '未审批' },
					{ label: '审批中', value: '审批中' },
					{ label: '已审批', value: '已审批' },
					{ label: '未通过', value: '未通过' },
					{ label: '已退回', value: '已退回' }
				]
			}
		},

		onLoad() {
			this.initializePage()
		},

		onShow() {
			// 页面显示时刷新数据（如果从编辑页面返回）
			if (this.dataList.length > 0) {
				this.refreshData()
			}
		},

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

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

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

			// 加载物品购买列表
			async loadPurchaseList() {
				if (this.loading) return

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

					const params = {
						currentPage: this.currentPage,
						pageSize: this.pageSize
					}
					if(this.newuserInfo.gw == '店助' || this.newuserInfo.gw == '店长') {
						 params.createUserStoreId = this.newuserInfo&&this.newuserInfo.mdid?this.newuserInfo.mdid:'暂无'
					} else {
						if (this.userInfo && this.userInfo.userId) {
							params.createUser = this.newuserInfo&&this.newuserInfo.id?this.newuserInfo.id:'暂无'
						}
					}
					

					// 添加购买时间范围参数
					if (this.dateRange && this.dateRange.length === 2) {
						params.purchaseTime = `${this.dateRange[0]},${this.dateRange[1]}`
					}

					// 添加审批状态筛选
					const selectedStatus = this.approveStatusOptions[this.approveStatusIndex]
					if (selectedStatus && selectedStatus.value) {
						params.approveStatus = selectedStatus.value
					}

					const res = await purchaseApi.getPurchaseList(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
				}
			},

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

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

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

			// 跳转到添加页面
			goToAdd() {
				uni.navigateTo({
					url: '/pages/purchase-form/purchase-form'
				})
			},

			// 查看详情
			handleView(item) {
				uni.navigateTo({
					url: `/pages/purchase-detail/purchase-detail?id=${item.id}`
				})
			},

			// 编辑记录（只有未审批状态才能编辑）
			handleEdit(item) {
				if (item.approveStatus === '未审批' || item.approveStatus === '已退回') {
					uni.navigateTo({
						url: `/pages/purchase-form/purchase-form?id=${item.id}`
					})
				} else {
					uni.showToast({
						title: '已审批的记录不能编辑',
						icon: 'none'
					})
				}
			},

			// 删除记录（只有未审批状态才能删除）
			async handleDelete(item) {
				if (item.approveStatus !== '未审批') {
					uni.showToast({
						title: '已审批的记录不能删除',
						icon: 'none'
					})
					return
				}

				// 显示确认对话框
				const confirm = await this.showConfirmDialog('确认删除', '确定要删除这条购买记录吗？删除后无法恢复。')
				
				if (!confirm) {
					return
				}

				try {
					uni.showLoading({
						title: '正在删除...'
					})

					const res = await purchaseApi.deletePurchase(item.id)

					if (res.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						// 刷新列表
						this.refreshData()
					} else {
						throw new Error(res.message || res.msg || '删除失败')
					}
				} catch (error) {
					console.error('删除购买记录失败:', error)
					uni.showToast({
						title: error.message || error.msg || '删除失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 显示确认对话框
			showConfirmDialog(title, content) {
				return new Promise((resolve) => {
					uni.showModal({
						title: title,
						content: content,
						success: (res) => {
							resolve(res.confirm)
						},
						fail: () => {
							resolve(false)
						}
					})
				})
			},

			// 获取状态样式类
			getStatusClass(status) {
				switch (status) {
					case '已审批':
						return 'approved'
					case '待审批':
						return 'pending'
					case '未通过':
						return 'rejected'
					case '未审批':
					default:
						return 'unapproved'
				}
			},

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

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

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


			// 格式化日期范围显示
			formatDateRange() {
				if (!this.startDate || !this.endDate) {
					return '请选择日期'
				}
				
				// 直接格式化日期字符串，避免时区问题
				const formatDisplay = (dateStr) => {
					// dateStr 格式为 YYYY-MM-DD
					const parts = dateStr.split('-')
					if (parts.length === 3) {
						return `${parts[0]}/${parts[1]}/${parts[2]}`
					}
					return dateStr
				}
				
				return `${formatDisplay(this.startDate)} - ${formatDisplay(this.endDate)}`
			},

			// 处理日期确认
			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.refreshData()
				}
			},

			// 处理审批状态筛选变化
			handleStatusChange(e) {
				this.approveStatusIndex = e.detail.value
				this.refreshData()
			}
		}
	}
</script>

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

	.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;
		margin-bottom: 24rpx;
	}

	.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;
	}

	.status-filter {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 24rpx;
		border-top: 2rpx solid #f0f0f0;
	}

	.status-filter-label {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 500;
	}

	.status-picker {
		display: flex;
		align-items: center;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 20rpx 32rpx;
		min-width: 200rpx;
		justify-content: space-between;
	}

	.status-text {
		font-size: 28rpx;
		color: #2e7d32;
	}

	.picker-arrow {
		font-size: 24rpx;
		color: #6a9c6a;
		margin-left: 16rpx;
	}

	.add-btn-wrapper {
		margin-bottom: 40rpx;
		display: flex;
		justify-content: flex-end;
	}

	.add-btn {
		display: flex;
		align-items: center;
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		padding: 24rpx 48rpx;
		border-radius: 32rpx;
		font-size: 28rpx;
		font-weight: 600;
		box-shadow: 0 8rpx 24rpx rgba(67, 233, 123, 0.3);
		transition: all 0.2s ease;
	}

	.add-btn:active {
		transform: scale(0.95);
		box-shadow: 0 4rpx 12rpx rgba(67, 233, 123, 0.4);
	}

	.add-icon {
		font-size: 32rpx;
		margin-right: 12rpx;
	}

	.add-text {
		letter-spacing: 2rpx;
	}

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

	.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(60vh - 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:active {
		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;
	}

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

	.purchase-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-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		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.unapproved {
		background: #fff3e0;
		color: #ef6c00;
		border: 2rpx solid #ffe0b2;
	}

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

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

	.status-badge.rejected {
		background: #ffebee;
		color: #c62828;
		border: 2rpx solid #ffcdd2;
	}

	.action-buttons {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.action-btn {
		display: flex;
		align-items: center;
		padding: 12rpx 24rpx;
		border-radius: 24rpx;
		font-size: 24rpx;
		font-weight: 500;
		transition: all 0.2s ease;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.action-btn:active {
		transform: scale(0.95);
		box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.15);
	}

	.view-btn {
		background: linear-gradient(135deg, #42a5f5 0%, #1e88e5 100%);
		color: #fff;
	}

	.view-btn:active {
		background: linear-gradient(135deg, #1e88e5 0%, #1565c0 100%);
	}

	.edit-btn {
		background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
		color: #fff;
	}

	.edit-btn:active {
		background: linear-gradient(135deg, #43a047 0%, #388e3c 100%);
	}

	.delete-btn {
		background: linear-gradient(135deg, #ef5350 0%, #e53935 100%);
		color: #fff;
	}

	.delete-btn:active {
		background: linear-gradient(135deg, #e53935 0%, #c62828 100%);
	}

	.btn-icon {
		font-size: 24rpx;
		margin-right: 8rpx;
	}

	.btn-text {
		letter-spacing: 1rpx;
	}

	.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;
	}
</style>

