<template>
	<view>
		<map :latitude="detailData.originLatitude" :longitude="detailData.originLongitude" :markers="covers" class="map"
			:polyline="polyline"></map>
		<view class='wrap'>
			<view class="c-row">
				<view class="title">车牌号</view>
				<view class="con-list">
					<input v-model='detailData.carNo' placeholder="请输入车牌号" maxlength="7"></input>
				</view>
			</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" />
	</view>
</template>

<script>
	var that
	export default {
		data() {
			return {
				fillingId: '',
				polyline: [{ //指定一系列坐标点，从数组第一项连线至最后一项
					points: [],
					color: "#0000AA", //线的颜色
					width: 1, //线的宽度
					// 　　　　dottedLine:true,//是否虚线
				}],
				detailData: {
					carNo: '',
					travelStatus: '',
					originProvince: '',
					originCity: '',
					originArea: '',
					originLongitude: '',
					originLatitude: '',
					destinationProvince: '',
					destinationCity: '',
					destinationArea: '',
					destinationLongitude: '',
					destinationLatitude: '',
					trackFlag: '',
					compId: '',
					commonId: '',
					driverName: '',
					fillingNo: '',
					strokeType: '1',
				},
				covers: [],
				titleBtn: "开始轨迹",
			}
		},
		onLoad(options) {
			this.id = options.id
			that = this
		},
		onShow() {
			var that = this
			if (this.id) {
				this.seeInfo()
			} else {
				// #ifdef APP-PLUS
				this.getLngLat('开始轨迹');
				// #endif
			}
		},
		methods: {
			getLngLat(type) {
				this.checkOpenGPSServiceByAndroidIOS()
				var that = this
				uni.showLoading({
					title: '获取定位中',
					mask: true
				})
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: res => {
						if (res.latitude) {
							console.log("定位信息", res)
							if (type == '开始轨迹' || type == '已开始') {
								that.detailData.originLongitude = res.longitude;
								that.detailData.originLatitude = res.latitude;
								that.detailData.originProvince = res.address.province;
								that.detailData.originCity = that.$helper.filterUrban(res.address.city)
								that.detailData.originArea = that.$helper.filterUrban(res.address.district)
								that.detailData.originAddress = res.address.street + res.address.streetNum
							} else if (type == '结束轨迹') {
								that.detailData.destinationLongitude = res.longitude;
								that.detailData.destinationLatitude = res.latitude;
								that.detailData.destinationProvince = res.address.province;
								that.detailData.destinationCity = that.$helper.filterUrban(res.address.city)
								that.detailData.destinationArea = that.$helper.filterUrban(res.address
									.district)
								that.detailData.destinationAddress = res.address.street + res.address.streetNum
								that.detailData.trackFlag = "1"
								console.log(that.detailData)
								that.$api.doRequest('post', '/shortFillingInfo/api/addShortFilling', that
										.detailData)
									.then(res1 => {
										console.log(111)
										console.log(res1)
										if (res1.data.code == 200) {
											that.$api.msg('提交成功')
											uni.navigateTo({
												url: '/pages/shortDistance/short_distance_record'
											})
										} else {
											that.$api.msg('提交失败')
										}

									})
									.catch(res => {
										uni.$u.toast(res.message);
									});
							}

							this.covers = [{
								id: 0,
								latitude: res.latitude,
								longitude: res.longitude,
								iconPath: '../../../static/img/location.png',
							}]
							that.$forceUpdate()
							uni.hideLoading()
						} else {
							if (uni.getSystemInfoSync().platform == 'android') {
								var context = plus.android.importClass("android.content.Context");
								var locationManager = plus.android.importClass(
									"android.location.LocationManager");
								var main = plus.android.runtimeMainActivity();
								var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
								that.bool = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)
							}
							if (that.bool === false) {
								uni.showModal({
									title: '提示',
									content: '请打开定位服务',
									success: ({
										confirm,
										cancel
									}) => {
										if (confirm) {
											if (uni.getSystemInfoSync().platform == 'android') {
												var Intent = plus.android.importClass(
													'android.content.Intent');
												var Settings = plus.android.importClass(
													'android.provider.Settings');
												var intent = new Intent(Settings
													.ACTION_LOCATION_SOURCE_SETTINGS);
												var main = plus.android.runtimeMainActivity();
												main.startActivity(intent); // 打开系统设置GPS服务页面
											}
										}
									}
								});
								uni.hideLoading()
							}
						}
					},
					fail: res => {
						console.log('定位失败')
						console.log(res)
						uni.hideLoading()
					}
				});
			},
			checkOpenGPSServiceByAndroidIOS() {
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform === 'android') { // 判断平台
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager");
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: '提示',
							content: '请打开定位服务功能',
							// showCancel: false, // 不显示取消按钮
							success(res) {
								if (res.confirm) {
									if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
										var Intent = plus.android.importClass('android.content.Intent');
										var Settings = plus.android.importClass('android.provider.Settings');
										var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
										main.startActivity(intent); // 打开系统设置GPS服务页面
									}
								}
							}
						});
					}
				} else if (system.platform === 'ios') {
					// console.log("苹果");
					var cllocationManger = plus.ios.import("CLLocationManager");
					var enable = cllocationManger.locationServicesEnabled();
					var status = cllocationManger.authorizationStatus();
					plus.ios.deleteObject(cllocationManger);
					if (enable && status != 2) {
						console.log("手机系统的定位已经打开");
					} else {
						console.log("手机系统的定位没有打开");
						uni.showModal({
							title: '提示',
							content: '请前往设置-隐私-定位服务打开定位服务功能',
							// showCancel: false, // 不显示取消按钮
							success(res) {
								if (res.confirm) {
									var UIApplication = plus.ios.import("UIApplication");
									var application2 = UIApplication.sharedApplication();
									var NSURL2 = plus.ios.import("NSURL");
									// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
									// var setting2 = NSURL2.URLWithString("App-Prefs:root=LOCATION_SERVICES");
									// var setting2 = NSURL2.URLWithString("app-settings");
									var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
									// var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION_SERVICES");
									application2.openURL(setting2);
									plus.ios.deleteObject(setting2);
									plus.ios.deleteObject(NSURL2);
									plus.ios.deleteObject(application2);
								}
							}
						});
					}
				}
			},
			seeInfo() {
				this.$api.doRequest('get', '/shortFillingInfo/getShortFilling', {
					id: this.id
				}).then(res => {
					if (res.data.code == 200) {
						this.detailData = res.data.data
						if (this.detailData.travelStatus == "已开始") {
							this.titleBtn = "结束轨迹"
						} else if (this.detailData.travelStatus == "已结束") {
							this.titleBtn = "申请报销"
						}
						// #ifdef APP-PLUS
						this.getLngLat(this.detailData.travelStatus);
						// #endif
					}
				})
			},
			// 申请报销
			// reimbursement() {
			// 	uni.navigateTo({
			// 		url: '/pages/fuelfilling/apply_for_reimbursement?id=' + this.id
			// 	})
			// },
			// 结束轨迹
			endTrack() {
				if (that.$helper.fUN_AmapLocation) {
					that.$helper.fUN_AmapLocation.stop({}, result => {
						console.log('====fUN_AmapLocation定位stop====', JSON.stringify(result));
						// 更新轨迹结束地点
						// 更新结束地点位置
						this.getLngLat('结束轨迹')
					});
				}
			},
			//开始轨迹
			startTrack() {
				console.log('车牌号')
				console.log(this.detailData.carNo)
				if (!this.detailData.carNo) {
					uni.showToast({
						title: "车牌号不能为空！",
						icon: "none"
					})

					return
				}
				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)
				that.$api.doRequest('post', '/shortFillingInfo/api/addShortFilling', that.detailData).then(res1 => {
						console.log(111)
						console.log(res1)
						if (res1.data.code == 200) {
							console.log(222)
							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
									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.dtList.push(_data)

									uni.setStorageSync('mapDT', this.$helper.dtList);
									console.log('this.$helper.dtList')
									console.log(this.$helper.dtList)
									console.log("条数", uni.getStorageSync('mapDT').length)
									if (uni.getStorageSync('mapDT').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('mapDT')
											}).then(res => {
												that.polyline[0].points.push({
													latitude: _data.latitude,
													longitude: _data.longitude
												});
												console.log('上传经纬度list', res)
												uni.removeStorageSync('mapDT');
												this.$helper.dtList = []
											})
											.catch(res => {
												uni.showToast({
													icon: "none",
													title: res.message
												})
											});
									}
								}
							);
							uni.showToast({
								title: "轨迹持续监控中！",
								icon: "none",
								complete() {
									that.titleBtn = '结束轨迹'
								}
							})
						}
					})
					.catch(res => {
						uni.$u.toast(res.message);
					});
			},
		}
	}
</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;
		padding: 10px;
		color: #fff;
		text-align: center;
		border-radius: 30px;
	}

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

	.button2 {
		background: #4089ff;
		width: 90%;
		margin: 0 auto;
		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>
