<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> -->

		<!-- 日历组件 -->
		<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="applicant-name">{{ item.applicationUserName || '无' }}</view>
						<view class="application-time">{{ utils.formatTime(item.applicationTime) }}</view>
					</view>
					<view class="item-details">
						<view class="detail-item">
							<text class="detail-label">门店:</text>
							<text class="detail-value">{{ getStoreName(item.applicationStoreId) || '无' }}</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">总金额:</text>
							<text class="detail-value amount">¥{{ item.amount || 0 }}</text>
						</view>
					</view>
					<view class="item-footer">
						<view class="status-badge" :class="item.approveStatus=='待审批'?'pending':item.approveStatus=='审批中'?'pending':item.approveStatus=='已通过'?'approved':item.approveStatus=='未通过'?'rejected':item.approveStatus=='已退回'?'rejected':'unapproved'">
							{{ item.approveStatus || '待审批' }}
						</view>
						<view class="action-buttons">
							<view v-if="item.approveStatus === '待审批' || item.approveStatus === '审批中'" class="action-btn audit-btn" @click.stop="handleAudit(item)">
								<text class="btn-text">审核</text>
							</view>
							<view v-else class="action-btn view-btn" @click.stop="handleView(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 api from '@/apis/index.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'),
				storeOptions: [],
				// 日期范围筛选相关
				showCalendar: false,
				startDate: this.utils.formatTimeday(firstDay),
				endDate: this.utils.formatTimeday(now),
				dateRange: [firstDay.getTime(), today.getTime()],
				// 审批状态筛选
				approveStatusIndex: 0, // 默认选择"全部"（索引0）
				approveStatusOptions: [
					{ label: '全部', value: '' },
					{ label: '待审批', value: '待审批' },
					{ label: '审批中', value: '审批中' },
					{ label: '已通过', value: '已通过' },
					{ label: '未通过', value: '未通过' },
					{ label: '已退回', value: '已退回' }
				]
			}
		},

		onLoad() {
			this.loadStoreOptions()
			this.loadReimbursementList()
		},

		onShow() {
			// 从详情页返回时刷新列表
			this.refreshData()
		},

		methods: {
			// 加载门店列表
			async loadStoreOptions() {
				try {
					const res = await api.getStoreList({
						currentPage: 1,
						pageSize: 1000
					})
					if (res.code === 200 && res.data && res.data.list) {
						this.storeOptions = res.data.list
					} else {
						this.storeOptions = []
					}
				} catch (error) {
					console.error('加载门店列表失败:', error)
					this.storeOptions = []
				}
			},

			// 获取门店名称
			getStoreName(storeId) {
				if (!storeId) return '无'
				const store = this.storeOptions.find(item => item.id === storeId)
				return store ? store.dm : '无'
			},

			// 显示日历
			showCalendarFun() {
				this.$refs.calendar.open()
			},

			// 日期确认
			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.currentPage = 1
					this.loadReimbursementList()
				}
			},

			// 格式化日期范围显示
			formatDateRange() {
				if (!this.startDate || !this.endDate) {
					return '请选择日期'
				}
				
				// 处理日期字符串，确保正确解析
				const startDate = new Date(this.startDate + 'T00:00:00')
				const endDate = new Date(this.endDate + 'T00:00:00')
				
				const formatDate = (date) => {
					const year = date.getFullYear()
					const month = String(date.getMonth() + 1).padStart(2, '0')
					const day = String(date.getDate()).padStart(2, '0')
					return `${year}/${month}/${day}`
				}
				
				return `${formatDate(startDate)} - ${formatDate(endDate)}`
			},

			// 审批状态变化
			handleStatusChange(e) {
				this.approveStatusIndex = e.detail.value
				this.currentPage = 1
				this.loadReimbursementList()
			},

			// 加载报销申请列表（我的待办）
			async loadReimbursementList() {
				if (this.loading) return

				try {
					this.loading = true
					this.loadmoreStatus = 'loading'

					// 构建查询参数（我的待办接口只支持门店筛选和分页参数）
					const params = {
						currentPage: this.currentPage,
						pageSize: this.pageSize,
						sidx: 'applicationTime',
						sort: 'desc'
					}

					// 我的待办接口支持门店筛选（如果需要的话，可以添加门店选择功能）
					// 注意：我的待办接口不支持审批状态和日期范围筛选
					// 如果需要这些筛选，需要在前端进行过滤，或者使用其他接口

					// 使用我的待办接口
					const res = await api.getMyPendingList(params)

					if (res.code === 200 && res.data) {
						let list = res.data.list || []
						const pagination = res.data.pagination || {}

						// 前端过滤：根据审批状态筛选
						const selectedStatus = this.approveStatusOptions[this.approveStatusIndex]
						if (selectedStatus && selectedStatus.value) {
							list = list.filter(item => item.approveStatus === selectedStatus.value)
						}

						// 前端过滤：根据日期范围筛选
						if (this.startDate && this.endDate) {
							const startTimestamp = new Date(this.startDate + 'T00:00:00').getTime()
							const endTimestamp = new Date(this.endDate + 'T23:59:59').getTime()
							list = list.filter(item => {
								if (!item.applicationTime) return false
								const itemTime = new Date(item.applicationTime).getTime()
								return itemTime >= startTimestamp && itemTime <= endTimestamp
							})
						}

						if (this.currentPage === 1) {
							this.dataList = list
						} else {
							// 加载更多时，需要去重（避免重复数据）
							const existingIds = new Set(this.dataList.map(item => item.id))
							const newItems = list.filter(item => !existingIds.has(item.id))
							this.dataList = [...this.dataList, ...newItems]
						}

						// 注意：由于前端过滤，总数可能不准确
						// 如果第一页且有筛选条件，使用过滤后的数量；否则使用后端返回的总数
						if (this.currentPage === 1) {
							const hasFilter = (selectedStatus && selectedStatus.value) || (this.startDate && this.endDate)
							if (hasFilter) {
								// 有筛选条件时，总数不准确，使用当前列表长度
								this.totalCount = list.length
							} else {
								// 无筛选条件时，使用后端返回的总数
								this.totalCount = pagination.total || list.length
							}
						}
						
						// 判断是否还有更多数据
						const hasFilter = (selectedStatus && selectedStatus.value) || (this.startDate && this.endDate)
						if (hasFilter) {
							// 有筛选条件时，如果返回的数据少于pageSize，说明没有更多了
							this.hasMore = list.length >= this.pageSize
						} else {
							// 无筛选条件时，使用后端分页信息
							this.hasMore = this.dataList.length < (pagination.total || 0)
						}

						if (!this.hasMore) {
							this.loadmoreStatus = 'nomore'
						} else {
							this.loadmoreStatus = 'loadmore'
						}
					} else {
						uni.showToast({
							title: res.message || '加载失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('加载报销审核列表失败:', error)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

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

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

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

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

			// 审核（跳转到详情页进行审核）
			handleAudit(item) {
				uni.navigateTo({
					url: `/pages/reimbursement-detail/reimbursement-detail?id=${item.id}`
				})
			},
			
			// 获取状态样式类
			getStatusClass(status) {
				switch (status) {
					case '待审批':
						return 'pending'
					case '审批中':
						return 'pending'
					case '已通过':
						return 'approved'
					case '未通过':
						return 'rejected'
					case '已退回':
						return 'rejected'
					default:
						return 'unapproved'
				}
			}
		}
	}
</script>

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

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

	.date-filter-header {
		margin-bottom: 24rpx;
	}

	.date-range-display {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 16rpx;
	}

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

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

	.status-filter {
		display: flex;
		align-items: center;
		gap: 24rpx;
		justify-content: space-between;
	}

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

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

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

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

	.list-card {
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(76, 175, 80, 0.1);
	}

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

	.header-text {
		font-size: 32rpx;
		color: #fff;
		font-weight: 600;
		letter-spacing: 2rpx;
	}

	.total-count {
		font-size: 24rpx;
		color: #fff;
		opacity: 0.9;
	}

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

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

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

	.list-item:active {
		background: #f9fff9;
	}

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

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

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

	.item-details {
		display: flex;
		flex-wrap: wrap;
		gap: 24rpx;
		margin-bottom: 16rpx;
	}

	.detail-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

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

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

	.detail-value.amount {
		color: #f57c00;
		font-weight: 600;
		font-size: 32rpx;
	}

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

	.audit-btn {
		background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
		color: #fff;
	}

	.audit-btn:active {
		background: linear-gradient(135deg, #f57c00 0%, #e65100 100%);
	}

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

