<template>
	<view class="page">
		<u-navbar title="运营状况" :border-bottom="false" :background="bgc" title-color='#3D3D3D' back-icon-color="#3D3D3D"
			title-size='36' height='45'></u-navbar>
		<view class="page-scroll">

			<!-- 时间范围选择卡片 -->
			<view class="time-filter-card">
				<view class="quick-dates">
					<view class="date-tag" :class="riqiindex == 0 ? 'active' : ''" @click="btnriqi(0)">今日</view>
					<view class="date-tag" :class="riqiindex == 1 ? 'active' : ''" @click="btnriqi(1)">昨日</view>
					<view class="date-tag" :class="riqiindex == 2 ? 'active' : ''" @click="btnriqi(2)">本月</view>
					<view class="date-tag" :class="riqiindex == 3 ? 'active' : ''" @click="btnriqi(3)">上月</view>
					<view class="date-tag" :class="riqiindex == 4 ? 'active' : ''" @click="btnriqi(4)">全部</view>
				</view>
				<view class="custom-date-row">
					<view class="date-picker-btn" hover-class="is-hover" hover-stay-time="100" @click="showTimePicker('start')">
						<u-icon name="calendar" color="#3B82F6" size="28" style="margin-right: 8rpx;"></u-icon>
						<text>{{kstime || '开始日期'}}</text>
					</view>
					<view class="date-separator">至</view>
					<view class="date-picker-btn" hover-class="is-hover" hover-stay-time="100" @click="showTimePicker('end')">
						<u-icon name="calendar" color="#3B82F6" size="28" style="margin-right: 8rpx;"></u-icon>
						<text>{{jstime || '结束日期'}}</text>
					</view>
				</view>
			</view>
			<u-picker mode="time" v-model="oneshow" :params="oneparams" @confirm="confirmone"></u-picker>
			<u-picker mode="time" v-model="twoshow" :params="twoparams" @confirm="confirmtwo"></u-picker>

			<view class="stats-body">
				<view class="stats-loading-mask" v-if="loading">
					<u-loading mode="circle" color="#3B82F6" size="48"></u-loading>
					<text class="stats-loading-tip">加载中...</text>
				</view>

			<!-- 期间营收统计 -->
			<view class="section-container">

				<!-- 数据总览 -->
				<view class="section-header">
					<view class="indicator"></view>
					<text class="title">数据总览</text>
				</view>
				<view class="grid-4">
					<!-- 1. 订单数量 -->
					<view class="grid-item">
						<view class="item-title">
							<view class="icon-box bg-light-primary"><u-icon name="order" color="#3B82F6" size="26"></u-icon></view>
							<text class="lbl">订单总数 (笔)</text>
						</view>
						<view class="item-val color-primary">{{ totalOrderCount | fmtInt }}</view>
						<view class="item-sub-pill">
							<view class="sub-seg">
								<text class="sub-lbl">骑行</text>
								<text class="sub-val color-primary">{{dateStat.finishedOrderCount | fmtInt}}</text>
								<text class="sub-lbl">笔</text>
							</view>
							<view class="sub-seg">
								<text class="sub-lbl">卡券</text>
								<text class="sub-val color-primary">{{dateStat.vipOrderCount | fmtInt}}</text>
								<text class="sub-lbl">笔</text>
							</view>
						</view>
					</view>

					<!-- 2. 订单实收 -->
					<view class="grid-item">
						<view class="item-title">
							<view class="icon-box bg-light-warning"><u-icon name="car" color="#F59E0B" size="28"></u-icon></view>
							<text class="lbl">订单实收 (元)</text>
						</view>
						<view class="item-val color-warning">{{ dateStat.orderActualReceivedAmount | fix2 }}</view>
						<view class="item-sub-pill">
							<view class="sub-seg">
								<text class="sub-lbl">总额</text>
								<text class="sub-val color-warning">{{dateStat.orderActualAmount | fix2}}</text>
							</view>
							<view class="sub-seg">
								<text class="sub-lbl">退款</text>
								<text class="sub-val color-warning">{{dateStat.orderAdminRefundAmount | fix2}}</text>
							</view>
						</view>
					</view>

					<!-- 3. 卡券实收 -->
					<view class="grid-item">
						<view class="item-title">
							<view class="icon-box bg-light-success"><u-icon name="coupon" color="#10B981" size="28"></u-icon></view>
							<text class="lbl">卡券实收 (元)</text>
						</view>
						<view class="item-val color-success">{{ dateStat.vipOrderAmount | fix2 }}</view>
						<view class="item-sub-pill">
							<view class="sub-seg">
								<text class="sub-lbl">售出</text>
								<text class="sub-val color-success">{{ dateStat.vipOrderCount | fmtInt }}</text>
								<text class="sub-lbl">笔</text>
							</view>
						</view>
					</view>

					<!-- 4. 收益 -->
					<view class="grid-item">
						<view class="item-title">
							<view class="icon-box bg-light-purple"><u-icon name="rmb-circle" color="#8B5CF6" size="28"></u-icon></view>
							<text class="lbl">我的收益 (元)</text>
						</view>
						<view class="item-val color-purple">{{ totalBonusAmount | fix2 }}</view>
						<view class="item-sub-pill">
							<view class="sub-seg">
								<text class="sub-lbl">骑行</text>
								<text class="sub-val color-purple">{{dateStat.bonusActualAmount | fix2}}</text>
							</view>
							<view class="sub-seg">
								<text class="sub-lbl">卡券</text>
								<text class="sub-val color-purple">{{dateStat.vipOrderBonusActualAmount | fix2}}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 费用细分 -->
				<view class="fee-container">
					<view class="section-header fee-section-header">
						<view class="fee-header-left">
							<view class="indicator"></view>
							<text class="title">订单费用细分</text>
						</view>
						<view class="fee-header-extra">
							<text class="ft-lbl">订单总额：</text>
							<text class="ft-val color-primary">¥{{ dateStat.orderActualAmount | fix2 }}</text>
						</view>
					</view>
					<view class="fee-wrapper">
						<view class="fee-list">
							<view class="fee-item">
								<text class="f-val color-primary">¥{{ dateStat.orderRiddingFee | fix2 }}</text>
								<view class="f-name-row">
									<view class="dot" style="background: #3B82F6;"></view>
									<text class="f-name">骑行费</text>
								</view>
							</view>
							<view class="fee-item">
								<text class="f-val color-success">¥{{ dateStat.orderDispatchFee | fix2 }}</text>
								<view class="f-name-row">
									<view class="dot" style="background: #10B981;"></view>
									<text class="f-name">调度费</text>
								</view>
							</view>
							<view class="fee-item">
								<text class="f-val color-warning">¥{{ dateStat.orderManageFee | fix2 }}</text>
								<view class="f-name-row">
									<view class="dot" style="background: #F59E0B;"></view>
									<text class="f-name">管理费</text>
								</view>
							</view>
							<view class="fee-item">
								<text class="f-val color-success">¥{{ dateStat.orderInsureFee | fix2 }}</text>
								<view class="f-name-row">
									<view class="dot" style="background: #10B981;"></view>
									<text class="f-name">保险费</text>
								</view>
							</view>
							<view class="fee-item">
								<text class="f-val color-purple">¥{{ dateStat.orderDeductionFee | fix2 }}</text>
								<view class="f-name-row">
									<view class="dot" style="background: #8B5CF6;"></view>
									<text class="f-name">车损费</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 收益在路上 -->
			<view class="section-container pending-container">
				<view class="section-header">
					<view class="indicator" style="background-color: #F59A23;"></view>
					<text class="title" style="color: #F59A23;">收益在路上</text>
					<u-icon name="info-circle" color="#F59A23" size="30" style="margin-left: 12rpx;" @click="showPendingTip"></u-icon>
				</view>

				<view class="pending-list">
					<view class="pending-item">
						<view class="p-icon bg-light-primary">
							<u-icon name="car" color="#3B82F6" size="36"></u-icon>
						</view>
						<view class="p-info">
							<view class="p-label">进行中订单</view>
							<view class="p-val">{{ pendingStat.orderProcessingCount | dv }}<text class="unit">笔</text></view>
						</view>
					</view>
					<view class="pending-item">
						<view class="p-icon bg-light-warning">
							<u-icon name="clock" color="#F59E0B" size="36"></u-icon>
						</view>
						<view class="p-info">
							<view class="p-label">待支付骑行费</view>
							<view class="p-val">{{ pendingStat.orderRideWaitPayCount | dv }}<text class="unit">笔</text></view>
						</view>
					</view>
					<view class="pending-item">
						<view class="p-icon bg-light-danger">
							<u-icon name="file-text" color="#EF4444" size="36"></u-icon>
						</view>
						<view class="p-info">
							<view class="p-label">待审核订单</view>
							<view class="p-val">{{ pendingStat.orderWaitVerifyCount | dv }}<text class="unit">笔</text></view>
						</view>
					</view>
				</view>
			</view>

			</view>

		</view>
	</view>
</template>

<script>
	import TabBar from '@/page_shanghu/components/tab-bar/tab-bar.vue';
	export default {
		components: {
			TabBar
		},
		filters: {
			fix2(value) {
				const num = parseFloat(value)
				if (isNaN(num)) return '0.00'
				const parts = num.toFixed(2).split('.')
				parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
				return parts.join('.')
			},
			fmtInt(value) {
				const num = parseInt(value)
				if (isNaN(num)) return '0'
				return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
			},
			dv(value) {
				return value || 0;
			}
		},
		computed: {
			totalOrderCount() {
				const ride = parseInt(this.dateStat.finishedOrderCount) || 0
				const vip = parseInt(this.dateStat.vipOrderCount) || 0
				return ride + vip
			},
			totalBonusAmount() {
				const ride = parseFloat(this.dateStat.bonusActualAmount) || 0
				const vip = parseFloat(this.dateStat.vipOrderBonusActualAmount) || 0
				return (ride + vip).toFixed(2)
			}
		},
		data() {
			return {
                bgc: {
                	backgroundColor: "#fff",
                },
				riqiindex: 0,
				oneparams: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				oneshow: false,
				twoparams: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				twoshow: false,
				kstime: '',
				jstime: '',
				dateStat: {},
				pendingStat: {},
				infoobj: {},
				areaId: '',
				loading: false,
			}
		},
		onPullDownRefresh() {
			this.getinfo()
			this.getCurrentDate(this.riqiindex)
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		onShow() {
			if (uni.getStorageSync('adminAreaid')) {
				this.areaId = uni.getStorageSync('adminAreaid')
			}
			this.getinfo()
			this.getCurrentDate(this.riqiindex)
		},
		methods: {
			getinfo() {
				this.$u.get(`/getInfo`).then(res => {
					if (res.code == 200) {
							this.infoobj = res.user
							this.gettongji()
						}
				})
			},
			gettongji() {
				if (!this.infoobj.userId) return Promise.resolve()
				const dateStatKeys = 'order_actual_amount,order_refund_amount,order_finished_count,bonus_actual_amount,order_ridding_fee,order_deduction_fee,order_dispatch_fee,order_manage_fee,order_insure_fee,vip_order_count,vip_order_amount,vip_order_bonus_actual_amount,order_admin_refund_amount'
				const pendingStatKeys = 'order_processing_count,order_wait_verify_count,order_ride_wait_pay_count'
				const dateRangeStr = (this.kstime && this.jstime) ? `${this.kstime},${this.jstime}` : ''
				const commonParams = `userId=${this.infoobj.userId}&areaId=${this.areaId}`
				this.loading = true
				return Promise.all([
					this.$u.get(`/dashboard/revenueStat?keys=${dateStatKeys}&dateRange=${dateRangeStr}&${commonParams}`),
					this.$u.get(`/dashboard/revenueStat?keys=${pendingStatKeys}&${commonParams}`)
				]).then(([dateRes, pendingRes]) => {
					if (dateRes.code == 200) {
						this.dateStat = dateRes.data
					}
					if (pendingRes.code == 200) {
						this.pendingStat = pendingRes.data
					}
				}).finally(() => {
					this.loading = false
				})
			},
			getCurrentDate(num) {
			    const currentDate = new Date()
			    const year = currentDate.getFullYear()
			    const month = currentDate.getMonth() + 1
			    const day = currentDate.getDate()
			    const formatDate = (year, month, day) => {
			        const formattedMonth = month < 10 ? `0${month}` : month
			        const formattedDay = day < 10 ? `0${day}` : day
			        return `${year}-${formattedMonth}-${formattedDay}`
			    }
			    const getFirstDayOfMonth = (year, month) => new Date(year, month - 1, 1)
			    const getLastDayOfMonth = (year, month) => new Date(year, month, 0) 
			    switch (num) {
			        case 0:
			            this.kstime = formatDate(year, month, day)
			            this.jstime = formatDate(year, month, day)
			            break
			        case 1:
			            const yesterday = new Date(currentDate)
			            yesterday.setDate(currentDate.getDate() - 1)
			            this.kstime = formatDate(yesterday.getFullYear(), yesterday.getMonth() + 1, yesterday.getDate())
			            this.jstime = formatDate(yesterday.getFullYear(), yesterday.getMonth() + 1, yesterday.getDate())
			            break
			        case 2:
			            const firstDayOfMonth = getFirstDayOfMonth(year, month)
			            this.kstime = formatDate(firstDayOfMonth.getFullYear(), firstDayOfMonth.getMonth() + 1, firstDayOfMonth.getDate())
			            this.jstime = formatDate(year, month, day)
			            break
			        case 3:
			            const lastMonthFirstDay = getFirstDayOfMonth(year, month - 1)
			            const lastMonthLastDay = getLastDayOfMonth(year, month - 1)
			            this.kstime = formatDate(lastMonthFirstDay.getFullYear(), lastMonthFirstDay.getMonth() + 1, lastMonthFirstDay.getDate())
			            this.jstime = formatDate(lastMonthLastDay.getFullYear(), lastMonthLastDay.getMonth() + 1, lastMonthLastDay.getDate())
			            break
			        case 4:
			            this.kstime = ''
			            this.jstime = ''
			            break
			        default:
			            this.kstime = formatDate(year, month, day)
			            this.jstime = formatDate(year, month, day)
			    }
			},
			confirmone(e) {
				this.kstime = e.year + '-' + e.month + '-' + e.day
				this.riqiindex = -1
				this.gettongji()
			},
			confirmtwo(e) {
				this.jstime = e.year + '-' + e.month + '-' + e.day
				this.riqiindex = -1
				this.gettongji()
			},
			btnriqi(num) {
				this.riqiindex = num
				this.getCurrentDate(this.riqiindex)
				this.gettongji()
			},
			showTimePicker(type) {
				if (type === 'start') {
					this.oneshow = true
				} else {
					this.twoshow = true
				}
			},
			showPendingTip() {
				uni.showToast({
					title: '以下订单尚未完结或未支付，完成后将计入营收',
					icon: 'none',
					duration: 3000
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #F3F4F6;
	}
	.page {
		min-height: 100vh;
		background: linear-gradient(180deg, #F3F4F6 0%, #FFFFFF 100%);
	}
	.page-scroll {
		padding-bottom: 60rpx;
		box-sizing: border-box;
	}
	.stats-body {
		position: relative;
		min-height: 520rpx;
	}
	.stats-loading-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 10;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: rgba(255, 255, 255, 0.78);
	}
	.stats-loading-tip {
		margin-top: 20rpx;
		font-size: 26rpx;
		color: #6B7280;
	}
	.is-hover {
		opacity: 0.85;
		transform: scale(0.98);
	}

	/* 时间范围选择卡片 */
	.time-filter-card {
		width: 710rpx;
		background: rgba(255, 255, 255, 0.98);
		backdrop-filter: blur(10px);
		border-radius: 24rpx;
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
		margin: 24rpx auto 0;
		padding: 24rpx;
		box-sizing: border-box;

		.quick-dates {
			display: flex;
			justify-content: space-between;
			margin-bottom: 24rpx;
			gap: 12rpx;
			.date-tag {
				flex: 1;
				height: 56rpx;
				line-height: 56rpx;
				text-align: center;
				background: #F3F4F6;
				color: #4B5563;
				font-size: 26rpx;
				font-weight: 500;
				border-radius: 12rpx;
				transition: all 0.3s ease;
				&.active {
					background: #EFF6FF;
					color: #3B82F6;
					font-weight: bold;
				}
			}
		}
		.custom-date-row {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: #F8FAFC;
			border-radius: 16rpx;
			padding: 12rpx 20rpx;
			border: 1rpx solid #F1F5F9;
			.date-picker-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				flex: 1;
				height: 64rpx;
				background: #FFFFFF;
				border-radius: 12rpx;
				font-size: 28rpx;
				color: #1F2937;
				font-weight: 600;
				box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.02);
			}
			.date-separator {
				padding: 0 20rpx;
				font-size: 24rpx;
				color: #9CA3AF;
				font-weight: 500;
			}
		}
	}

	/* 通用区块容器 */
	.section-container {
		width: 710rpx;
		margin: 24rpx auto 0;
		box-sizing: border-box;

		.section-header {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			padding-left: 8rpx;

			.indicator {
				width: 8rpx;
				height: 28rpx;
				background-color: #3B82F6;
				border-radius: 4rpx;
				margin-right: 12rpx;
				&.bg-info {
					background-color: #9CA3AF;
				}
			}
			.title {
				font-size: 30rpx;
				font-weight: bold;
				color: #1F2937;
			}
		}
	}

	/* 4宫格大字报 */
	.grid-4 {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: stretch;

		.grid-item {
			width: 340rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 24rpx 20rpx;
			margin-bottom: 24rpx;
			box-sizing: border-box;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.03);
			border: 1rpx solid #F3F4F6;
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;
			align-self: stretch;

			.item-title {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.icon-box {
					width: 40rpx;
					height: 40rpx;
					border-radius: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 10rpx;
				}
				.lbl {
					font-size: 24rpx;
					color: #6B7280;
					font-weight: 500;
				}
			}

			.item-val {
				font-size: 44rpx;
				font-weight: bold;
				font-family: 'DIN Alternate', -apple-system, BlinkMacSystemFont, sans-serif;
				margin-bottom: 16rpx;
				line-height: 1.2;
				max-width: 100%;
				word-break: break-all;
			}

			.item-sub-pill {
				width: 100%;
				margin-top: auto;
				display: flex;
				flex-wrap: wrap;
				justify-content: center;
				align-items: baseline;
				align-content: flex-start;
				gap: 8rpx 16rpx;
				background: #F3F4F6;
				padding: 8rpx 12rpx;
				border-radius: 20rpx;
				line-height: 1.4;
				box-sizing: border-box;

				.sub-seg {
					display: inline-flex;
					align-items: baseline;
					flex: 0 1 auto;
					max-width: 100%;
					white-space: nowrap;
				}
				.sub-lbl {
					font-size: 22rpx;
					color: #6B7280;
					font-weight: 500;
					margin: 0 4rpx;
				}
				.sub-val {
					font-size: 24rpx;
					font-weight: bold;
					font-family: 'DIN Alternate', -apple-system, BlinkMacSystemFont, sans-serif;
				}
			}
		}
	}

	/* 费用细分 */
	.fee-container {
		margin-top: 8rpx;

		.fee-section-header {
			justify-content: space-between;
			margin-bottom: 20rpx;
			padding-left: 8rpx;

			.fee-header-left {
				display: flex;
				align-items: center;
			}
			.fee-header-extra {
				display: flex;
				align-items: baseline;
				.ft-lbl {
					font-size: 24rpx;
					color: #6B7280;
				}
				.ft-val {
					font-size: 28rpx;
					font-weight: bold;
					font-family: 'DIN Alternate', -apple-system, BlinkMacSystemFont, sans-serif;
				}
			}
		}
	}

	.fee-wrapper {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 28rpx 16rpx 12rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.03);
		border: 1rpx solid #F3F4F6;

		.fee-list {
			display: flex;
			flex-wrap: wrap;

			.fee-item {
				width: 33.33%;
				display: flex;
				flex-direction: column;
				align-items: center;
				text-align: center;
				margin-bottom: 24rpx;
				padding: 0 8rpx;
				box-sizing: border-box;

				.f-val {
					font-size: 28rpx;
					font-weight: bold;
					font-family: 'DIN Alternate', -apple-system, BlinkMacSystemFont, sans-serif;
					margin-bottom: 10rpx;
					line-height: 1.2;
				}
				.f-name-row {
					display: flex;
					align-items: center;
					justify-content: center;

					.dot {
						width: 10rpx;
						height: 10rpx;
						border-radius: 50%;
						margin-right: 8rpx;
						flex-shrink: 0;
					}
					.f-name {
						font-size: 24rpx;
						color: #6B7280;
						font-weight: 500;
					}
				}
			}
		}
	}

	/* 收益在路上 */
	.pending-container {
		margin-top: 32rpx;

		.pending-list {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			gap: 16rpx;
			margin-bottom: 24rpx;

			.pending-item {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				background: #FFFFFF;
				padding: 24rpx 10rpx;
				border-radius: 16rpx;
				box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.03);
				border: 1rpx solid #F3F4F6;
				text-align: center;

				.p-icon {
					width: 56rpx;
					height: 56rpx;
					border-radius: 12rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 12rpx;
					.u-icon {
						font-size: 32rpx !important;
					}
				}

				.p-info {
					display: flex;
					flex-direction: column;
					align-items: center;

					.p-label {
						font-size: 24rpx;
						color: #6B7280;
						font-weight: 500;
						margin-bottom: 8rpx;
					}
					.p-val {
						font-size: 32rpx;
						font-weight: bold;
						color: #1F2937;
						font-family: 'DIN Alternate', -apple-system, BlinkMacSystemFont, sans-serif;
						.unit {
							font-size: 22rpx;
							font-weight: normal;
							color: #9CA3AF;
							margin-left: 4rpx;
						}
					}
				}
			}
		}
	}

	/* 颜色辅助类 */
	.color-primary { color: #3B82F6; }
	.color-warning { color: #F59E0B; }
	.color-success { color: #10B981; }
	.color-danger { color: #EF4444; }
	.color-purple { color: #8B5CF6; }

	.bg-light-primary { background: #EFF6FF; }
	.bg-light-warning { background: #FFFBEB; }
	.bg-light-success { background: #ECFDF5; }
	.bg-light-danger { background: #FEF2F2; }
	.bg-light-purple { background: #F5F3FF; }
</style>
