<template>
	<view class="page">
		<u-navbar :title="navTitle" :border-bottom="false" :background="bgc" back-icon-color="#000"
			title-color='#000' title-size='36' height='44'></u-navbar>

		<view class="fixed-header">
			<view class="search-box">
				<view class="date-picker-group">
					<view class="date-btn" hover-class="date-btn--press app-tap-hover" hover-stay-time="80" @click="btnonetime">
						<text class="date-text">{{ startDate }}</text>
						<u-icon name="calendar" color="#9CA3AF" size="28" class="date-ico"></u-icon>
					</view>
					<text class="separator">至</text>
					<view class="date-btn" hover-class="date-btn--press app-tap-hover" hover-stay-time="80" @click="btnonetimes">
						<text class="date-text">{{ endDate }}</text>
						<u-icon name="calendar" color="#9CA3AF" size="28" class="date-ico"></u-icon>
					</view>
				</view>
				<view class="search-icon-btn" hover-class="search-icon-btn--press app-tap-hover" hover-stay-time="80"
					@click="onSearch">
					<u-icon v-if="!listLoading" name="search" color="#fff" size="34"></u-icon>
					<u-loading v-else mode="circle" color="#ffffff" size="34"></u-loading>
				</view>
			</view>
			<view class="mini-summary" v-if="hasFetched">
				<text class="mini-summary-txt">共 <text class="em">{{ total }}</text> 条，已加载 <text class="em">{{ dhlist.length }}</text> 条</text>
			</view>
		</view>

		<scroll-view class="list-scroll list_box" scroll-y :show-scrollbar="false" :enable-back-to-top="true"
			:lower-threshold="120" @scrolltolower="handqixing" refresher-enabled
			:refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
			<view class="list-inner">
				<view class="card" v-for="(item, index) in dhlist"
					:key="item.dispatchLogId || item.id || (item.startTime + '-' + index)" hover-class="card--press"
					hover-stay-time="70">
					<view class="card-header">
						<view class="header-left">
							<view class="time-wrap">
								<u-icon name="clock" color="#9CA3AF" size="26"></u-icon>
								<text class="time">{{ item.startTime || '--' }}</text>
							</view>
						</view>
						<view class="status-tag" :class="item.status == 2 ? 'success' : 'processing'">
							{{ item.status == 1 ? '调度中' : '已完成' }}
						</view>
					</view>

					<view class="divider"></view>

					<view class="info-grid">
						<view class="grid-item">
							<text class="label">车牌号</text>
							<text class="value highlight">{{ item.deviceVehicleNum || '--' }}</text>
						</view>
						<view class="grid-item grid-item--end">
							<text class="label">是否有效</text>
							<view class="valid-pill" :class="item.isValid ? 'valid' : 'invalid'">
								{{ item.isValid ? '有效' : '无效' }}
							</view>
						</view>
					</view>
				</view>

				<view v-if="!listLoading && !loadingMore && dhlist.length === 0" class="empty-state">
					<view class="empty-ico">🛵</view>
					<text class="empty-title">暂无调度记录</text>
					<text class="empty-sub">试试调整日期后点击搜索</text>
				</view>

				<view class="footer-text">
					<text v-if="dhlist.length > 0 && loadingMore">加载中…</text>
					<text v-else-if="dhlist.length > 0 && dhlist.length >= total && total > 0">— 已全部加载 · 共 {{ total }} 条 —</text>
					<text v-else-if="dhlist.length > 0 && total > dhlist.length">下拉或上滑加载更多</text>
				</view>
				<view class="scroll-pad"></view>
			</view>
		</scroll-view>

		<u-picker mode="time" v-model="show" :params="datePickerParams" @confirm="confirmone"></u-picker>
		<u-picker mode="time" v-model="shows" :params="datePickerParams" @confirm="confirmones"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgc: {
					backgroundColor: "#fff",
				},
				areaId: '',
				startDate: '',
				endDate: '',
				dhlist: [],
				userId: '',
				datePickerParams: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				show: false,
				shows: false,
				tit: '',
				pageNum: 1,
				total: 0,
				isRefreshing: false,
				listLoading: false,
				loadingMore: false,
				hasFetched: false
			}
		},
		computed: {
			navTitle() {
				const t = this.tit || '调度明细'
				try {
					return decodeURIComponent(t)
				} catch (e) {
					return t
				}
			}
		},
		onLoad(option) {
			this.tit = option.tit || '调度明细'
			this.startDate = this.getCurrentDate().formatted
			this.endDate = this.getCurrentDate().formatted
			this.areaId = option.areaId
			this.userId = option.userId
			this.getlist()
		},
		methods: {
			onSearch() {
				this.pageNum = 1
				this.getlist()
			},
			parseYmd(str) {
				const p = (str || '').split('-').map((n) => parseInt(n, 10))
				if (p.length !== 3 || p.some((x) => !Number.isFinite(x))) return null
				return new Date(p[0], p[1] - 1, p[2])
			},
			handqixing() {
				if (this.listLoading || this.loadingMore || this.isRefreshing) return
				if (this.total > 0 && this.dhlist.length >= this.total) return
				if (this.total === 0 && this.dhlist.length === 0 && this.pageNum <= 1) return
				this.pageNum += 1
				this.getlist(false, true)
			},
			onRefresh() {
				this.isRefreshing = true
				this.pageNum = 1
				this.getlist(true)
			},
			btnonetime() {
				this.show = true
			},
			confirmone(e) {
				this.startDate = this.formatPickerYmd(e)
			},
			btnonetimes() {
				this.shows = true
			},
			confirmones(e) {
				this.endDate = this.formatPickerYmd(e)
			},
			padYM(n) {
				const s = String(n == null ? '' : n)
				return s.length >= 2 ? s : '0' + s
			},
			formatPickerYmd(e) {
				if (!e) return this.getCurrentDate().formatted
				return `${e.year}-${this.padYM(e.month)}-${this.padYM(e.day)}`
			},
			getlist(isRefresh = false, isAppend = false) {
				if (this.areaId === undefined || this.areaId === null || this.areaId === '' ||
					this.userId === undefined || this.userId === null || this.userId === '') {
					uni.showToast({ title: '缺少参数', icon: 'none' })
					if (isRefresh) this.isRefreshing = false
					return
				}
				const a = this.parseYmd(this.startDate)
				const b = this.parseYmd(this.endDate)
				if (a && b && a > b) {
					uni.showToast({ title: '开始日期不能晚于结束日期', icon: 'none' })
					if (isRefresh) this.isRefreshing = false
					if (isAppend) this.pageNum = Math.max(1, this.pageNum - 1)
					return
				}

				const firstPage = this.pageNum === 1 && !isAppend
				if (firstPage) this.listLoading = true
				if (isAppend) this.loadingMore = true

				const range = `${this.startDate},${this.endDate}`
				const qs =
					`areaId=${encodeURIComponent(String(this.areaId))}` +
					`&endDateRange=${encodeURIComponent(range)}` +
					`&userId=${encodeURIComponent(String(this.userId))}` +
					`&pageNum=${this.pageNum}&pageSize=20`

				this.$u.get(`/bst/dispatchLog/list?${qs}`).then((res) => {
					if (res.code == 200) {
						const rows = res.rows || []
						this.total = res.total != null ? res.total : rows.length
						if (isAppend && rows.length === 0) {
							this.pageNum = Math.max(1, this.pageNum - 1)
							if (this.total > this.dhlist.length) {
								this.total = this.dhlist.length
							}
							return
						}
						if (this.pageNum === 1) {
							this.dhlist = rows
						} else {
							this.dhlist = this.dhlist.concat(rows)
						}
						if (this.total > 0 && this.dhlist.length > this.total) {
							this.total = this.dhlist.length
						}
					} else {
						uni.showToast({ title: res.msg || '加载失败', icon: 'none' })
						const onFirstPage = this.pageNum === 1
						if (this.pageNum > 1) this.pageNum = Math.max(1, this.pageNum - 1)
						if (onFirstPage) this.dhlist = []
					}
				}).catch(() => {
					uni.showToast({ title: '网络异常', icon: 'none' })
					if (this.pageNum > 1) this.pageNum = Math.max(1, this.pageNum - 1)
				}).finally(() => {
					this.hasFetched = true
					this.listLoading = false
					this.loadingMore = false
					if (isRefresh) this.isRefreshing = false
				})
			},
			getCurrentDate() {
				const date = new Date()
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				const formattedMonth = month.toString().padStart(2, '0')
				const formattedDay = day.toString().padStart(2, '0')
				return {
					formatted: `${year}-${formattedMonth}-${formattedDay}`
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #F3F4F6;
	}

	.page {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.fixed-header {
		flex-shrink: 0;
		width: 100%;
		z-index: 10;
		background: linear-gradient(180deg, #ffffff 0%, #fafbfc 100%);
		box-shadow: 0 8rpx 24rpx rgba(15, 23, 42, 0.06);
		border-radius: 0 0 28rpx 28rpx;
	}

	.search-box {
		padding: 24rpx 28rpx 12rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.date-picker-group {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: #F3F4F6;
			padding: 8rpx;
			border-radius: 44rpx;
			margin-right: 20rpx;
			border: 1rpx solid rgba(226, 232, 240, 0.9);

			.date-btn {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				height: 64rpx;
				font-size: 26rpx;
				color: #1F2937;
				background: #fff;
				border-radius: 36rpx;
				margin: 0 6rpx;
				box-shadow: 0 2rpx 8rpx rgba(15, 23, 42, 0.04);

				.date-text {
					max-width: 180rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.date-ico {
					margin-left: 8rpx;
					flex-shrink: 0;
				}
			}

			.date-btn--press {
				opacity: 0.88;
				transform: scale(0.98);
			}

			.separator {
				color: #9CA3AF;
				font-size: 22rpx;
				padding: 0 4rpx;
				flex-shrink: 0;
			}
		}

		.search-icon-btn {
			width: 84rpx;
			height: 84rpx;
			background: linear-gradient(135deg, #60A5FA 0%, #3B82F6 100%);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 8rpx 20rpx rgba(59, 130, 246, 0.35);
			flex-shrink: 0;
		}

		.search-icon-btn--press {
			opacity: 0.92;
			transform: scale(0.95);
		}
	}

	.mini-summary {
		padding: 0 28rpx 20rpx;
	
	}

	.mini-summary-txt {
		font-size: 24rpx;
		color: #6B7280;

		.em {
			color: #2563EB;
			font-weight: 700;
			font-variant-numeric: tabular-nums;
		}
	}

	.list-scroll {
		flex: 1;
		min-height: 0;
		height: 0;
		padding-top: 10rpx;
	}

	.list-inner {
		padding: 12rpx 24rpx 0;
		box-sizing: border-box;
	}

	.card {
		background: rgba(255, 255, 255, 0.98);
		border-radius: 24rpx;
		padding: 28rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 12rpx 36rpx rgba(15, 23, 42, 0.06);
		border: 1rpx solid rgba(255, 255, 255, 0.9);
	}

	.card--press {
		opacity: 0.97;
		transform: scale(0.995);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 4rpx;

		.header-left {
			flex: 1;
			min-width: 0;
		}

		.time-wrap {
			display: flex;
			align-items: center;
			gap: 10rpx;
		}

		.time {
			font-size: 28rpx;
			color: #374151;
			font-weight: 500;
			font-variant-numeric: tabular-nums;
		}

		.status-tag {
			flex-shrink: 0;
			padding: 8rpx 20rpx;
			border-radius: 999rpx;
			font-size: 22rpx;
			font-weight: 500;

			&.processing {
				background: #EFF6FF;
				color: #2563EB;
				border: 1rpx solid rgba(147, 197, 253, 0.6);
			}

			&.success {
				background: #ECFDF5;
				color: #059669;
				border: 1rpx solid rgba(110, 231, 183, 0.5);
			}
		}
	}

	.divider {
		height: 1rpx;
		background: linear-gradient(90deg, transparent, #E5E7EB 15%, #E5E7EB 85%, transparent);
		margin: 20rpx 0;
	}

	.info-grid {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		gap: 24rpx;

		.grid-item {
			display: flex;
			flex-direction: column;
			min-width: 0;

			&--end {
				align-items: flex-end;
				text-align: right;
			}

			.label {
				font-size: 22rpx;
				color: #9CA3AF;
				margin-bottom: 10rpx;
			}

			.value {
				font-size: 32rpx;
				color: #111827;
				font-weight: 600;
				font-variant-numeric: tabular-nums;

				&.highlight {
					color: #1D4ED8;
				}
			}
		}
	}

	.valid-pill {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx 28rpx;
		border-radius: 999rpx;
		font-size: 26rpx;
		font-weight: 600;

		&.valid {
			background: #ECFDF5;
			color: #059669;
		}

		&.invalid {
			background: #FEF2F2;
			color: #DC2626;
		}
	}

	.empty-state {
		padding: 100rpx 40rpx 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.empty-ico {
		font-size: 72rpx;
		margin-bottom: 20rpx;
		opacity: 0.5;
	}

	.empty-title {
		font-size: 30rpx;
		color: #6B7280;
		font-weight: 500;
		margin-bottom: 12rpx;
	}

	.empty-sub {
		font-size: 24rpx;
		color: #9CA3AF;
	}

	.footer-text {
		text-align: center;
		color: #9CA3AF;
		font-size: 22rpx;
		padding: 28rpx 0 8rpx;
		min-height: 44rpx;
	}

	.scroll-pad {
		height: calc(32rpx + constant(safe-area-inset-bottom));
		height: calc(32rpx + env(safe-area-inset-bottom));
	}
</style>
