<template>
	<view class="container">
		<!-- 头部时间信息区域 -->
		<view class="header-time">
			<view class="today" @click="handleChangeTime">{{ dateType == '明天' ? '今天' : '' }}</view>
			<view class="time-info">
				{{ currentMonth }}月{{ currentDay }}日
				<span>{{ dateType }}</span>
				{{ currentWeek }}
			</view>
			<view class="tomorrow" @click="handleChangeTime">{{ dateType == '今天' ? '明天' : '' }}</view>
		</view>

		<!-- 头部路线信息区域 -->
		<view class="header-path">
			<view class="path-title">请选择路线</view>
			<view class="path-list" v-if="pathList.length">
				<view
					:class="currentIndex1 === index ? 'active path-item' : 'path-item'"
					v-for="(item, index) in pathList"
					:key="index"
					@click="handleChangeCurrentIndex(1, index, item)"
				>
					{{ item.route }}
				</view>
			</view>
			<view class="path-list-nodata" v-else>暂无数据</view>
		</view>

		<!-- 车辆列表区域 -->
		<view class="carList">
			<view class="carList-title">请选择车辆</view>
			<view
				:class="[currentIndex2 === index ? 'active ' : '', item.can_order == 0 ? 'unactive' : '', 'carList-item']"
				v-for="(item, index) in busList"
				:key="index"
				@click="handleChangeCurrentIndex(2, index, item)"
			>
				<view class="item-time">{{ item.ci_time }}</view>
				<view class="item-info">
					<view class="item-info-place">{{ item.route_end }}</view>
					<view class="item-info-detail">
						车牌：{{ item.car_number }}
						<span>容量：{{ item.boarde_num + '/' + item.contain }}</span>
					</view>
				</view>
			</view>

			<!-- 没有数据时展示的区域 -->
			<view class="carList-nodata" v-if="busList.length == 0">
				<img src="../../static/no-bus.png" />
				<view class="nodata-info">暂无数据</view>
			</view>
		</view>

		<!-- 立即预约按钮区域 -->
		<view class="btn-box" v-if="busList.length">
			<view class="btn">
				<view class="btn-clock"><img src="../../static/clock.png" /></view>
				<view class="btn-info" v-if="status">
					<view class="btn-info-title">开始预约时间段</view>
					<view>{{ yy_duration }}</view>
				</view>
				<view class="btn-info" v-else>
					<view class="btn-info-title2">候补截止时间</view>
					<view class="btn-info-time">{{ currentPath == '墨轩湖校区-黄家湖校区' ? mxh_end : hjh_end }}</view>
				</view>

				<view class="btn-button" @click="handleSub">{{ status ? '立即预约' : '候补预约' }}</view>
			</view>
		</view>

		<!-- 温馨提示区域 -->
		<view class="box-info">
			<view class="info-title">温馨提示</view>
			<view class="info-detail">
				预约截止时间为发车前{{ yy_end }}分钟，如当月爽约{{ black_count }}次，账号会被锁定，锁定后联系车队长解锁。车队长联系方式：
				<span @click="handlePhone(13576937506)">13576937506</span>
				，技术支持联系方式：
				<span @click="handlePhone(`0791 - 82293574`)">0791-82293574</span>
				，候补功能仅当日开放。
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

import { onLoad, onPullDownRefresh, onShow } from '@dcloudio/uni-app'

import { myRequest } from '@/util/api.js'

import { isWeixin } from '@/util/isWeixin.js'

import { filterIdentity } from '@/util/filterIdentity.js'

onLoad(() => {
	if (isWeixin()) {
		filterIdentity()
		card_number.value = uni.getStorageSync('bus_card_number')
	} else {
		uni.redirectTo({
			url: '/pages/404/404?message=请在微信客户端打开链接'
		})
	}
})

onShow(() => {
	dateType.value == '今天' ? getTimeFormat() : getTimeFormat(1)
	getPathList()
	getOrderConfig()
	currentIndex1.value = 0
	currentIndex2.value = null
	currentBusId.value = null
	busList.value = []
	setTimeout(() => {
		currentPath.value = pathList.value[0].route
		getBusList(pathList.value[0].route)
	}, 300)
})

// 页面下拉触发刷新回调
onPullDownRefresh(() => {
	dateType.value == '今天' ? getTimeFormat() : getTimeFormat(1)
	getPathList()
	getOrderConfig()
	currentIndex1.value = 0
	currentIndex2.value = null
	currentBusId.value = null
	busList.value = []

	setTimeout(function() {
		currentPath.value = pathList.value[0].route
		getBusList(pathList.value[0].route)
		uni.stopPullDownRefresh()
	}, 500)
})

// 用户card_number
const card_number = ref('')
// 判断是今天还是明天
const dateType = ref('今天')
// 当前月份
const currentMonth = ref('')
// 当前日期
const currentDay = ref('')
// 当前星期
const currentWeek = ref('')
// 发车路线列表
const pathList = ref([])
// 发车路线当前选中项
const currentIndex1 = ref(0)
// 当前发车路线
const currentPath = ref(null)
// 发车车辆列表
const busList = ref([])
// 预约车辆当前选中项
const currentIndex2 = ref(null)
// 当前预约车辆ID
const currentBusId = ref(null)
// 开始预约时间段
const yy_duration = ref('')
// 预约截止时间
const yy_end = ref('')
// 黄家湖校区-墨轩湖校区 候补截止时间
const hjh_end = ref('')
// 墨轩湖校区-黄家湖校区 候补截止时间
const mxh_end = ref('')
// 爽约次数
const black_count = ref('')

// 候补预约状态  true表示预约 false表示候补
const status = ref(true)

// 监听车辆列表更改候补预约状态
watch(
	() => busList.value,
	newValue => {
		if (newValue.length) {
			let flag = newValue.some(item => item.can_order == 1)
			let count = newValue.length
			let LastObj = newValue[count - 1]
			if (LastObj.boarde_num == LastObj.contain && !flag) {
				status.value = false
			} else {
				status.value = true
			}
		}
	}
)

// 获取所有的发车路线
const getPathList = async () => {
	const res = await myRequest({
		url: '/appqueryRoute.action'
	})
	// console.log(res);
	pathList.value = res.data
}

// 根据路线查询所有车次
const getBusList = async route => {
	busList.value = []
	// 处理时间参数
	let date = new Date()
	let year = date.getFullYear()

	const res = await myRequest({
		url: '/appqueryCarNums.action',
		data: {
			date: `${year}-${currentMonth.value}-${currentDay.value}`,
			route: route || currentPath.value,
			card_number: card_number.value
		}
	})
	// console.log(res)
	busList.value = res.data || []
}

// 获取预约时间段数据
const getOrderConfig = async () => {
	const res = await myRequest({
		url: '/appqueryConfig.action'
	})
	// console.log(res);
	yy_duration.value = res.data.yy_duration
	yy_end.value = res.data.yy_end
	hjh_end.value = res.data.hjh_end
	mxh_end.value = res.data.mxh_end
	black_count.value = res.data.black_count
}

// 立即预约按钮回调
const handleSub = () => {
	if (status.value) {
		if (!currentPath.value) {
			uni.showToast({
				title: '请选择路线',
				icon: 'none'
			})
			return
		}
		if (!currentBusId.value) {
			uni.showToast({
				title: '请选择车辆',
				icon: 'none'
			})
			return
		}
		uni.showModal({
			title: '提示',
			content: '确定预约吗？',
			success: res => {
				if (res.confirm) {
					handleSubscribe()
				} else if (res.cancel) {
				}
			}
		})
	} else {
		if (dateType.value == '明天') {
			uni.showToast({
				title: '候补功能仅当日开放',
				icon: 'none'
			})
			return
		}
		if (!currentPath.value) {
			uni.showToast({
				title: '请选择路线',
				icon: 'none'
			})
			return
		}
		if (pathList.value[currentIndex1.value].is_repair == 0) {
			uni.showToast({
				title: '当前路线不可候补',
				icon: 'none'
			})
			return
		}
		uni.showModal({
			title: '提示',
			content: '确定候补预约吗？',
			success: res => {
				if (res.confirm) {
					handleStandby()
				} else if (res.cancel) {
				}
			}
		})
	}
}

// 预约请求
const handleSubscribe = async () => {
	// 处理时间参数
	let date = new Date()
	let year = date.getFullYear()
	const res = await myRequest({
		url: '/appmakeAppointment.action',
		data: {
			date: `${year}-${currentMonth.value}-${currentDay.value}`,
			card_number: card_number.value,
			id: currentBusId.value,
			yyEnd: yy_end.value
		}
	})
	// console.log(res);
	if (res) {
		uni.showToast({
			title: res.message
		})
		currentIndex1.value = null
		currentIndex2.value = null
		currentPath.value = null
		currentBusId.value = null
		busList.value = []
		uni.switchTab({
			url: '/pages/my/my'
		})
	}
}

// 候补预约请求
const handleStandby = async () => {
	const res = await myRequest({
		url: '/appwait_appointment.action',
		data: {
			route: currentPath.value,
			card_number: card_number.value,
			hh_end: currentPath.value == '墨轩湖校区-黄家湖校区' ? mxh_end.value : hjh_end.value
		}
	})
	// console.log(res);
	if (res) {
		uni.showToast({
			title: res.message
		})
		currentIndex1.value = null
		currentIndex2.value = null
		currentPath.value = null
		currentBusId.value = null
		uni.switchTab({
			url: '/pages/my/my'
		})
	}
}

// 改变选中项回调
const handleChangeCurrentIndex = (type, index, item) => {
	if (type === 1) {
		currentIndex2.value = null
		currentBusId.value = null
		currentIndex1.value = index
		currentPath.value = item.route
		getBusList()
	} else {
		// 如果车辆不能预约则不进行任何操作
		if (item.can_order == 0) {
		} else {
			currentIndex2.value = index
			currentBusId.value = item.id
		}
	}
}

// 切换日期回调
const handleChangeTime = () => {
	if (dateType.value == '今天') {
		dateType.value = '明天'
		getTimeFormat(1)
	} else {
		dateType.value = '今天'
		getTimeFormat()
	}
	// currentIndex1.value = null
	// currentPath.value = null
	// currentIndex2.value = null
	// currentBusId.value = null
	// busList.value = []
	currentIndex1.value = 0
	currentPath.value = pathList.value[0].route
	currentIndex2.value = null
	currentBusId.value = null
	busList.value = []
	getBusList()
}

// 获取格式化时间 日期 和 星期
const getTimeFormat = dayType => {
	let date = new Date()
	if (dayType) {
		let targetday = date.getTime() + 1000 * 60 * 60 * 24
		date.setTime(targetday)
	}
	let month = (date.getMonth() + 1 + '').padStart(2, '0')
	let day = (date.getDate() + '').padStart(2, '0')
	let week = date.getDay()
	let weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

	currentMonth.value = month
	currentDay.value = day
	currentWeek.value = weekArr[week]
}

// 点击电话回调
const handlePhone = phone => {
	uni.makePhoneCall({
		phoneNumber: phone
	})
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #ebeced;

	.header-time {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		height: 118rpx;
		background-color: #fff;

		.today,
		.tomorrow {
			width: 72rpx;
			font-size: 24rpx;
			color: #999999;
		}

		.time-info {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 34rpx;

			span {
				margin: 0 15rpx;
				font-size: 24rpx;
				color: #3d51e8;
			}
		}
	}

	.header-path {
		margin-top: 20rpx;
		padding: 0 30rpx;
		background-color: #fff;

		.path-title {
			line-height: 95rpx;
			font-size: 34rpx;
			font-weight: bold;
		}

		.path-list {
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;

			.path-item {
				box-sizing: border-box;
				margin-bottom: 20rpx;
				padding: 0 8rpx;
				min-width: 45%;
				line-height: 96rpx;
				text-align: center;
				font-size: 27rpx;
				border-radius: 14rpx;
				background-color: #ebebeb;
			}

			.active {
				color: #fff;
				background-color: #5c60f3;

				.item-info {
					.item-info-detail {
						color: #fff;
					}
				}
			}

			.unactive {
				color: #a6a6a6;

				.item-info {
					.item-info-detail {
						color: #a6a6a6;
					}
				}
			}
		}

		.path-list-nodata {
			text-align: center;
			color: #999999;
			padding-bottom: 20rpx;
		}
	}

	.carList {
		margin-top: 20rpx;
		padding-bottom: 30rpx;
		min-height: 508rpx;
		background-color: #fff;

		.carList-title {
			padding-left: 30rpx;
			line-height: 95rpx;
			font-size: 34rpx;
			font-weight: bold;
		}

		.carList-item {
			display: flex;
			align-items: center;
			box-sizing: border-box;
			padding: 37rpx 30rpx 32rpx;
			height: 163rpx;

			.item-time {
				position: relative;
				width: 128rpx;
				font-weight: bold;
			}

			.item-time::after {
				content: '';
				height: 77rpx;
				position: absolute;
				top: -15rpx;
				right: 0;
				border-right: 1px solid #a6a6a6;
			}

			.item-info {
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				margin-left: 50rpx;
				height: 100%;

				.item-info-place {
					font-weight: bold;
				}

				.item-info-detail {
					color: #999999;
					font-size: 26rpx;

					span {
						margin-left: 20rpx;
					}
				}
			}
		}

		.active {
			color: #fff;
			background-color: #5c60f3;

			.item-info {
				.item-info-detail {
					color: #fff;
				}
			}
		}

		.unactive {
			color: #a6a6a6;

			.item-info {
				.item-info-detail {
					color: #a6a6a6;
				}
			}
		}

		.carList-nodata {
			padding: 0 30rpx;
			text-align: center;

			img {
				height: 508rpx;
			}

			.nodata-info {
				padding-bottom: 10rpx;
				color: #999999;
			}
		}
	}

	.btn-box {
		padding: 0 30rpx;
		background-color: #fff;

		.btn {
			position: relative;
			display: flex;
			align-items: center;
			width: 690rpx;
			height: 95rpx;
			border-radius: 15rpx;
			box-shadow: 0px 0px 12rpx rgba(0, 0, 0, 0.12);

			.btn-clock {
				margin-left: 30rpx;
				width: 61rpx;
				height: 61rpx;

				img {
					width: 100%;
				}
			}

			.btn-info {
				margin-left: 18rpx;
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				font-size: 24rpx;
				color: #5863f1;

				.btn-info-title {
					margin-bottom: 8rpx;
				}

				.btn-info-title2 {
					font-size: 28rpx;
					margin-bottom: 8rpx;
				}

				.btn-info-time {
					color: #b3b3b3;
				}
			}

			.btn-button {
				position: absolute;
				right: 0;
				top: -7rpx;
				width: 257rpx;
				height: 113rpx;
				line-height: 113rpx;
				text-align: center;
				font-size: 30rpx;
				color: #fff;
				background: url(../../static/box.png);
				background-size: 100% 100%;
			}
		}
	}

	.box-info {
		padding: 30rpx 30rpx 40rpx;
		background-color: #fff;

		.info-title {
			height: 41rpx;
			font-size: 28rpx;
			color: #666666;
		}

		.info-detail {
			margin-top: 5rpx;
			color: #999999;
			font-size: 24rpx;
		}
	}
}
</style>
