<template>
	<view class="reserveDock content_box">
		<view class="emptyImg flex_col" v-if="false">
			<image mode="aspectFit" src="../../static/img/empty/reserveEmpty.png" />
			<text class="empty-text">暂无可预约月台</text>
		</view>
		<view v-else>
			<subscribeOrderInfo :orderInfo="subscribeInfo" :materialInfo="materialList[materialList.length - 1]" />
			<!-- <view class="selectDock"> -->
			<view class="selectDock">

				<bs-customCell label="选择月台" labelCol="3">
					<text slot="value" @click="showRadio = true">{{ currentDockInfo.name }}</text>
					<view style="position: absolute; right: 41rpx;" slot="right-icon" class="t-icon t-icon-rightArrow"
						@click="showRadio = true" />
				</bs-customCell>
			</view>
			<view class="select-date flex_sb">
				<view class="prevDate" :class="{ forbidClick: isToday }" @click="onPrev">前一天</view>
				<view class="currentDate">{{ convertTime(timestamp) }}</view>
				<view class="nextDate" :class="{ forbidClick: noTomorrow }" @click="onNext">后一天</view>
			</view>
			<!-- 可选日期列表 -->
			<view class="dock-time-table">
				<view class="table-title flex flex_center">
					<text class="font_bolder">选择时段</text>
				</view>
				<view class="table-label">
					<u-row>
						<u-col span="6"> 时段</u-col>
						<u-col span="4">可预约</u-col>
						<u-col span="2" textAlign="center">选择</u-col>
					</u-row>
				</view>
				<view class="table-value-list">
					<u-empty mode="data" textSize='32' iconSize="160" text="暂无可预约时间" v-if="!currentDockTimes.length" />
					<view :class="['table-value-item', reserveTimeId === item.id ? 'activeClass' : '']"
						v-for="item in currentDockTimes" :key="item.id" @click="onSelectTime(item.id)"
						:style="(item.shipmentCapacity && (item.shipmentCapacity - item.actualShipments)<0)|| new Date(item.allEndTime).getTime() < new Date().getTime() ? 'pointer-events: none;' : ''">
					
						<u-row>
							<!-- 可预约时间 -->
							<u-col span="6"> {{ item.startTime }} - {{ item.endTime }}</u-col>
							<u-col span="4.3">
								<!-- 可预约量 -->
								<template>
									<!-- 可预约车次 -->
									<text>{{item.shipmentCapacity - item.actualShipments}}次</text>
									<!-- 可预约件数 -->
									<!-- <text>{{ item.qtyCapacity - item.actualQty }}件</text> -->
									<!-- 可预约重量 -->
									<!-- <text>{{ item.weightCapacity - item.actualWeight }}千克</text> -->
									<!-- 可预约体积 -->
							<!-- 		<text
										:style="{ 'color': item.volumeCapacity - item.actualVolume > 0 ? '' : '#AAAAAA' }">
										{{ item.volumeCapacity - item.actualVolume }}方
									</text> -->
								</template>
							</u-col>
							<u-col span="2" textAlign="center">
								<u-radio-group :key="item.id" :value="reserveTimeId === item.id?reserveTimeId:''" placement="column">
									<u-radio checked="true" :size="40" :iconSize="32" :name="item.id"
										@change="onSelectTime(item.id)"
										:disabled="(item.shipmentCapacity && (item.shipmentCapacity - item.actualShipments)<0)|| new Date(item.allEndTime).getTime() < new Date().getTime()" />
								</u-radio-group>
							</u-col>
						</u-row>
					</view>
				</view>
			</view>
			<view class="detailFoot">
				<button @click="cancelOrder">返回</button>
				<button @click="onConfirm"
					:style="reserveTimeId? '' : 'pointer-events: none;opacity: .3'">预约</button>
			</view>

			<popupRadio :radioShow="showRadio" :radioList="materialDockList" title="对应月台"
				:currentSelect="currentDockInfo.name" @cancel="closeRadio" @confirm="changeDock">

			</popupRadio>

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

<script>
import {
	ChangeOrderTime,
	CancelOrder,
	GetProductDockList,
	GetCargoDockList,
	QueryAccessItemList,
	GetDockOrderTimeList,
	SubscribeFormSubmit,
	GetDockInfo,
	GetOrderDetail,
	GetMiniDockList,
	GetOrderDays,
	NewSubscribeFormSubmit
} from '../../api/apiList';
import {
	formatTime,
	formatGMT
} from '../../utils/util';
export default {
	data() {
		return {
			subscribeInfo: {},
			dockTimes: [], //道口可预约时间列表
			reserveTimeId: '', //当前可预约时间表id
			timestamp: new Date().getTime(), //当前日期时间
			reserveTime: {},
			currentDockTimes: [],
			materialList: [],
			daysBookable: 0,
			showRadio: false,
			materialDockList: [],
			currentDockInfo: {
				name: '',
				id: ''
			},
			isProcessing: false

		}
	},
	computed: {
		isToday() {
			return new Date(this.timestamp).toDateString() === new Date().toDateString() || new Date(this.timestamp) <
				new Date()
		},
		noTomorrow() {
			if (this.daysBookable == 1) {
				return true
			}
			return false
		},
		isDockEmpty() {
			if(this.materialList.length){
				return this.materialDockList.length === 0				
			}
			return true
		}

	},
	onLoad(options) {
		let that = this
		const {
			subscribeInfo
		} = JSON.parse(options.data)
		GetOrderDetail({
			"args": {

			},
			"aux": {
				"id": subscribeInfo.id
			}
		}).then(res => {
			that.queryAccessItemList(res.data.data.header.id)
			that.subscribeInfo = res.data.data.header
		}).catch(err => {
			console.log(err)
		})

	},
	watch: {
		dockTimes: {
			deep: true,
			handler(newVal, oldVal) {
				this.isCurrentDay()
			}
		}
	},
	mounted() {

	},
	methods: {
		changeDock(value) {
			const index = this.materialDockList.findIndex((val) => {
				return val.name === value
			})
			this.currentDockInfo.name = this.materialDockList[index]["name"]
			this.currentDockInfo.id = this.materialDockList[index]["id"]
			this.getDockInfo(this.currentDockInfo.id)
			this.showRadio = false

		},
		closeRadio() {
			this.showRadio = false
		},
		isCurrentDay() {
			this.currentDockTimes = this.dockTimes.filter(val => {
				return new Date(val.allStartTime).toDateString() === new Date(this.timestamp).toDateString()
			})
		},

		queryAccessItemList(id) {
			const that = this
			const reqData = {
				"args": {
					"pageNum": 1,
					"pageSize": 100,
					"restrictions": [{
						"field": "truckAccess.id",
						"type": "EQ",
						"value": id
					}]
				}
			}
			QueryAccessItemList(reqData).then(res => {
				that.materialList = res.data.data.datas
				if (that.materialList.length > 0) {
					const firstMaterial = that.materialList[0];
					if (firstMaterial["dock.id"]) {
						that.getDockInfo(firstMaterial["dock.id"]);
						that.currentDockInfo = {
							name: firstMaterial['dock.name'] || null,
							id: firstMaterial['dock.id']
						};
					} else if (firstMaterial["product.id"]) {
						that.getProductDockList(firstMaterial["product.id"]);
					} else {
						that.getCargoDockList()
					}
				}


				// that.getCargoDockList()

			})
		},
		getProductDockList(productId) {
			const that = this
			const reqData = {
				"args": {
					"pageNum": 1,
					"pageSize": 100,
					"restrictions": [{
						"field": "product.id",
						"type": "EQ",
						"value": productId
					}]
				}
			}
			GetProductDockList(reqData).then(res => {
				if (res.data.data.datas.length > 0) {
					that.materialList[0]['dock.id'] = res.data.data.datas[0]['dock.id']
					that.materialList[0]['dock.name'] = res.data.data.datas[0]['dock.name']
					that.getDockInfo(that.materialList[0]["dock.id"])
				} else {
					that.getCargoDockList()
				}
			})

		},
		//获取道口枚举
		getDockOrderTimeList(dockId) {
			const that = this
			const reqData = {
				"args": {
					"pageNum": 1,
					"pageSize": 100,
					"restrictions": [{
						"field": "dock.id",
						"type": "EQ",
						"value": dockId
					}, {
						"field": "workDate",
						"type": "EQ",
						"value": new Date(new Date(this.timestamp).setHours(0, 0, 0, 0))
					},

					]
				}
			}
			GetDockOrderTimeList(reqData).then(res => {
				const datas = res.data.data.datas
				const dateArr = []
				datas.map(date => { //格式化后台返回时间
					if (new Date(date.startTime).getTime() >= new Date(new Date().setHours(0, 0, 0, 0))
						.getTime()) {
						date.allStartTime = date.startTime
						date.allEndTime = date.endTime
						date.startTime = formatGMT(date.startTime, 'H')
						date.endTime = formatGMT(date.endTime, 'H')
						that.reserveTimeId = !that.reserveTimeId &&
							formatGMT(that.timestamp, 'D') === that.reserveTime.arrivalDay &&
							date.startTime === that.reserveTime.arrivalTime &&
							date.endTime === that.reserveTime.departureTime ? date.id : that
							.reserveTimeId
						dateArr.push(date)
					}

				})
				this.dockTimes = dateArr
			})
		},
		getDockInfo(id) {
			let that = this
			GetDockInfo({
				"args": {

				},
				"aux": {
					"id": id
				}
			}).then(res => {
				that.getOrderDays(res.data.data.header["address.id"])

			})
		},
		getCargoDockList() {
			this.materialDockList = []
			let that = this
			GetCargoDockList({
				"args": {
					"pageNum": 0,
					"pageSize": 100,
					"restrictions": [{
						"field": "product.id",
						"type": "EQ",
						"value": this.materialList[0]["product.id"]
					}]
				}
			}).then(res => {
				if (res.data.data.datas.length > 0) {

					res.data.data.datas.map((val, ind) => {
						if (ind === 0) {
							that.currentDockInfo = {
								name: val['dock.name'],
								id: val['dock.id']
							}
							that.getDockInfo(val['dock.id'])
						}
						that.materialDockList.push(Object.assign(val, {
							name: val['dock.name']
						}))
					})

				} else {
					GetMiniDockList({
						"args": {
							"pageNum": 0,
							"pageSize": 100,
							"restrictions": [{
								"field": "address.name",
								"type": "EQ",
								"value": this.subscribeInfo['address.name']
							}]
						}
					}).then(res => {
						res.data.data.datas.map((val, ind) => {
							if (ind === 0) {
								that.currentDockInfo = {
									name: val['name'],
									id: val['id']
								}
								that.getDockInfo(val['id'])
							}
							that.materialDockList.push(Object.assign(val, {
								name: val['name']
							}))
						})

					})
				}
			})
		},
		getOrderDays(id) {
			let that = this
			GetOrderDays({
				"args": {

				},
				"aux": {
					"id": id
				}
			}).then(res => {
				that.getDockOrderTimeList(that.materialList[0]["dock.id"] || that.currentDockInfo.id)
				that.daysBookable = res.data.data.header.daysBookable
			})
		},

		//选择预约时间
		onSelectTime(id) {
			this.reserveTimeId = id
			// const currentTime = this.dockTimes.find(item => item.id === id)
			// if ((currentTime.volumeCapacity - currentTime.actualVolume) > 0 && (currentTime.weightCapacity -
			// 	currentTime.actualWeight) > 0 && (currentTime.qtyCapacity - currentTime.actualQty) >
			// 	0) { // 判断是否可选
			// 	this.reserveTimeId = id
			// } else {
			// 	// uni.showToast({
			// 	// 	title: '所选时段已约满，请选择其它时段',
			// 	// 	icon: 'none',
			// 	// 	duration: 3000
			// 	// })
			// }
		},
		//确认预约
		onConfirm() {
			// 如果已经在处理中，则直接返回
			if (this.isProcessing) return uni.showToast({
				title: '正在处理中，请稍候',
				icon: 'none',
				duration: 3000
			})

			// 设置处理中标志
			this.isProcessing = true;

			const { subscribeInfo, reserveTimeId } = this;
			let that = this;
			const reqData = {
				"args": {
					"selectedIds": [subscribeInfo.id],
					"additionalIds": {
						"": {
							"bizName": "md.DockTimeTable",
							"selectedIds": [reserveTimeId]
						}
					}
				}
			}

			NewSubscribeFormSubmit(reqData).then(res => {
				if (res.data.messageType === 'success') {
					uni.showToast({
						title: '预约成功',
						duration: 3000,
					})
					setTimeout(() => {
						uni.navigateBack();
						// 处理完成后重置标志
						that.isProcessing = false;
					}, 3000);
				} else {
					// 请求未成功时，重置标志
					that.isProcessing = false;
				}
			}).catch(error => {
				// 处理异常情况并重置标志
				that.isProcessing = false;
			});
		},

		cancelOrder() {

			uni.navigateBack()
		},







		//前一天 24h转时间戳 24*60*60*1000
		onPrev() {
			let that = this
			this.daysBookable += 1
			this.timestamp -= 86400000
			this.getDockOrderTimeList(that.materialList[0]["dock.id"] || that.currentDockInfo.id)

			// this.isCurrentDay()
		},
		//后一天
		onNext() {
			let that = this
			
			this.daysBookable -= 1
			this.timestamp += 86400000
			this.getDockOrderTimeList(that.materialList[0]["dock.id"] || that.currentDockInfo.id)
			// this.isCurrentDay()
		},
		//页面展示时间戳转换为日期
		convertTime(timestamp) {
			if (!timestamp) return
			const nowDate = new Date(timestamp)
			const year = nowDate.getFullYear();
			const month = nowDate.getMonth() + 1;
			const date = nowDate.getDate();
			const day = nowDate.getDay();
			const dayList = { //转换为大写星期
				'0': '日',
				'1': '一',
				'2': '二',
				'3': '三',
				'4': '四',
				'5': '五',
				'6': '六',
			}
			return `${year}年 ${month}月 ${date}日 周${dayList[day]}`
		},

	},

}
</script>

<style lang="scss">
.reserveDock {
	background-color: #FAFAFA;
	font-size: 28rpx;

	.emptyImg {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);

		.empty-text {
			font-size: 28rpx;
			text-align: center;
		}
	}

	.select-date {
		background-color: #FFFFFF;
		padding: 40rpx 32rpx;
		font-weight: bolder;

		.prevDate,
		.nextDate {
			color: #5B8BFC
		}

		.forbidClick {
			pointer-events: none;
			color: #BFBFBF;
		}
	}

	.selectDock {
		margin-bottom: 24rpx;
		background-color: #FFFFFF;
		padding: 40rpx 32rpx;

		/deep/.custom-cell-row {
			margin-top: 0;

			.custom-cell-label {
				color: #8C8C8C;
			}
		}
	}

	.dock-time-table {
		margin-top: 40rpx;
		background-color: #FFFFFF;

		.table-title {
			padding: 32rpx;

			.vertical-separate {
				height: 40rpx;
				border-left: 7rpx solid #797979;
				margin-right: 20rpx;
			}
		}

		.table-label {
			padding: 10rpx 32rpx;
			color: #8C8C8C;
			background-color: #FAFAFA;
		}

		/deep/.table-value-list {
			padding: 0 32rpx;

			.table-value-item {
				margin: 40rpx 0;
				padding-right: 10rpx;

				.u-radio {
					justify-content: center;
				}
			}

			.activeClass {
				color: #2E5BFB;
			}
		}
	}

	.reservePop {
		/deep/.u-popup {
			flex: none !important;

			.u-popup__content {
				width: 620rpx;
				height: 378rpx;
				border-radius: 24rpx;
				padding: 32rpx;

				.cancel_pop_header {
					width: 144rpx;
					height: 50rpx;
					font-size: 36rpx;
					line-height: 50rpx;
				}

				.cancel_pop_content {
					margin-top: 40rpx;
					width: 556rpx;
					height: 80rpx;
					text-align: center;
					font-size: 28rpx;
				}

				.cancel_pop_foot {
					margin-top: 64rpx;

					button {
						width: 262rpx;
						height: 80rpx;
						font-size: 32rpx;
						color: #2e75e6;
						border-radius: 40rpx;
						border: 2rpx solid #2e75e6;
						background-color: #FFFFFF;
					}

					.submitBtn {
						background-color: #2e75e6 !important;
						color: #FFFFFF !important;
						border: none !important;
					}
				}
			}
		}
	}

	.detailFoot {
		position: sticky;
		display: flex;
		justify-content: space-between;
		bottom: 28rpx;
		width: 100%;
		background-color: #FAFAFA;

		button {
			width: 339rpx;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx;
			color: #2E75E6;
			padding: 0 24rpx;
			border: 3rpx solid transparent;
			position: relative;
			background-clip: padding-box, border-box;
			background-origin: padding-box, border-box;
			background-image: linear-gradient(90deg, #FAFAFA, #FAFAFA), linear-gradient(90deg, #2E75E6, #5E58EE);

			&:after {
				content: "";
			}

			&:last-child {
				background-image: linear-gradient(90deg, #2E75E6, #5E58EE), linear-gradient(90deg, #2E75E6, #5E58EE);
				color: #FFFFFF;
			}
		}

	}

	.orderDetailFoot {
		button {
			width: 262rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			margin: 0;
		}
	}

	/deep/.u-modal {
		.u-modal__title {
			color: #434343 !important;
			font-weight: unset !important;
			padding: 38rpx auto !important;
		}

		.u-textarea {
			background-color: #FAFAFA;
		}
	}

}
</style>
