<template>
	<view>
		<u-navbar
		 title="车辆出场" 
		 title-color="#fff" 
		 :custom-back="customBack" 
		 :border-bottom="false" 
		 back-icon-color="#CCE8FF" 
		 :background="{background: 'linear-gradient(145deg, #41AFF9 0%, #2D8CFB 100%)' }"></u-navbar>
		<view class="search"><u-search placeholder="请输入车位名称"  v-model="roadspaceList.spaceName" shape="round" @search="spaceSearch()" @custom="spaceSearch()"></u-search></view>
		<u-empty class="u-m-t-80" text="暂无停车" mode="data" v-if="roadspaceList.length == 0"></u-empty>
		<view class="roadspace-list wrap">
			<view class="roadspace-list-item" :class="{used:item.placeStatus==1}" v-if="item.placeStatus==1&&item.vehicleNo != 0" @click="roadspaceClick(item)" v-for="item in roadspaceList" :key="item.id">
				<view class="block"  >
					<view class="block-top">
						<u-icon name="car-fill" size="40" color="#fff"></u-icon>
						<view class="car-no">{{ item.vehicleNo }}</view>
					</view>
					<view class="block-bottom">
						<u-icon name="clock-fill" size="40" color="#3397FA"></u-icon>
						<view class="time">{{ item.inTime | timeago(currentTime)}}</view>
					</view>
				</view>
				<view class="text">{{item.spaceName}}</view>
			</view>	
		</view>
		<view class="bottom-btn-wrap">
			<!-- <view class="bottom-btn" @click="jumpToMain()">返回主页</view> -->
			<u-button class="bt1"  @click="last(list.pageNum)"><</u-button>
			<view class="pagesInput">
				<view class="pagesInput-left">第</view><u-input v-model="pageNum" type="text" :border="true" :clearable="false" /><view class="pagesInput-right">页</view></view>
			<view class="num">
			<u-button @click="jump(list.pageNum)" size="mini">跳转</u-button>
			</view>
			<u-button class="bt2" @click="next(list.pageNum)">></u-button>
		</view>
		<u-action-sheet :list="actionList" @click="actionClick" v-model="actionShow"></u-action-sheet>
		<u-popup class="confirm-pop" v-model="confirmPop" mode="center" border-radius="20" width="90%" duration="300">
			<view class="confirm-pop-til">入场确认</view>
			<view class="confirm-pop-con car-info u-flex">
				<view class="car-info-img" @click="getPic">
					<u-image :src="confirmData.carImg" mode="aspectFit" width="100%" height="100%"></u-image>
				</view>
				<view class="car-info-text u-flex-1">
					<view class="text-item position-wrap">
						<view class="position">车位：{{confirmData.spaceName}}</view>
					</view>
					<view class="text-item u-flex u-flex u-row-between">
						<view>车牌号</view>
						<view class="u-flex-1 u-m-l-40">
							<u-input v-model="confirmData.vehicleNo" height="80" width="100" type="text" @focus="messageInputClick" placeholder="输入车牌号" />
							
						</view>
					</view>
					<view class="text-item u-flex u-flex u-row-between">
						<view class="">车辆类型</view>
						<view class="" @click="carTypeShow = true">
							{{confirmData.vehicleType|filterCarType}}
							<u-icon class="u-m-l-10" name="arrow-down-fill" color="#C2C2C2" size="15"></u-icon>
						</view>
					</view>
					<view class="text-item u-flex u-flex u-row-between">
						<view>车辆颜色</view>
						<view @click="carColorShow = true">
							{{confirmData.vehicleColor|filterCarColor}}
							<u-icon class="u-m-l-10" name="arrow-down-fill" color="#C2C2C2" size="15"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="upload-wrap">
				<u-upload 
				ref="uUpload"
				:action="uploadAction" 
				:show-progress="false" 
				upload-text="拍照取证" ></u-upload>
			</view>
			<view class="btn-wrap">
				<view class="btn" @click="confirmIn">确认</view>
			</view>
		</u-popup>
		<u-toast ref="uToast" />
		<u-keyboard ref="uKeyboard" mode="car" @change="keyboardChange" @backspace="backspace" v-model="keyboardshow"></u-keyboard>
		<u-select v-model="carTypeShow" :default-value="[2]" :list="carTypeList" @confirm="carTypeConfirm"></u-select>
		<u-select v-model="carColorShow" :default-value="[2]" :list="carColorList" @confirm="carColorConfirm"></u-select>
		
	</view>
</template>

<script>
	import { config } from '@/common/config.js';
	import { mydata } from '@/common/data.js';
	//#ifdef APP-PLUS
	import speak from '@/utils/speaks.js';
	let ALog = uni.requireNativePlugin("AndroidLog");
	let device = uni.requireNativePlugin("DeviceInfo");
	let ocr = uni.requireNativePlugin("OcrPlug");
	//#endif
	export default {
		data() {
			return {
				speakParkOut:'',
				roadNo:null,//路段编码 ,示例值(RN000000004)
				actionList:[
					{text: '出场'},
					{text: '入场确认'},
				],
				actionShow:false,
				roadspaceList:{
					spaceName:'',
				},
				searchList:[],
				orderInfo:null,
				spaceId:null,
				currentTime: new Date(), // 获取当前时间
				confirmPop:false,
				confirmData:{
					carImg:'/static/img/default-car.png',
					spaceName:null,
					vehicleType:null,
					vehicleColor:null,
				},
				keyboardshow:false,
				carTypeShow:false,
				carColorShow:false,
				carTypeList:mydata.carTypeList,
				carColorList:mydata.carColorList,
				uploadAction:config.baseUrl+'/file/tencent/upload',
				list:{
					pageNum:''
				},
				pages:'',
				pageNum:'',
				currentPageNum:'',
				
			}
		},
		onLoad() {
			uni.getStorage({
				key:'speakData',
				success: (res) => {
					this.speakParkOut = res.data.switchVal4;
				},
				fail: (err) => {
				}
			})
		},
		onShow() {
			let that = this;
			this.roadNo = this.$store.state.vuex_user?.roadList?.[0].roadNo || '';
			this.handleGetRoadspace(this.roadNo);
			// this.timeList[0].time = this.roadspaceList[0].inTime;
			// this.timeList[1].time = this.currentTime.getFullYear()+'-'+(this.currentTime.getMonth()+1)+'-'+this.currentTime.getDay()+' '+this.getTimer();
			setInterval( () => {
				that.currentTime = new Date()//修改数据让他可以实时更新
			}, 1000);
		},
		methods:{
			
			jump(){
				this.$u.api.getRoadspace({roadNo:this.roadNo,placeStatus:1,pageNum:this.pageNum || ''})
				.then(res => {
					this.pages=res.data.pages;
					this.currentPageNum=res.data.page;
					this.list.pageNum=res.data.page;
					this.roadspaceList = res.data.rows;
				})
			},
			spaceSearch(){
				console.log(this.roadspaceList.spaceName)
				this.$u.api.getRoadspace({roadNo:this.roadNo,placeStatus:1,spaceName:this.roadspaceList.spaceName})
				.then(res => {
					this.pages=res.data.pages;
					this.list.pageNum=res.data.page;
					this.roadspaceList = res.data.rows;
				})
			},
			last(i){
				if(i>1){
					setTimeout(	this.handleGetRoadspace(this.roadNo,i-1),500)
					// this.handleGetRoadspace(this.roadNo,i-1)
				}else{
					return
				}				
			},
			next(n){
				if(n < this.pages){
					setTimeout(this.handleGetRoadspace(this.roadNo,n+1),500)
					// this.handleGetRoadspace(this.roadNo,n+1)
				}else{
					this.$refs.uToast.show({
						title: '已经是最后一页',
						type: 'warning',
					})
				}
			},
			jumpToMain(){
				this.$u.route({
					type: 'redirectTo',
					url: '/pages/index/index'
				})
			},
			customBack(){
				this.$u.route({
					type: 'redirectTo',
					url: 'pages/index/index'
				});
			},
			handleGetRoadspace(roadNo,page){
				this.$u.api.getRoadspace({roadNo:this.roadNo,placeStatus:1,pageNum:page || ''})
				.then(res=>{
					// this.$refs.uToast.show({
					// 	title: res.msg,
					// 	type: 'success',
					// });
					this.currentPageNum=res.data.page;
					this.pages=res.data.pages;
					this.list.pageNum=res.data.page;
					this.roadspaceList = res.data.rows;
				}).catch(err=>{
					if(err.errMsg){
						this.$refs.uToast.show({
							title: '请检查网络',
							type: 'error',
						});
						return false;
					};
					err.msg&&this.$refs.uToast.show({
						title: err.msg,
						type: 'error',
					});
					console.log('handleGetRoadspace ',err)
				});
			},
			roadspaceClick(item){
				this.confirmData = item;
				this.confirmData.vehicleColor = 0;
				this.confirmData.vehicleType = 0;
				this.orderInfo = item;
				this.spaceId = item.id;
				if(!item.vehicleNo){
					//无车牌打开补全车牌信息
					let that = this;
					ocr.ocrVehicleNo((ret) => {
						if (ret.success){
							that.confirmData.vehicleNo = ret.vehicleNo;
							that.confirmData.carImg =  'data:image/png;base64,' + ret.imageBase64;
							this.$u.api.tencentBase64Upload({
								base64: ret.imageBase64,
								suffix: 'png'
							})
							.then(res=>{
									this.confirmPop = true;
									that.confirmData.vehicleImage =  res.data.url;
							}).catch(err=>{});
						}else {
							plus.nativeUI.toast('识别失败');
						}
					});
				}else {
					//信息完整打开出场页面
					const d = new Date();
					this.$u.route({
						url: 'pages/getout/getoutpage/getoutpage',
						params: {
							orderID:item.id,
							orderInTime:item.inTime,
							orderOutTime:`${d.getFullYear()}-${((d.getMonth()+1)>=10?+(d.getMonth()+1):"0"+(d.getMonth()+1))}-${((d.getDate())>=10?d.getDate():'0'+d.getDate())} ${d.getHours()>=10?d.getHours():'0'+d.getHours()}:${d.getMinutes()>=10?d.getMinutes():'0'+d.getMinutes()}:${d.getSeconds()>=10?d.getSeconds():'0'+d.getSeconds()}`,
							orderSpaceName:item.spaceName,
							orderVehicleNo:item.vehicleNo
						}
					});
				}
				
			},
			actionClick(e){
				console.log('actionClick',e);
				switch (e){
					case 0:
						const d = new Date();
						this.$u.route({
							url: 'pages/getout/getoutpage/getoutpage',
							params: {
								orderID:this.orderInfo.id,
								orderInTime:this.orderInfo.inTime,
								orderOutTime:`${d.getFullYear()}-${((d.getMonth()+1)>=10?+(d.getMonth()+1):"0"+(d.getMonth()+1))}-${((d.getDate())>=10?d.getDate():'0'+d.getDate())} ${d.getHours()>=10?d.getHours():'0'+d.getHours()}:${d.getMinutes()>=10?d.getMinutes():'0'+d.getMinutes()}:${d.getSeconds()>=10?d.getSeconds():'0'+d.getSeconds()}`,
								orderSpaceName:this.orderInfo.spaceName,
								orderVehicleNo:this.orderInfo.vehicleNo
							}
						});
						break;
					case 1:{
						this.confirmPop = true;
						break;
					}
					default:
						break;
				}
			},
			messageInputClick(){
				this.keyboardshow = true;
			},
			// 按键被点击(点击退格键不会触发此事件)
			keyboardChange(val) {
				// 将每次按键的值拼接到value变量中，注意+=写法
				this.confirmData.vehicleNo += val;
				console.log(this.confirmData.vehicleNo);
			},
			// 退格键被点击
			backspace() {
				// 删除value的最后一个字符
				if(this.confirmData.vehicleNo.length) this.confirmData.vehicleNo = this.confirmData.vehicleNo.substr(0, this.confirmData.vehicleNo.length - 1);
				console.log(this.confirmData.vehicleNo);
			},
			carTypeConfirm(e){
				this.confirmData.vehicleType = e[0].value;
			},
			carColorConfirm(e){
				console.log('e',e)
				this.confirmData.vehicleColor = e[0].value;
				console.log('this.confirmData',this.confirmData)
			},
			getPic(){
				let that = this;
				ocr.ocrVehicleNo((ret) => {
					if (ret.success){
						that.confirmData.vehicleNo = ret.vehicleNo;
						that.confirmData.carImg =  'data:image/png;base64,' + ret.imageBase64;
						this.$u.api.tencentBase64Upload({
							base64: ret.imageBase64,
							suffix: 'png'
						})
						.then(res=>{
								that.confirmData.vehicleImage =  res.data.url;
						}).catch(err=>{});
					}else {
						plus.nativeUI.toast('识别失败');
					}
				});
				// uni.chooseImage({
				// 	count: 1, //默认9
				// 	sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				// 	sourceType: ['camera'], //
				// 	success: function (res) {
				// 		console.log('img',res)
				// 		that.confirmData.carImg = res.tempFilePaths[0];
				// 		uni.showLoading({});
				// 		const tempFilePaths = res.tempFilePaths;
				// 		// 若多选，需循环调用uni.uploadFile ，因微信小程序只支持单文件上传
				// 		uni.uploadFile({
				// 			url: `${that.config.fileUrl}/baidu/ocr`,
				// 			filePath: tempFilePaths[0],
				// 			name: 'file',
				// 			formData: {
				// 				'isUpload': '1'  // 上传附带参数
				// 			},
				// 			success: (res) => {
				// 				// 根据接口具体返回格式   赋值具体对应url
				// 				// alert(uploadFileRes.data);
				// 				let resobj=eval("("+res.data+")");
				// 				uni.hideLoading();
				// 				if(resobj.code==200){
				// 					console.log(resobj);
				// 					//#ifdef APP-PLUS
				// 					speak(resobj.data.vehicleNo);
				// 					//#endif
				// 					that.confirmData.vehicleNo = resobj.data.vehicleNo;
				// 					that.confirmData.vehicleClor = resobj.data.vehicleClor;
				// 					that.confirmData.vehicleImage =  resobj.data.url;
				// 					console.log('that.confirmData',that.confirmData);
				// 				}else{
				// 					that.$refs.uToast.show({
				// 						title: resobj.msg,
				// 						type: 'error'
				// 					});
				// 				};
				// 				console.log('resobj',resobj);
				// 			},
				// 			fail: (err) => {
				// 				that.$refs.uToast.show({
				// 					title:err.msg,
				// 					type: 'error'
				// 				});
				// 				uni.hideLoading();
				// 			}
				// 		});
				// 	}
				// });
			},
			confirmIn(){
				let files = [];
				let that = this;
				// 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
				files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				});
				// 如果不需要进行太多的处理，直接如下即可
				// files = this.$refs.uUpload.lists;
				that.confirmData.images = [];
				this.confirmData.spaceId = that.confirmData.id;
				files.forEach(function(element) {
				  that.confirmData.images.push(element.response.data.url);
				});
				let param = this.confirmData;
				this.$u.api.parkInConfirm(param)//有车但是车牌为空
				.then(res=>{
					this.$refs.uToast.show({
						title: res.msg,
						type: 'success',
						url:'pages/getout/getout'
					});
					//#ifdef APP-PLUS
					device.print(res.data.print);
					if(this.speakParkOut==true||this.speakParkOut==''){
						speak(res.data.speak);
					}
					//#endif
					console.log('parkInConfirm',res)
				}).catch(err=>{
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error',
						// url:'pages/parking/parking'
					});
					console.log('parkInConfirm ',err)
				});
			}
			
			
		},
		filters:{
			timeago(inTime,currentTime){
				var time_start = '', clock_start = ''
				if (inTime) {
					time_start = new Date(inTime.replace(/-/g,'/'));
					time_start.getTime();
				}
				const formatNumber = (num) => {
					num = num.toString()
					return num[1] ? num : '0' + num
				};
				var i_total_secs = Math.round(currentTime.getTime() - time_start);
				//计算出相差天数
				var days = Math.floor(i_total_secs / (24 * 3600 * 1000))
					 
				//计算出小时数
				var leave1 = i_total_secs % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
				var hours = Math.floor(leave1 / (3600 * 1000))
				
				// var hours = Math.floor(i_total_secs / (3600 * 1000))
				
				//计算相差分钟数
				var leave2 = i_total_secs % (3600 * 1000)        //计算小时数后剩余的毫秒数
				var minutes = Math.floor(leave2 / (60 * 1000))
				//计算相差秒数
				var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
				var seconds = Math.round(leave3 / 1000)
				days = formatNumber(days)
				hours = formatNumber(hours);
				minutes = formatNumber(minutes);
				seconds = formatNumber(seconds);
				// console.log(days + '天' + hours + '个小时' + minutes + '分钟' + seconds + '秒');
				return days + '天' + hours + '时' + minutes + '分' + seconds + '秒'
			}
		}
		
	}
</script>

<style lang="scss">
	// @import "../parking/parking.scss";
	@import "./getout.scss";
</style>
