<template>
	<view class="create-investigation">
		<top-title title="排查选择" class="custom_bg" :rightWidth='60'>

		</top-title>
		<view class="query-form" v-show="!pageFlag">
			<view class="tab">
				<view v-for="tabItem in tabList" :key="tabItem.active" :class="{
						'tab-item': true,
						'active': tabItem.active == approve
					}" @click="handleTabChange(tabItem.active)">
					<text>{{tabItem.name}}</text>
				</view>
			</view>
		</view>
		<view class="Content MarginAuto BorderBox" v-show="!pageFlag">
			<view class="List Width100 BorderBox" style="background: #fff;height: 80vh;margin-top: 20%;">
				<view class="formBox" v-show="approve == 1">
					<uni-forms border>
						<uni-forms-item label="路口名称" required class="label_item">
							<input type="text" :placeholder="'请输入路口名称'" class="label_input" v-model="roadName" />
						</uni-forms-item>
						<uni-forms-item label="路口位置" required class="label_item" style="border-bottom: 1px solid #eee;">
							<input type="text" :placeholder="'请在地图中选择'" class="label_input" style="padding-right: 30px;"
								:disabled="true" v-model="point1" />
							<cover-image src="../../static/map/d2.png" alt="" srcset="" class="label_img"
								@click="()=>handlePoint('point1')" />
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="formBox" v-show="approve == 2">
					<uni-forms border>
						<uni-forms-item label="路段名称" required class="label_item">
							<input type="text" :placeholder="'请输入路段名称'" class="label_input" v-model="roadName" />
						</uni-forms-item>
						<uni-forms-item label="起始位置" required class="label_item">
							<input type="text" :placeholder="'请在地图中选择'" class="label_input" :disabled="true"
								style="padding-right: 30px;" v-model="point1" />
							<cover-image src="../../static/map/d2.png" alt="" srcset="" class="label_img"
								@click="()=>handlePoint('point1')" />
						</uni-forms-item>
						<uni-forms-item label="终止位置" required class="label_item">
							<input type="text" :placeholder="'请在地图中选择'" class="label_input" :disabled="true"
								style="padding-right: 30px;" v-model="point2" />
							<cover-image src="../../static/map/d2.png" alt="" srcset="" class="label_img"
								@click="()=>handlePoint('point2')" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</view>
		</view>
		<view class="page-body" v-show='pageFlag'>
			<!-- <map :latitude="latitude" :longitude="longitude" :markers="markers" /> -->
			<map id="myMap" ref="myMaps" class="map" style="width: 100%; height: 100%" :scale="scale"
				:latitude="latitude" :longitude="longitude" :markers="markers" @regionchange="regionchange" />
			<cover-image class="curCenter" src="../../static/map/d3.png" alt="" srcset="" />
			<cover-view class="location">
				<cover-image src="../../static/map/3746.png" alt="" srcset="" @click="getCurCenter" />
			</cover-view>
		</view>
		<!-- <mapNavigation ref="mapNavigation" /> -->
		<view class="page-footer" v-if="pageFlag">
			<view>
				<view style="padding:10rpx 0 0 15rpx;">当前坐标：{{longitude.toFixed(6)}},{{latitude.toFixed(6)}}</view>
				<u-button type="primary" @click="handleAdd"
					style="width: 140rpx;background: #2663bf;height: 44rpx;position: absolute;right: 24rpx;top: 10rpx;">确定</u-button>
			</view>
			<change :sectionsList="sectionsList" @onSearch="onSearch" @changeCode="changeCode" />
		</view>
		<three class="footer-buttons" :type="'view'" first-text="取消" next-text="确认" :second-primary="true"
			@first="handleCancel" @last="handleCheck" v-else />
	</view>
</template>

<script>
	import TopTitle from "../../components/top-title.vue";
	import Three from "../../components/bottom-button/three.vue";
	import Change from "./Change.vue";
	import {
		locationRequest
	} from '@/libs/util/permission-request.js'
	import {
		wgs84LL2gcjLL2
	} from "@/pages/map/c.js";
	// import mapNavigation from "./map-navigation.vue";

	export default {
		components: {
			Change,
			TopTitle,
			Three,
			// mapNavigation
		},

		data() {
			return {
				latitude: 36.066006272609904, // 默认定在首都
				longitude: 120.38279699971847,
				scale: 17, // 默认16
				// markers: [],
				markerHeight: 60,
				isChanging: false,
				res: null,
				sectionsList: [],
				search: '',
				sectionCode: null,
				mapContext: null,
				timer: null,
				approve: 1,
				tabList: [{
						name: '新增路口',
						active: '1',
					},
					{
						name: '新增路段',
						active: '2',
					},
				],
				pageFlag: '',
				point1: '',
				point2: '',
				roadName: '',
			};
		},
		computed: {
			curSections() {
				return this.sectionsList.find(item => item.sectionCode == this.sectionCode) || {}
			},

			markers() {
				if (!this.sectionsList) {
					return
				}
				const sectionsMarker = this.sectionsList.map(item => {
					return {
						id: item.id,
						latitude: item.location.split(',')[1],
						longitude: item.location.split(',')[0],
						iconPath: "/static/icon/fill_position.svg",
					}
				})
				console.log('sectionsMarkersectionsMarkersectionsMarker', sectionsMarker)
				return sectionsMarker
			}
		},

		mounted() {
			this.mapContext = uni.createMapContext('myMap', this).$getAppMap()
		},
		methods: {
			handleCheck() {
				const {
					roadName,
					point1,
					point2,
					approve
				} = this
				if (!roadName) {
					return this.$.toast(`请输入${approve == 1?'路口':'路段'}名称`)
				}
				if (this.approve == 1) {
					if (!roadName) {
						return this.$.toast(`请输入路口名称`)
					}
					if (!point1) {
						return this.$.toast(`请选择路口位置`)
					}
				}
				if (this.approve == 2) {
					if (!roadName) {
						return this.$.toast(`请输入路段名称`)
					}
					if (!point1) {
						return this.$.toast(`请选择起始位置`)
					}
					if (!point2) {
						return this.$.toast(`请选择终止位置`)
					}
				}

				let position = point1
				if (point2) {
					position += ',' + point2
				}

				// 					let pages = getCurrentPages()
				// 					// 2. 上一页面实例
				// 					// 注意是length长度，所以要想得到上一页面的实例需要 -2
				// 					// 若要返回上上页面的实例就 -3，以此类推
				// 					let prevPage = pages[pages.length - 1]
				// 					console.log('prevPageprevPageprevPageprevPage',prevPage)
				// return
				// 					// 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
				// 					prevPage.$vm.setValue({
				// 						formData:{
				// 							name:'kang'
				// 						}
				// 					})
				uni.$emit('isRefresh', {
					roadName,
					position,
					approve,
				})
				uni.navigateBack()
				return
				// }
			},
			handlePoint(flag) {
				this.pageFlag = flag
			},
			handleTabChange(tabKey) {
				if (this.approve != tabKey) {
					this.approve = tabKey
					this.roadName = ''
					this.point1 = ''
					this.point2 = ''
				}
			},
			handleOpenMapNav() {
				if (!this.sectionCode) return this.$.toast('请选择路段或路口')
				this.$refs.mapNavigation.open({
					name: this.curSections.name,
					latitude: this.curSections.position[
						0].latitude,
					longitude: this.curSections.position[
						0].longitude
				})
			},
			handleCancel() {
				uni.navigateBack()
			},
			onSearch(value) {
				return
				this.search = value
				this.getList()
			},
			getCurCenter() {
				console.log('回到定位点')
				this.initPage(this.curSections)
			},
			handleAdd() {
				if (this.pageFlag == 'point1') {
					this.point1 = this.longitude.toFixed(6) + ',' + this.latitude.toFixed(6)
				} else if (this.pageFlag == 'point2') {
					this.point2 = this.longitude.toFixed(6) + ',' + this.latitude.toFixed(6)
				}
				this.pageFlag = ''
			},
			changeCode(code) {
				this.latitude = code.location.split(',')[1]
				this.longitude = code.location.split(',')[0]
				return
				if (this.pageFlag == 'point1') {
					this.point1 = this.longitude + ',' + this.latitude
				} else if (this.pageFlag == 'point2') {
					this.point2 = this.longitude + ',' + this.latitude
				}
				this.pageFlag = ''
			},
			// onConfirm() {
			// 	if (this.pageFlag == 'point1') {
			// 		this.point1 = this.latitude + ',' + this.longitude
			// 	} else if (this.pageFlag == 'point2') {
			// 		this.point2 = this.latitude + ',' + this.longitude
			// 	}
			// 	this.pageFlag = ''
			// },
			moveUserToMapViewCenter() {
				// #ifdef APP-PLUS
				this.mapContext.getCurrentCenter((state, point) => {
					if (state == 0) {
						const {
							longitude,
							latitude
						} = point
						let location = longitude.toFixed(6) + ',' + latitude.toFixed(6)
						// return
						this.$.showLoading()
						this.$request
							.globalRequest(
								`https://restapi.amap.com/v3/place/around?location=${location}&key=fbd17cb563bde2363b98aefc9dcfc5b9`, {},
								'GET').then(res => {
								// if (!res.pois) {
								// 	this.$.toast(res.info)
								// }
								this.$.hideLoading()
								// res = {
								// 	"suggestion": {
								// 		"keywords": [],
								// 		"cities": []
								// 	},
								// 	"count": "450",
								// 	"infocode": "10000",
								// 	"pois": [{
								// 		"parent": [],
								// 		"address": "中韩街道银川东路55号(崂山党校对面)",
								// 		"distance": "313",
								// 		"pname": "山东省",
								// 		"importance": [],
								// 		"biz_ext": {
								// 			"cost": [],
								// 			"rating": []
								// 		},
								// 		"biz_type": [],
								// 		"cityname": "青岛市",
								// 		"type": "商务住宅;楼宇;商务写字楼",
								// 		"photos": [{
								// 			"title": [],
								// 			"url": "http://store.is.autonavi.com/showpic/bb019677d47600e77d889492362db6c7"
								// 		}],
								// 		"typecode": "120201",
								// 		"shopinfo": "0",
								// 		"poiweight": [],
								// 		"childtype": [],
								// 		"adname": "崂山区",
								// 		"name": "昌盛·财富中心",
								// 		"location": "120.473844,36.110959",
								// 		"tel": [],
								// 		"shopid": [],
								// 		"id": "B0FFGAH04Q"
								// 	}, {
								// 		"parent": [],
								// 		"address": "银川东路与松岭路交叉口西北140米",
								// 		"distance": "768",
								// 		"pname": "山东省",
								// 		"importance": [],
								// 		"biz_ext": {
								// 			"cost": [],
								// 			"rating": []
								// 		},
								// 		"biz_type": [],
								// 		"cityname": "青岛市",
								// 		"type": "商务住宅;住宅区;住宅小区",
								// 		"photos": [{
								// 			"title": [],
								// 			"url": "http://store.is.autonavi.com/showpic/f674f519097b0177a8776737a282ad2a"
								// 		}],
								// 		"typecode": "120302",
								// 		"shopinfo": "0",
								// 		"poiweight": [],
								// 		"childtype": [],
								// 		"adname": "崂山区",
								// 		"name": "朱家洼小区",
								// 		"location": "120.479327,36.110854",
								// 		"tel": [],
								// 		"shopid": [],
								// 		"id": "B0FFG7XPX6"
								// 	}],
								// 	"status": "1",
								// 	"info": "OK"
								// },
								this.sectionsList = res.pois;
							}).catch(err => {
								console.log(err, 'errerrerrerrerrerrerrerr')
							})
						// https://restapi.amap.com/v3/place/text?keywords=北京大学&city=beijing&offset=20&page=1&key=<用户的key>&extensions=all 

						this.latitude = point.latitude
						this.longitude = point.longitude
						clearTimeout(this.timer)
						this.timer = setTimeout(() => {
							this.getList();
						}, 500)
					}
				})
				// #endif
			},
			regionchange(e) {
				// if(!this.pageFlag){
				// 	return
				// }
				console.log('地图视野变化')
				this.moveUserToMapViewCenter()
			},
			getList() {
				return
				if (!this.longitude || !this.latitude) {
					return
				}
				this.sectionCode = null
				this.sectionsList = []
				let location = this.longitude.toFixed(6) + ',' + this.latitude.toFixed(6)
				const data = {
					location,
					key: 'fbd17cb563bde2363b98aefc9dcfc5b9'
				};
				if (this.pageFlag) {
					this.$.showLoading()
				}
				this.$request
					.globalRequest(
						`https://restapi.amap.com/v3/place/around`, data,
						'GET').then(res => {
						if (res.code === 200) {
							console.log('返回数据2222222222222', res)
							this.sectionsList = res.pois;
						} else {
							this.$.toast(res.message)
						}
					}).catch(err => {
						console.log(err, 'errerrerrerrerrerrerrerr')
					})
				// this.$request
				// 	.globalRequest('/hiddenDanger/highDanger/getNearRoadInfo?pageNum=1&pageSize=10', data, 'POST')
				// 	.then(res => {
				// 		if (res.code === 200) {
				// 			console.log('返回数据', res)
				// 			this.sectionsList = res.result;
				// 			if (this.sectionsList.length) {
				// 				this.sectionCode = this.sectionsList[0].sectionCode
				// 			}
				// 		} else {
				// 			this.$.toast(res.message)
				// 		}
				// 	}).finally(() => {
				// 		this.search = ''
				// 		this.$.hideLoading()
				// 	})
			},
			async initPage() {
				// #ifdef H5

				// #endif
				// #ifdef APP-PLUS
				try {
					console.log('trytrytrytrytrytrytry')
					const locationInfo = await locationRequest()
					const [longitude, latitude] = wgs84LL2gcjLL2(locationInfo.longitude, locationInfo.latitude);
					this.longitude = longitude
					this.latitude = latitude
				} catch (e) {
					console.log('errerrerrerrerrerr', err)
					//TODO handle the exception
				}
				// #endif
				// #ifdef H5
				this.getList()
				// #endif
				// 当前中心点变化，自动调取接口 见moveUserToMapViewCenter
				// this.getList()
			}
		},
		onLoad(e) {
			console.log('2222222222222222222222222')
			console.log('eeeeeeeeeeeeeeeeeeeeeeeee', e)

			// const pages = getCurrentPages();
			// const prevPage = pages[pages.length - 2];  // 上一个页面实例对象
			// prevPage.setData({  // 假设上一页面有个data属性需要更新
			//   someData: 'new value'
			// });
			// uni.navigateBack()
			this.initPage()
		}
	}
</script>

<style lang="scss" scoped>
	.label_item {
		white-space: nowrap;
		height: 36px;
		padding: 36rpx 28rpx;
		position: relative;
	}

	.label_input {
		font-size: 14px;
		height: 36px;
		text-align: right
	}

	.label_img {
		width: 26px;
		height: 26px;
		position: absolute;
		right: 0px;
		top: 0;
	}

	.create-investigation {
		height: 100vh;
		width: 100vw;
		display: flex;
		flex-direction: column;
		background: #F0F2F7;

		.right-dh {
			display: inline-block;
			width: 30px;
			height: 30px;
		}

		.page-body {
			width: 100%;
			padding-top: calc(var(--status-bar-height) + 88rpx);
			//height     : calc(100vh - var(--status-bar-height) - 88rpx);
			position: relative;
			z-index: 1;
			flex: 1;

			.map {
				width: 100vw;
				height: 100%;
			}

			.curCenter {
				position: absolute;
				width: 30px;
				height: 30px;
				z-index: 9999;
				left: 50%;
				top: 50%;
				transform: translate(-15px, -15px);
				background: transparent;
			}

			.location {
				position: absolute;
				width: 48px;
				height: 48px;
				display: flex;
				align-items: center;
				justify-content: center;
				right: 24rpx;
				bottom: 24rpx;
				background: #fff;
				border-radius: 16px;
				z-index: 99999;

				cover-image {
					width: 32px;
					height: 32px;
				}
			}

		}

		.page-footer {
			width: 100vw;
			//z-index: 9999999999999;
			overflow: visible;
			position: relative;


			.init-content {
				background: #ffffff;
				width: calc(100vw - 32rpx);
				margin: 0 auto;

				.footer-content {
					padding: 32rpx 0;
					text-align: center;
					display: block;

					.title {
						text-align: center;
						font-size: 28rpx;
						color: #777777;
					}

					.position-name {
						font-size: 36rpx;
						color: #333333;
						padding: 24rpx 0;
						display: block;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}

				.footer-buttons {
					width: calc(100% - 72rpx);
					margin-top: 0;
				}
			}
		}
	}

	.Content {
		width: calc(100% - 48rpx);
		padding-bottom: 88rpx;
	}

	.label-box {
		display: flex;
		align-items: center;
		height: 110rpx;
		font-size: 30rpx;
		font-weight: 600;

		.border {
			background-color: #2663BF;
			height: 35rpx;
			width: 6rpx;
			margin-right: 14rpx;
		}
	}

	.query-form {
		width: 100%;
		font-size: 16px;
		background: #ffffff;
		box-shadow: 3px 0px 10px #ccc;
		color: #666666;
		position: sticky;
		// top: var(--status-bar-height + 88rpx);
		top: calc(var(--status-bar-height) + 88rpx);
		z-index: 10;

		.tab {
			display: flex;
			align-items: center;
			justify-content: space-around;

			.tab-item {
				position: relative;
				height: 41px;
				line-height: 41px;
				padding: 0 30rpx 0 30rpx;
				border-bottom: 3px solid #fff;
				display: flex;
				align-items: center;

				&.active {
					color: rgb(60, 109, 195);
					border-color: rgb(60, 109, 195);
				}

				.number {
					font-weight: bold;
					font-size: 18px;
					margin-left: 10rpx;
				}
			}
		}


	}
</style>
<style lang="scss">
	.amap-logo,
	.amap-copyright {
		display: none !important;
	}
</style>