<template>
	<view class="page">
		<u-navbar :is-back="false" title="订单管理" :border-bottom="false" :background="bgc" title-color='#2E4975'
			title-size='36' height='45'></u-navbar>
		<view class="top_box">
			<view class="left_text">
				时间范围
			</view>
			<view class="timebox">
				<view class="left_time" @click="time1=true">
					{{firsTime}}
				</view>
				-
				<view class="right_time" @click="time2=true">
					{{lasTime}}
				</view>
			</view>
		</view>
		<view class="top_box" style="margin-top: 20rpx;">
			<view class="left_text" @click="shows=true">
				{{tit}}
				<view class="iconfont icon-xiangxia1"></view>
			</view>
			<view class="sear_ipt">
				<input type="text" v-model="searchKeyword" placeholder="请输入内容" class="input" placeholder-style="color:#C7CDD3" @input="search()">
			</view>
		</view>
		<view class="tap">
			<view class="tap_cont " :class="zhuangtai==''?'act1':''" @click="changeidx('')">
				全部
			</view>
			<view class="tap_cont" :class="zhuangtai=='PROCESSING'?'act1':''" @click="changeidx('PROCESSING')">
				进行中
			</view>
			<view class="tap_cont" style="width: 200rpx;" :class="zhuangtai=='RIDE_WAIT_PAY'?'act1':''" @click="changeidx('RIDE_WAIT_PAY')">
				骑行待支付
			</view>
			<view class="tap_cont" :class="zhuangtai=='FINISHED'?'act1':''" @click="changeidx('FINISHED')">
				已完成
			</view>
		</view>
		<u-mask :show="show" :z-index='100' />
		<u-picker mode="time" v-model="time1" :params="params" @confirm="confirm1" :default-time='pickertime'></u-picker>
		<u-picker mode="time" v-model="time2" :params="params" @confirm="confirm2" :default-time='pickertime'></u-picker>
		<scroll-view class="warp_box" @scrolltolower="handqixing" scroll-y refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing" refresher-default-style="black">
					<view class="swiper-item">
						<view class="card" v-for="(item,index) in allList" :key="index" @click="toOrderDetail(item.deviceSn,item.id,item)">
							<view class="line"></view>
							<view class="top_info">
								<view class="top_info_left" style="display: flex; align-items: center; ">
									<text v-if="item.timeout == false">{{item.no}}</text> 
									<text v-else style="color: red;">{{item.no}}</text> 
									<text style="color: red;" v-if="item.timeout == true"> ·超时</text>
									<zhima-no-deposit-badge v-if="item.payChannelApiType === ChannelApiType.ZHIMA_DEPOSIT_ONLY.value" style="margin-left: 12rpx;" />
								</view>
								<view class="top_info_right status-processing" v-if="item.status=='PROCESSING'">
									<view class="yuan"></view>
									进行中
								</view>
								<view class="top_info_right status-wait-pay" v-if="item.status== 'WAIT_PAY'">
									<view class="yuan"></view>
									押金待支付
								</view>
								<view class="top_info_right status-finished" v-if="item.status=='FINISHED'">
									<view class="yuan"></view>
									已完成
								</view>
								<view class="top_info_right status-canceled" v-if="item.status=='CANCELED'">
									<view class="yuan"></view>
									已取消
								</view>
								<view class="top_info_right status-ride-wait-pay" v-if="item.status=='RIDE_WAIT_PAY'">
									<view class="yuan"></view>
									骑行待支付
								</view>
								<view class="top_info_right status-wait-verify" v-if="item.status=='WAIT_VERIFY'">
									<view class="yuan"></view>
									待审核
								</view>
							</view>
							<view class="lines"></view>
							<view class="order_info">
								<view class="info_li">
									<view class="half_info_li" v-if="item.status=='PROCESSING'">
										实收金额：<span style="color:orange;">0元</span>
									</view> 
									<view class="half_info_li" v-else>
										实收金额：<span style="color: orange;">{{ item.actualReceivedAmount.toFixed(2)}}</span>
									</view> 
									<view class="half_info_li">
										用户手机号：<span>{{item.userPhone == null ? '--' : item.userPhone}}</span>
									</view> 
								</view>
								<view class="info_li">
									<view class="half_info_li">
										车辆编号：<span>{{item.deviceSn == null ? '--' : item.deviceSn}}</span>
									</view>
									<view class="half_info_li" v-if="item.deviceVehicleNum">
										车牌号：<span>{{item.deviceVehicleNum}}</span>
									</view>
									<view class="half_info_li" v-else>
										车牌号：<span>--</span>
									</view>
								</view>
								<view class="info_li">
									<view class="half_info_li">
										订单费用：<span>{{item.totalFee}}元</span>
									</view> 
									<view class="half_info_li">
										人工退款：<span v-if="item.payAdminRefund>0" style="color: red;">{{item.payAdminRefund.toFixed(2)}}元</span>
										<span v-else>0.00元</span>
									</view>
								</view>
								<view class="info_li">
									<view class="half_info_li" v-if="item.startTime">
										开始时间：<span>{{formatDate(item.startTime)}}</span>
									</view>
									<view class="half_info_li" v-else>
										开始时间：<span>无</span>
									</view>
									<view class="half_info_li">
										租赁时长：<span>{{formatDatess(item.startTime,item.endTime)}}</span>
									</view>
								</view>
							</view>
						</view>
						<view class="no-more-orders">
							当前没有更多订单啦...
						</view>
					</view>
		</scroll-view>
		<u-select v-model="shows" :list="list" title='添加方式' @confirm="searchconfirm"></u-select>
		<TabBar :indexs='3' style=""></TabBar>
	</view>
</template>

<script>
	import { ChannelApiType } from '@/common/enums/channel';
import ZhimaNoDepositBadge from '@/components/zhima-no-deposit-badge/zhima-no-deposit-badge.vue';
import TabBar from '@/page_shanghu/components/tab-bar/tab-bar.vue';

	let timerId;
	let timerId1;
	export default {
		components: {
			TabBar,
			ZhimaNoDepositBadge
		},
		data() {
			return {
				ChannelApiType,
				bgc: {
					backgroundColor: "#F7FAFE",
				},
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				pickertime: '',
				time1: false,
				time2: false,
				lasTime: '',
				firsTime: '',
				searchKeyword: '',
				curtitidx: '',
				swiperHeight: 400,
				allList: [],
				ingList: [],
				reprement: [],
				alreadyList: [],
				show: false,
				showfz: false,
				showgj: false,
				showtk: false,
				orderInfo: {},
				initialValues: {},
				isRefreshing: false,
				areaId: false,
				tit: '车牌号',
				shows: false,
				list: [{
						value: '1',
						label: '手机号'
					},
					{
						value: '2',
						label: '车牌号'
					}],
				typeidx: '2',
				passList: [],
				dispatchFee: 0,
				manageFee: 0,
				ridingFee: 0,
				appointmentFee: 0,
				reason: '',
				pageNum: 1,
				isback: false,
				zhuangtai:'',
				total:'',
				wateringListone:[],

				pageSize:20
			}
		},
		onLoad() {
			if (uni.getStorageSync('adminAreaid')) {
				this.areaId = uni.getStorageSync('adminAreaid')
				this.orderList()
			}
		},
		onShow() {
			this.$store.dispatch('jiance');
		},
		watch: {
		
		},
		computed: {
			userId() {
				return this.$store.getters.userId
			},
		},
		computed: {
           formattedPayedAmount() {
               // 假设item是组件的一个响应式对象
               if (!this.item) return '￥0.00'
               const payedAmount = parseFloat(this.item.payedAmount) || 0
               const payRefunded = parseFloat(this.item.payRefunded) || 0
               const payRefunding = parseFloat(this.item.payRefunding) || 0
               const actualAmount = payedAmount - (payRefunded + payRefunding)
               return `￥${actualAmount.toFixed(2)}`
             }
		},
		onReachBottom() {

		},
		methods: {
			// 下拉刷新
			onRefresh() {
				this.isRefreshing = true
				this.pageNum = 1
				this.orderList()
				setTimeout(() => {
					this.isRefreshing = false
				}, 1000)
			},
			formatPayedAmount(payedAmount, payRefunded, payRefunding) {
				if (!payedAmount) return '0.00元'
				const amount = parseFloat(payedAmount) || 0
				const refunded = parseFloat(payRefunded) || 0
				const refunding = parseFloat(payRefunding) || 0
				const actualAmount = amount - (refunded + refunding)
				return `${actualAmount.toFixed(2)}元`
			},
			handqixing() {
				console.log(this.total,this.allList.length)
				if(this.total > this.allList.length){
					this.orderList()
				}
			},
			formatDatess(startTime, endTime) {
			  if (!startTime) return "0秒" // 如果没有开始时间，返回0
			    // 解析时间（无效时间则返回0）
			    const start = new Date(startTime)
			    const end = endTime ? new Date(endTime) : new Date()
			    if (isNaN(start.getTime()) || isNaN(end.getTime())) return "0秒"
			    // 计算时间差（毫秒）
			    let diffMs = end - start
			    if (diffMs < 0) return "0秒" // 结束时间早于开始时间
			    // 计算各时间单位
			    const diffDays = Math.floor(diffMs / 86400000)       // 天
			    diffMs %= 86400000
			    const diffHours = Math.floor(diffMs / 3600000)      // 小时
			    diffMs %= 3600000
			    const diffMinutes = Math.floor(diffMs / 60000)       // 分钟
			    diffMs %= 60000
			    const diffSeconds = Math.floor(diffMs / 1000)        // 秒
			    // 智能拼接结果（忽略0值单位，但至少显示"X秒"）
			    const parts = []
			    if (diffDays > 0) parts.push(`${diffDays}天`)
			    if (diffHours > 0) parts.push(`${diffHours}时`)
			    if (diffMinutes > 0) parts.push(`${diffMinutes}分`)
			    parts.push(`${diffSeconds}秒`) // 始终显示秒
			    return parts.join("")
			},
			formatDate(value) {
				if (!value) return ''
				let date = new Date(value)
				let month = date.getMonth() + 1 // 月份从0开始计数，所以加1
				let day = date.getDate()
				let hours = date.getHours()
				let minutes = date.getMinutes()
				// 确保月份、日期、小时和分钟都是两位数
				month = month < 10 ? '0' + month : month
				day = day < 10 ? '0' + day : day
				hours = hours < 10 ? '0' + hours : hours
				minutes = minutes < 10 ? '0' + minutes : minutes
				return `${month}-${day} ${hours}:${minutes}`
			},
			searchconfirm(e) {
				this.typeidx = e[0].value
				this.tit = e[0].label
			},
			toOrderDetail(id,orid,item) {
				uni.navigateTo({
					url: '/page_shanghu/guanli/order_detail?id=' + id + '&orid=' + orid + '&ksitem=' + item.startTime + '&endtime=' + item.endTime
				})
			},
			checkAndUpdate(key) {
				clearTimeout(timerId)
				timerId = setTimeout(() => {
					let inputValue = parseFloat(this.orderInfo[key]);
					let initialValue = parseFloat(this.initialValues[key]);
					if (inputValue > initialValue) {
						this.orderInfo[key] = initialValue;
					}
				}, 500)
			},
			showtks(item) {
				this.orderInfo = item
				this.show = true
				this.showtk = true
				this.initialValues.dispatchFee = this.orderInfo.dispatchFee
				this.initialValues.manageFee = this.orderInfo.manageFee
				this.initialValues.ridingFee = this.orderInfo.ridingFee
				this.initialValues.appointmentFee = this.orderInfo.appointmentFee
			},
			closetk() {
				this.show = false
				this.showtk = false
				this.orderInfo = {}
			},
			showgjs(item) {
				this.orderInfo = item
				this.show = true
				this.showgj = true
			},
			closegj() {
				this.show = false
				this.showgj = false
				this.orderInfo = {}
			},
			showfzs(item) {
				this.orderInfo = item
				this.show = true
				this.showfz = true
			},
			orderList() {
				let data = {}
				if (this.typeidx == 1) {
					data = {
						userPhone: this.searchKeyword,
						status: this.zhuangtai,
						createDateRange:this.firsTime == '' ? '' : this.lasTime == '' ? '' : this.firsTime + ',' + this.lasTime,
						areaId: this.areaId,
						pageSize: this.pageSize,
						pageNum: this.pageNum,
						isAsc:'desc',
						orderByColumn:'createTime'
					};
				} else if (this.typeidx == 2) { // 修改条件为 this.typeidx == 2
					data = {
						deviceVehicleNum: this.searchKeyword,
						type: '1',
						status:this.zhuangtai,
						createDateRange:this.firsTime == '' ? '' : this.lasTime == '' ? '' : this.firsTime + ',' + this.lasTime,
						areaId: this.areaId,
						pageSize: this.pageSize,
						pageNum: this.pageNum,
						isAsc:'desc',
						orderByColumn:'createTime'
					};
				}
				this.$u.get('/bst/order/list?', data).then((res) => {
					if (res.code === 200) {
						this.total = res.total
						if(this.pageNum == 1){
							this.allList = res.rows
						}else{
							this.allList = this.allList.concat(res.rows)
						}
						this.pageNum++
						this.curtitidx = 0
						this.$forceUpdate()
					}
				})
			},
			async changeidx(idx) {
				this.zhuangtai = idx
				this.pageNum = 1
				this.allList = []
				this.ingList = []
				this.reprement = []
				this.alreadyList = []
				this.orderList()
			},
			confirm1(e) {
				console.log(e, 'eeeeeeee');
				this.firsTime = e.year + '-' + e.month + '-' + e.day
				this.pageNum = 1
				this.orderList()
			},
			confirm2(e) {
				this.lasTime = e.year + '-' + e.month + '-' + e.day
				this.pageNum = 1
				this.orderList()
			},
			search() {
				this.pageNum = 1
				this.allList = []
				this.ingList = []
				this.reprement = []
				this.alreadyList = []
				clearTimeout(timerId1)
				timerId1 = setTimeout(() => {
					this.pageNum = 1
					this.orderList()
				}, 500)
				// 根据关键字过滤 this.classlist
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
	.page {
		width: 750rpx;
		.tip_box {
			position: fixed;
			left: 72rpx;
			top: 628rpx;
			width: 610rpx;
			background: #FFFFFF;
			border-radius: 30rpx 30rpx 30rpx 30rpx;
			z-index: 110;
			padding-bottom: 100rpx;
			.top {
				padding: 52rpx 38rpx 42rpx 36rpx;
				.ipt_box {
					margin-top: 22rpx;
					display: flex;
					flex-wrap: nowrap;
					align-items: center;
					.text {
						width: 350rpx;
						font-weight: 400;
						font-size: 32rpx;
						color: #3D3D3D;
					}
					.ipt {
						padding: 10rpx 18rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						margin-left: 26rpx;
						width: 420rpx;
						height: 64rpx;
						border-radius: 0rpx 0rpx 0rpx 0rpx;
						border: 2rpx solid #979797;
						.input {
							width: 80%;
						}
					}
				}
				.tip {
					width: 100%;
					text-align: center;
					font-weight: 700;
					font-size: 32rpx;
					color: #3D3D3D;
				}
				.txt {
					margin-top: 32rpx;
					width: 100%;
					text-align: center;
					font-weight: 500;
					font-size: 32rpx;
					color: #3D3D3D;
				}
			}
			.bot {
				position: absolute;
				width: 610rpx;
				display: flex;
				flex-wrap: nowrap;
				bottom: -20rpx;
				.bot_left {
					border-radius: 0rpx 0rpx 0rpx 30rpx;
					width: 50%;
					height: 86rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: 500;
					font-size: 32rpx;
					color: #3D3D3D;
					background: #EEEEEE;
				}
				.bot_right {
					border-radius: 0rpx 0rpx 30rpx 0rpx;
					width: 50%;
					height: 86rpx;
					background: #4C97E7;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #FFFFFF;
					font-weight: 500;
					font-size: 32rpx;
				}
			}
		}
		.warp_box {
			height: 61vh;
			overflow: scroll;
			background: #f5f5f5;
			.swiper-item {
				padding: 16rpx;
				.card {
					margin: 0 auto 16rpx;
					width: 100%;
					background: #fff;
					border-radius: 12rpx;
					overflow: hidden;
					border-radius: 24rpx;
					transition: all 0.3s ease;
					&:active {
						transform: scale(0.98);
					}
					.btn_box {
						display: flex;
						flex-wrap: nowrap;
						align-items: center;
						width: 100%;
						height: 96rpx;
						.btn {
							display: flex;
							align-items: center;
							justify-content: center;
							font-weight: 500;
							font-size: 32rpx;
							color: #333;
							width: 49%;
						}
						.btn_line {
							width: 0rpx;
							height: 51rpx;
							border: 2rpx solid #4C97E7;
						}
					}
					.order_info {
						padding: 20rpx 30rpx 30rpx;
						display: flex;
						flex-direction: column;
						margin-top: 10rpx;
						.info_li {
							display: flex;
							justify-content: space-between;
							align-items: center;
							width: 100%;
							font-weight: 400;
							font-size: 28rpx;
							color: #808080;
							margin-bottom: 12rpx;
							.half_info_li {
								display: flex;
								align-items: center;
								font-weight: 400;
								font-size: 28rpx;
								color: #808080;
								span {
									color: #000;
									font-weight: 500;
									margin-left: 8rpx;
								}
							}
							.half_info_li:last-child {
								text-align: right;
								justify-content: flex-end;
							}
						}
					}
					.line {
						width: 100%;
						height: 12rpx;
						background: #F6F6F6;
					}
					.lines {
						width: 100%;
						height: 1rpx;
						background: #f7f7f7;
					}
					.top_info {
						padding: 24rpx 32rpx;
						display: flex;
						flex-wrap: nowrap;
						align-items: center;
						.top_info_left {
							flex: 1;
							font-size: 26rpx;
							color: #3D3D3D;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}
						.top_info_right {
							display: flex;
							flex-wrap: nowrap;
							align-items: center;
							margin-left: auto;
							padding: 6rpx 12rpx;
							border-radius: 16rpx;
							font-weight: 500;
							font-size: 24rpx;
							.yuan {
								margin-right: 8rpx;
								border-radius: 50%;
								width: 12rpx;
								height: 12rpx;
							}
							&.status-processing {
								background: rgba(76, 151, 231, 0.1);
								color: #4C97E7;
								.yuan { background: #4C97E7; }
							}
							&.status-wait-pay {
								background: rgba(255, 69, 0, 0.1);
								color: #ff4500;
								.yuan { background: #ff4500; }
							}
							&.status-finished {
								background: rgba(34, 139, 34, 0.1);
								color: #228b22;
								.yuan { background: #228b22; }
							}
							&.status-canceled {
								background: rgba(128, 128, 128, 0.1);
								color: #808080;
								.yuan { background: #808080; }
							}
							&.status-ride-wait-pay {
								background: rgba(255, 165, 0, 0.1);
								color: #ffa500;
								.yuan { background: #ffa500; }
							}
							&.status-wait-verify {
								background: rgba(128, 128, 128, 0.1);
								color: #808080;
								.yuan { background: #808080; }
							}
						}
					}
				}
			}
			.no-more-orders {
				width: 100%;
				text-align: center;
				color: #999;
				margin: 30rpx 0;
				font-size: 28rpx;
				padding: 20rpx;
			}
		}
		.tap {
			margin-top: 24rpx;
			width: 750rpx;
			display: flex;
			flex-wrap: nowrap;
			align-items: center;
			justify-content: space-around;
			.tap_cont {
				text-align: center;
				padding-bottom: 15rpx;
				width: 100rpx;
				font-weight: 500;
				font-size: 32rpx;
				color: #3D3D3D;
				border-bottom: 6rpx solid #fff;
			}
			.act1 {
				border-bottom: 6rpx solid #4C97E7;
				color: #4C97E7;
			}
		}
		.top_box {
			display: flex;
			flex-wrap: nowrap;
			align-items: center;
			padding: 28rpx 30rpx;
			margin: 0 auto;
			width: 672rpx;
			height: 100rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 22rpx 0rpx rgba(0, 0, 0, 0.07);
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			.left_text {
				display: flex;
				flex-wrap: nowrap;
				align-items: center;
				width: 25%;
				font-weight: 400;
				font-size: 32rpx;
				color: #3D3D3D;
				.icon-xiangxia1 {
					font-size: 26rpx;
				}
			}
			.timebox {
				width: 75%;
				display: flex;
				flex-wrap: nowrap;
				align-items: center;
				margin-left: 34rpx;
				.left_time {
					text-align: center;
					margin-right: 6rpx;
					height: 50rpx;
					width: 45%;
					border: 2rpx solid #ccc;
					border-radius: 12rpx;
					font-weight: 400;
					font-size: 32rpx;
					color: #979797;
				}
				.right_time {
					text-align: center;
					margin-left: 6rpx;
					height: 50rpx;
					width: 45%;
					border: 2rpx solid #ccc;
					border-radius: 12rpx;
					font-weight: 400;
					font-size: 32rpx;
					color: #979797;
				}
			}
		}
	}
</style>