<template>
	<view class="container-view">
		<view class="clap-info">
			<view class="flex-row">
				<view><img class="clap-img" src="https://qiniu.bms16.com/Fn80rw2jge0oUlkYH-Ac6HzQVVvz" /></view>
				<view class="clap-title">{{ $t('拍照车牌号') }}</view>
			</view>
			<view class="clap-text">{{ $t('拍照时请留意照片的清晰度，便于系统提取车牌号') }}</view>
			<camera v-if="src==''" class="camera" :flash="flashValue" device-position="back" mode="normal"></camera>
			<!-- <camera v-if="src==''" class="camera" :flash="flashValue" device-position="back" mode="scanCode"></camera> -->
			<view v-else>
				<image class="camera-img" :src="src"></image>
			</view>
			<view class="camera-bottom flex-row">
				<view v-if="src==''" class="no-img flex-row">
					<view @tap.stop="onFlash" v-if="flashValue=='off'" class="flash"><img
							src="https://qiniu.bms16.com/FuGszSZeG74ArUnRFaG2inmosT2i" /></view>
					<view @tap.stop="onFlash" v-else class="flash"><img
							src="https://qiniu.bms16.com/FksGKHJe895cYYB-Do4b7XytX-d7" /></view>
					<view @tap.stop="takePhoto"><img class="camera-button"
							src="https://qiniu.bms16.com/FncX5x6TJ3SqRmvz9YwkwmEYkCgq" /></view>
				</view>
				<view v-else class="flex-row">
					<button @tap="bindRetake" class="retake flex-row">{{ $t('重拍') }}</button>
					<button @tap="bindUsePhoto" class="use-photo flex-row">{{ $t('使用照片') }}</button>
				</view>
			</view>
		</view>
		<view @tap="navToPage" class="input-info flex-row flex-between">
			<view class="flex-row">
				<view><img class="input-img" src="https://qiniu.bms16.com/Fmjwred5RFltqVGpxlP33MWim689" /></view>
				<view class="input-title">{{ $t('手动输入车牌号') }}</view>
			</view>
			<view><img class="right-img" src="https://qiniu.bms16.com/FpIN7AVzFU75slFlX-SIdnSEmn1k" /></view>
		</view>

		<!-- <view v-if="isShowInput" class="input-box">
			<view class="input-view">
				<view @tap="isShowInput=false" class="close">×</view>
				<input :value="plate_number" type="text">
				<view class="input-button flex-row">
					<view @tap="isShowInput=false" class="close-button flex-row">{{ $t('取消') }}</view>
					<view @tap="bindOkPhoto" class="use-button flex-row">{{ $t('确定') }}</view>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	var config = require('../../common/config.js');
	var common = require('../../common/common.js');
	var http = require('../../common/http.js');
	var storage = require('../../common/storage.js');
	var OCR = require('../../common/OCR.js');
	export default {
		components: {

		},
		data() {
			return {
				src: '',
				myLocation: {},
				hideValue: '',
				order_sn: '',
				order_model_id: '',
				isReturnIndex: true, //是否返回首页
				flashValue: 'off',
				isShowInput: false,
				plate_number: '',
				userLocation: false,
				loading: false
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad: function(options) {
			this.order_sn = options.order_sn ? options.order_sn : ''
			this.order_model_id = options.order_model_id ? options.order_model_id : ''
			this.isReturnIndex = options.isReturnIndex ? false : true
			const storedLocation = uni.getStorageSync('user_current_location');
			const me = this
			this.getUserLocation()
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			const me = this
			uni.getSetting({
				success(res) {
					//#ifdef MP-ALIPAY
					if (res.authSetting["location"] == true) {
						me.setData({
							userLocation: true,
							loading: false
						})
						me.getLocationAndSave();
					} else {
						me.setData({
							userLocation: false,
							loading: true
						})
						me.userLocation = false
						me.myLocation = {}
					}
					//#endif
					//#ifdef MP-WEIXIN
					if (res.authSetting["scope.userLocation"] == true) {
						me.setData({
							userLocation: true,
							loading: false
						})
						me.getLocationAndSave();
					} else {
						me.setData({
							userLocation: false,
							loading: true
						})
						me.userLocation = false
						me.myLocation = {}
					}
					//#endif

				}
			})
			if (this.userLocation == true && (!this.myLocation.longitude) && (!this.myLocation.latitude)) {
				this.getLocationAndSave()
			}
		},
		methods: {
			getUserLocation() {
				const me = this
				if (me.userLocation != false) { // 开了定位权限
					if (storedLocation && storedLocation.longitude && storedLocation.latitude) {
						// 如果本地有存储的定位信息，则直接使用
						console.log("111", storedLocation)
						me.myLocation = storedLocation
					} else {
						me.getLocationAndSave();
					}
				} else {
					console.log("11休闲鞋1")
					me.myLocation = {}
				}
			},

			getLocationAndSave: function() {
				const me = this;
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						uni.hideLoading();
						var myLocation = {
							longitude: res.longitude,
							latitude: res.latitude
						}
						console.log("11122", myLocation)
						me.setData({
							myLocation: myLocation,
							loading: true
						})
						uni.setStorageSync('user_current_location', myLocation);
					},
					fail: function(res) {
						uni.hideLoading();
					},
					complete: function(res) {
						uni.hideLoading();
					}
				});
			},

			takePhoto() {
				const ctx = uni.createCameraContext()
				ctx.takePhoto({
					quality: 'high',
					success: (res) => {
						this.setData({
							src: res.tempImagePath
						})
					}
				})
			},

			navToPage() {
				const me = this
				if (!me.loading) {
					common.simpleToast(this.$t('数据加载中，请稍等'))
				} else {
					if ((!me.myLocation.longitude) && (!me.myLocation.latitude)) { // 未获取到经纬度
						if (me.userLocation == false) { // 判断原因是否为微信小程序内部没有授权定位
							common.simpleToast(this.$t('无法获取位置信息，请检查您的定位权限设置'))
						} else {
							common.simpleToast(this.$t('您的手机未授权定位权限，请前往手机设置开启权限'))
						}
						return
					}
					if ((!me.myLocation.longitude) && (!me.myLocation.latitude)) {
						uni.navigateTo({
							url: '/pages/manualInput/manualInput',
						});
					} else {
						uni.navigateTo({
							url: '/pages/manualInput/manualInput?longitude=' + me.myLocation.longitude +
								'&latitude=' +
								me.myLocation.latitude,
						});
					}
				}

			},

			bindRetake() {
				this.setData({
					src: '',
					flashValue: 'off'
				})
			},

			onFlash() {
				this.setData({
					flashValue: this.flashValue == 'off' ? 'torch' : 'off'
				})
			},

			bindUsePhoto() {
				const me = this
				if ((!this.myLocation.longitude) && (!this.myLocation.latitude)) { // 未获取到经纬度
					if (me.userLocation == false) { // 判断原因是否为微信小程序内部没有授权定位
						common.simpleToast(this.$t('无法获取位置信息，请检查您的定位权限设置'))
					} else {
						common.simpleToast(this.$t('您的手机未授权定位权限，请前往手机设置开启权限'))
					}
					return
				}
				let tempFilePaths = this.src;
				uni.getFileSystemManager().readFile({
					filePath: tempFilePaths,
					encoding: 'base64',
					success: function(res) {
						common.loading();
						OCR.scanOCRText(res.data).then((words) => {
							uni.hideLoading();
							me.setData({
								hideValue: words
							});
							const licensePlate = me.hideValue.licensePlate //车牌
							const licensePlatePrefix = me.hideValue.licensePlatePrefix //前缀
							me.setData({
								// isShowInput: true,
								// plate_number: licensePlatePrefix!=''?licensePlatePrefix + licensePlate:licensePlate
								plate_number: licensePlate
							});

							me.submitPlate()
						});
					},

					fail: function(res) {
						console.log('[读取图片数据fail]', res);
					},
					complete: function(res) {}
				});
			},

			// bindOkPhoto() {
			// 	this.submitPlate()
			// },

			submitPlate() {
				const pData = {
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
					plate_number: this.plate_number
				}
				const me = this
				http.postApi(config.API_DAYHIRE_CAR_CAR_INFO, pData, (resp) => {
					uni.hideLoading()
					if (resp.data.code === 200) {
						const timestamp = Date.now(); // 获取当前时间戳（毫秒）  
						const isOffline = (Math.floor(timestamp / 1000) - resp.data.data.last_comm_time) > 1800
						if (resp.data.data.last_comm_time === 0 || isOffline) {
							common.simpleToast(this.$t('此车辆已离线，请选择其他车辆'))
						} else {
							let carInfo = JSON.stringify(resp.data.data)
							const car_model = resp.data.data.model_info.car_model
							const model_images = resp.data.data.model_info.model_images.split(',')
							const return_imgs = resp.data.data.return_imgs
							var model_id = resp.data.data.model_info.model_id
							if (resp.data.data.has_owner) { //车辆正在被使用
								if (resp.data.data.is_mine) { //是本人在使用
									uni.showModal({
										title: this.$t('提示'),
										content: '已有正在使用的车辆，是否跳转至车辆详情页?',
										cancelText: this.$t('取消'),
										confirmText: this.$t('确定'),
										success: function(res) {
											this.isReturnHome = false
											uni.navigateTo({
												url: '/pages/battery/battery?plate_number=' +
													this.plate_number
											});
										},
										fail: function(res) {},
										complete: function(res) {},
									})
								} else {
									common.simpleToast(this.$t('此车辆正在被使用'))
								}
							} else {
								if (me.order_sn != '') {
									if (this.order_model_id != model_id) { // 预租车型与之前预约车型不一致
										common.simpleToast(this.$t('与预约车型不符'))
									} else {
										this.isReturnHome = false
										uni.navigateTo({
											url: '/pages/activation/activation?plate_number=' +
												this.plate_number + '&order_sn=' + this.order_sn +
												'&car_model=' + car_model + '&model_image=' +
												model_images[0] + '&return_imgs=' + JSON.stringify(
													return_imgs),
											fail() {}
										})
									}

								} else {
									this.setData({
										flashValue: 'off',
										isReturnHome: false
									})
									// this.isReturnHome = false
									uni.redirectTo({
										url: '/pages/carIntroduce/carIntroduce?carInfo=' +
											encodeURIComponent(carInfo) + '&plate_number=' + this
											.plate_number,
										fail() {}
									})
								}
							}
							setTimeout(() => {
								me.setData({
									src: '',
									hideValue: '',
								})
							}, 500)
						}
					} else {
						common.simpleToast(resp.data.msg)
						me.setData({
							src: '',
							hideValue: '',
							// isShowInput: false,
						})
					}
				})
			},


		},
		onUnload: function() {

		}
	};
</script>

<style>
	@import './scanCar.css';
</style>