<template>
	<view>
		<map :latitude="detailData.originLatitude" :longitude="detailData.originLongitude" :markers="covers" class="map"
			:polyline="polyline"></map>
		<!-- <cover-view v-if='show'>
			<view>确认行程已结束？</view>
		</cover-view> -->
		<view class='wrap'>
			<view class="c-row">
				<view class="title">车牌号</view>
				<view class="con-list">

					<!-- <input :disabled='titleBtn=="申请报销"' v-model='detailData.carNo' placeholder="请输入车牌号" maxlength="7"></input> -->
				</view>
				<picker :range="carNolist" range-key="carNo" @change='carnopicker($event)' :disabled='titleBtn=="申请报销"'
					mode="selector">
					<view>{{detailData.carNo?detailData.carNo:'请选择车牌号'}}</view>
				</picker>
			</view>
			<view @click='startTrack' class="button" v-if='titleBtn=="开始轨迹"'>{{titleBtn}}</view>
			<view @click='endTrack' class="button1" v-if='titleBtn=="结束轨迹"'>{{titleBtn}}</view>
			<view @click='reimbursement' class="button2" v-if='titleBtn=="申请报销"'>{{titleBtn}}</view>
		</view>
		<u-toast ref="uToast" />
		<!-- <u-modal v-model="show" @confirm='submit' content="确认行程已结束？" :show-cancel-button='true' ></u-modal> -->
	</view>
</template>

<script>
	var that
	export default {
		data() {
			return {
				place: {},
				fillingId: '',
				polyline: [{ //指定一系列坐标点，从数组第一项连线至最后一项
					points: [],
					color: "#0000AA", //线的颜色
					width: 1, //线的宽度
					// 　　　　dottedLine:true,//是否虚线
				}],
				carNo: '',
				show: false,
				show4: false,
				carNolist: [],
				detailData: {
					carNo: '',
					travelStatus: '',
					originProvince: '',
					originCity: '',
					originArea: '',
					originLongitude: '',
					originLatitude: '',
					destinationProvince: '',
					destinationCity: '',
					destinationArea: '',
					destinationLongitude: '',
					destinationLatitude: '',
					trackFlag: '',
					compId: '',
					commonId: '',
					driverName: '',
					fillingNo: '',
					strokeType: '1',
				},
				covers: [],
				titleBtn: "开始轨迹",
			}
		},
		created() {
			// #ifdef APP-PLUS
			const subNVue = uni.getSubNVueById('popview') //'popview'就是你在                		 
			subNVue.hide('none', 100);

			uni.$on('page-popup-submit', (data) => {
				console.log(data)
				subNVue.hide('none', 100);

				this.submit()
			})
			uni.$on('page-popup-close', (data) => {
				console.log(data)
				subNVue.hide('none', 100);
			})
			// #endif
		},
		destroyed() {
			// 移除监听事件
			uni.$off("page-popup-submit")
		},
		onLoad(options) {
			//获取车牌号
			this.$api.doRequest('get', '/carInfo/selectCars', {
					currentPage: 1,
					pageSize: 9999,
					compId: uni.getStorageSync('pcUserInfo').compId,
				})
				.then(res1 => {
					console.log(111)
					console.log(res1)
					if (res1.data.code == 200) {
						this.carNolist = res1.data.data.records
					}
				})
				.catch(res => {
					uni.$u.toast(res.message);
				});
			this.id = options.id
			that = this

		},
		onShow() {
			this.getLngLat('开始轨迹');
			// this.$api.doRequest('post', '/CarPostionController/api/getlocation', {
			// 		currentPage: 1,
			// 		pageSize: 9999,
			// 		compId: uni.getStorageSync('pcUserInfo').compId,
			// 	})
			// 	.then(res1 => {
			// 		// if(res1.data.code==200){
			// 		console.log(res1, 11111111)
			// 		// }
			// 	})
			// 	.catch(res => {
			// 		uni.$u.toast(res.message);
			// 	});
			var that = this
			if (this.id) {
				this.seeInfo()
			} else {
				// #ifdef APP-PLUS
				this.getLngLat('开始轨迹');
				// #endif
			}
		},
		methods: {
			carnopicker(e) {
				this.detailData.carNo = this.carNolist[e.target.value].carNo
			},
			async getLngLat(type) {
				let that = this
				uni.showLoading({
					title: '获取定位中',
					mask: true
				})
				let _location = {}
				await that.$api.doRequest('post', '/CarPostionController/api/getlocation')
					.then(res => {
						this.place = JSON.parse(res.data.data)[0]
						console.log(this.place)
					})
					.catch(res => {
						// uni.$u.toast(res.message);
					});

				await that.$api.changeLocation('post', '/v3/assistant/coordinate/convert', {
						key: 'dd701d394d116b50268dc16470ddd615',
						locations: this.place.lng + "," + this.place.lat
					})
					.then(res => {
						this.place = JSON.parse(res.data.data)[0]
						console.log(this.place)
					})
					.catch(res => {
						// uni.$u.toast(res.message);
					});
				let _data = {
					key: 'dd701d394d116b50268dc16470ddd615',
					location: this.place.lng + "," + this.place.lat
				}
				await that.$api.getPlace('get', '/v3/geocode/regeo', _data).then(res => {
						console.log('111')
						console.log("定位信息", res)
						if (type == '开始轨迹' || type == '已开始') {
							console.log(2)
							that.detailData.originLongitude = that.place.lng;
							that.detailData.originLatitude = that.place.lat;
							that.detailData.originProvince = res.data.regeocode.addressComponent.province;
							that.detailData.originCity = that.$helper.filterUrban(res.data.regeocode
								.addressComponent.city)
							that.detailData.originArea = that.$helper.filterUrban(res.data.regeocode
								.addressComponent.district)
							that.detailData.originAddress = res.data.regeocode.formatted_address
							console.log("that.detailData", that.detailData)
						} else if (type == '结束轨迹') {
							console.log("结束")
							// console.log("res",res)
							that.detailData.carNo = that.carNo

							that.detailData.destinationLongitude = that.place.lng;

							that.detailData.destinationLatitude = that.place.lat;
							that.detailData.destinationProvince = res.data.regeocode.addressComponent.province;
							that.detailData.destinationCity = that.$helper.filterUrban(res.data.regeocode
								.addressComponent.city)
							that.detailData.destinationArea = that.$helper.filterUrban(res.data.regeocode
								.addressComponent.district)
							that.detailData.destinationAddress = res.data.regeocode.formatted_address
							that.detailData.trackFlag = "1"
							console.log("asddfadsad", that.detailData)
							that.$api.doRequest('post', '/fuelFillingInfo/api/addFilling', that.detailData)
								.then(res1 => {
									if (res1.data.code == 200) {
										this.titleBtn = "申请报销"
									}
								})
								.catch(res => {
									uni.$u.toast(res.message);
								});
						}

						this.covers = [{
							id: 0,
							latitude: that.place.lat,
							longitude: that.place.lng,
							iconPath: '../../../static/img/location.png',
						}]


					})
					.catch(res => {
						// uni.$u.toast(res.message);
					});
				that.$forceUpdate()
				uni.hideLoading()
			},

			seeInfo() {
				this.$api.doRequest('get', '/fuelFillingInfo/getFilling', {
					id: this.id
				}).then(res => {
					console.log(222222, res.data, this.id)
					if (res.data.code == 200) {
						this.detailData = res.data.data
						console.log(this.detailData, 111111)
						if (this.detailData.travelStatus == "已开始") {
							this.titleBtn = "结束轨迹"
						} else if (this.detailData.travelStatus == "已结束") {
							this.titleBtn = "申请报销"
						}
						// #ifdef APP-PLUS
						this.getLngLat(this.detailData.travelStatus);
						// #endif
					}
				})
			},
			async seeInfo1() {
				await this.$api.doRequest('get', '/fuelFillingInfo/getFilling', {
					id: this.id
				}).then(res => {
					if (res.data.code == 200) {
						this.detailData = res.data.data
						this.getLngLat('结束轨迹')
					}
				})
			},
			// 申请报销
			reimbursement() {
				uni.navigateTo({
					url: '/pages/fuelfilling/apply_for_reimbursement?id=' + this.id
				})
			},
			// 结束轨迹
			endTrack() {
				this.carNo = this.detailData.carNo
				let that = this
				uni.showModal({
					content: "确定结束轨迹？",
					showCancel: true,
					confirmText: '确定',
					success: function(res) {
						if (res.confirm) {
							let time = new Date();
							let timeInfo = (time.getFullYear() + '-' + time.getMonth() + '-' + time.getDate() +
								" " + time
								.getHours() +
								':' + time.getMinutes() + ':' + time.getSeconds())
							uni.setStorageSync('jyEndTime', timeInfo)
							that.seeInfo1()
						}
					}
				})
				// // #ifdef APP-PLUS
				// const subNVue = uni.getSubNVueById('popview') //'popview'就是你在                		 
				// subNVue.show('zoom-fade-out', 300, function() {});
				// // #endif
			},
			submit() {
				// if (that.$helper.fUN_AmapLocation) {
				// 	that.$helper.fUN_AmapLocation.stop({}, result => {
				// 		console.log('====fUN_AmapLocation定位stop====', JSON.stringify(result));
				// 		// 更新轨迹结束地点
				// 		// 更新结束地点位置
				// 		this.seeInfo1()
				// 		this.getLngLat('结束轨迹')
				// 	});
				// }
			},
			//开始轨迹
			async startTrack() {
				var that = this
				// if (!this.detailData.carNo) {
				// 	uni.showToast({
				// 		title: "车牌号不能为空！",
				// 		icon: "none"
				// 	})
				// 	return
				// }
				// if (!this.detailData.originAddress) {
				// 	uni.showToast({
				// 		title: "未获取起始位置，请开启定位在试！",
				// 		icon: "none"
				// 	})
				// 	return
				// }
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				that.detailData.compId = uni.getStorageSync('pcUserInfo').compId
				that.detailData.commonId = uni.getStorageSync('pcUserInfo').userId
				that.detailData.driverName = uni.getStorageSync('userInfo').userName
				that.detailData.trackFlag = "0"
				console.log(that.detailData)
				//存储开始时间

				let time = new Date();
				let timeInfo = (time.getFullYear() + '-' + time.getMonth() + '-' + time.getDate() + " " + time
					.getHours() +
					':' + time.getMinutes() + ':' + time.getSeconds())
				await that.$api.doRequest('post', '/fuelFillingInfo/api/addFilling', that.detailData).then(res1 => {
						console.log(res1.data)
						if (res1.data.code == 200) {
							uni.hideLoading()
							// that.$helper.fUN_AmapLocation.start({
							// 		intervalTime: 5000,
							// 		isReport: false
							// 	},
							// 	res => {
							// 		this.covers = [{
							// 			id: 0,
							// 			latitude: res.latitude,
							// 			longitude: res.longitude,
							// 			iconPath: '../../../static/img/location.png',
							// 		}]
							this.id = res1.data.data
							// 		this.seeInfo1()
							// 		let _data = {
							// 			fillingId: res1.data.data,
							// 			longitude: res.longitude,
							// 			latitude: res.latitude,
							// 			province: res.province,
							// 			city: res.city,
							// 			area: res.district
							// 		}
							// if (this.shippingNoteInfos && this.shippingNoteInfos.length > 0) { //更新持续定位经纬度
							// 	for (let i = 0; i < this.shippingNoteInfos.length; i++) {
							// 		this.shippingNoteInfos[i].startLatitude = _data.latitude //纬度
							// 		this.shippingNoteInfos[i].startLocationText = _data.city //起点
							// 		this.shippingNoteInfos[i].startLongitude = _data.longitude //经度
							// 	}
							// }
							// this.$helper.gjList.push(_data)

							// uni.setStorageSync('mapGJ', this.$helper.gjList);
							// console.log('this.$helper.gjList')
							// console.log(this.$helper.gjList)
							// console.log("条数", uni.getStorageSync('mapGJ').length)
							// if (uni.getStorageSync('mapGJ').length > 5) {
							// 	//存储轨迹经纬度list
							// 	that.$api.doRequest('post', '/trackDetailInfo/api/addTrackDetail', {
							// 			fillingId: _data.fillingId,
							// 			carNo: that.detailData.carNo,
							// 			// trackDetailInfos: JSON.stringify(uni.getStorageSync('mapGJ'))
							// 			trackDetailInfos: uni.getStorageSync('mapGJ')
							// 		}).then(res => {
							// 			that.polyline[0].points.push({
							// 				latitude: _data.latitude,
							// 				longitude: _data.longitude
							// 			});
							// 			console.log('上传经纬度list', res)
							// 			uni.hideLoading()
							// 			uni.removeStorageSync('mapGJ');
							// 			this.$helper.gjList = []
							// 		})
							// 		.catch(res => {
							// 			uni.showToast({
							// 				icon: "none",
							// 				title: res.message
							// 			})
							// 		});
							// }
							// }
							// );
							// uni.showToast({
							// 	title: "轨迹持续监控中！",
							// 	icon: "none",
							// 	complete() {
							// 		that.titleBtn = '结束轨迹'
							// 	}
							// })
						}
					})
					.catch(res => {
						uni.$u.toast(res.message);
					});


				if (this.titleBtn == "开始轨迹") {
					var that = this
					uni.showModal({
						content: "确定开始轨迹？",
						showCancel: true,
						confirmText: '确定',
						success: function(res) {
							if (res.confirm) {
								uni.setStorageSync('jyStartTime', timeInfo)
								// that.detailData.compId = uni.getStorageSync('pcUserInfo').compId
								// that.detailData.commonId = uni.getStorageSync('pcUserInfo').userId
								// that.detailData.driverName = uni.getStorageSync('userInfo').userName
								// that.detailData.trackFlag = "0"
								// that.detailData.fillingNo = "202207040001"
								// that.detailData.originProvince = "辽宁省"
								// that.detailData.originCity = "营口市"
								// that.detailData.originArea = "鲅鱼圈区"
								// that.detailData.originLongitude = "122.21"
								// that.detailData.originLatitude = "40.664"
								// that.$api.doRequest('post', '/fuelFillingInfo/api/addFilling',
								// 		that.detailData
								// 	)
								// 	.then(res => {
								// 		that.id = res.data.data
								// 		if (res.data.code == 200) {
								// 			that.$api.msg('提交成功')
								that.titleBtn = "结束轨迹"
								// 		} else {
								// 			that.$api.msg('提交失败')
								// 		}
								// 	})
							}
						}
					})
				} else {
					uni.navigateTo({
						url: '/pages/fuelfilling/apply_for_reimbursement?id=' + this.id
					})
				}
			},
		}
	}
</script>

<style lang='scss' scoped>
	page {
		background: #F5F6FA;
	}

	.title_b {
		margin: 20rpx 20rpx 0rpx 20rpx;
		padding: 20rpx 10rpx 20rpx 10rpx;
		font-size: 18px;
		font-weight: 550;
	}

	.c-row {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		/* 	padding: 20rpx 30rpx;
		margin: 20rpx 0; */


	}

	.con-list {
		-webkit-box-flex: 1;
		-webkit-flex: 1;
		flex: 1;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-orient: vertical;
		-webkit-box-direction: normal;
		-webkit-flex-direction: column;
		flex-direction: column;
		color: #303133;
		line-height: 40rpx;
		text-align: right;
		padding-right: 20rpx;
	}

	.wrap {
		background: #fff;
		padding: 40rpx 20rpx;
		box-sizing: border-box;
		height: 20vh;
	}

	.button {
		background: #22C572;
		width: 90%;
		margin: 40rpx auto 30rpx;
		padding: 10px;
		color: #fff;
		text-align: center;
		border-radius: 30px;
	}

	.button1 {
		background: #ff0000;
		width: 90%;
		margin: 40rpx auto 30rpx;
		padding: 10px;
		color: #fff;
		text-align: center;
		border-radius: 30px;
	}

	.button2 {
		background: #4089ff;
		width: 90%;
		margin: 40rpx auto 30rpx;
		padding: 10px;
		color: #fff;
		text-align: center;
		border-radius: 30px;
	}

	.buns_item {
		display: flex;
		padding: 80rpx 0 50rpx 0;
		justify-content: space-around;
	}

	.but_css {
		background: #22C572;
		width: 40%;
		padding: 20rpx;
		color: #fff;
		text-align: center;
		border-radius: 20rpx;
	}

	/deep/.u-radio-group {
		flex-direction: row-reverse;
	}

	.no-boder {
		border: 0;
	}

	.textarea {
		background: #F9F9FA;
		border: 1px solid #EEEEEE;
	}

	.map {
		width: 100vw;
		height: 80vh;

	}
</style>
