<template>
	<view class="create-investigation">
		<top-title title="排查选择" class="custom_bg" :rightWidth='60'>
			<template slot="right">
				<image src="/static/map/daohang.png" class="right-dh" mode="" @click="handleOpenMapNav">
				</image>
			</template>
		</top-title>

		<view class="page-body">
			<!-- <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,currentPoint]" :polyline="polyline"
				@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">
			<view class="init-content" v-if="!isChanging">
				<view class="footer-content" v-if="customData.name">
					<text class="title">根据当前定位信息，您要排查的是这{{customData.type == 1?'个路口':'条路段'}}吗？</text>
					<text class="position-name">{{customData.name}}</text>
				</view>
				<view class="footer-content" v-else>
					<text class="title">根据当前定位信息，您要排查的是这{{curSections.type == 1?'个路口':'条路段'}}吗？</text>
					<text class="position-name">{{curSections.name || '未选择'}}</text>
				</view>
				<three class="footer-buttons" first-text="更换" second-text="向导模式" next-text="自主模式" :second-primary="true"
					@first="isChanging = true" @second="handleSecond" @last="nextStep" />
			</view>
			<change :sectionsList="sectionsList" @onSearch="onSearch" @changeCode="changeCode" v-else />
		</view>
	</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,
				// polyline: [],
				customData: {},
				currentPoint: {}
			};
		},
		computed: {
			curSections() {
				return this.sectionsList.find(item => item.sectionCode == this.sectionCode) || {}
			},
			polyline() {
				if (this.customData.name) {
					const {
						type,
						position
					} = this.customData
					if (type == 2) {
						return [{
							arrowLine: true,
							color: "#CC2936",
							width: 8,
							points: [{
									longitude: position.split(',')[0],
									latitude: position.split(',')[1]
								},
								{
									longitude: position.split(',')[2],
									latitude: position.split(',')[3]
								}
							]
						}]
					}
					return []
				}
				const arr = this.sectionsList.filter(item => item.type == 2).map(item => ({
					id: item.sectionCode,
					name: item.name,
					arrowLine: true,
					color: item.sectionCode == this.sectionCode ? "#CC2936" : '#4588E6',
					width: 8,
					id: 1,
					points: item.position,
				}))

				console.log('arrarrarrarrarr', arr)
				return arr
			},
			markers() {
				if (this.customData.name) {
					const {
						type,
						position
					} = this.customData
					if (type == 1) {
						return [{
							latitude: position.split(',')[1],
							longitude: position.split(',')[0],
							iconPath: "/static/icon/fill_position.svg",
						}]
					}
					return []
				}
				const sectionsMarker = this.sectionsList.filter(item => item.type == 1).map(item => {
					return {
						id: item.sectionCode,
						latitude: item.position[0].latitude,
						longitude: item.position[0].longitude,
						iconPath: "/static/icon/fill_position.svg",
					}
				})
				return sectionsMarker
			}
		},
		mounted() {
			this.mapContext = uni.createMapContext('myMap', this).$getAppMap()
			this.mapContext.onclick = (point) => {
				this.longitude = point.longitude
				this.latitude = point.latitude

				// const sectionsMarker = this.sectionsList.filter(item => item.type == 1).map(item => {
				// 	return {
				// 		id: item.sectionCode,
				// 		latitude: item.position[0].latitude,
				// 		longitude: item.position[0].longitude,
				// 		iconPath: "/static/icon/fill_position.svg",
				// 	}
				// })
				this.currentPoint = {
					latitude: point.latitude,
					longitude: point.longitude,
					iconPath: "/static/map/d3.png",
				}


				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.getList();
				}, 500)
			}
		},
		methods: {
			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
				})
			},
			onSearch(value) {
				this.search = value
				this.getList()
			},
			getCurCenter() {
				console.log('回到定位点')
				this.initPage(this.curSections)
			},
			handleSecond() {
				if (this.customData.name) {
					const {
						name,
						type,
						position
					} = this.customData
					this.$.open(
						"/pages/index/detail?taskId=" +
						'' +
						"&id=" +
						'' +
						"&sectionId=" +
						'' +
						"&roadName=" +
						name +
						"&userId=" +
						'' +
						"&deptId=" +
						'' +
						"&sectionType=" +
						type +
						"&coordinate=" +
						position +
						"&isCustom=" +
						'1'
					);
					return
				}
				if (!this.sectionCode) return this.$.toast('请选择路段或路口')
				this.$.open(
					"/pages/index/detail?taskId=" +
					'' +
					"&id=" +
					this.sectionCode +
					"&sectionId=" +
					this.sectionCode +
					"&roadName=" +
					this.curSections.name +
					"&userId=" +
					'' +
					"&deptId=" +
					'' +
					"&sectionType=" +
					this.curSections.type
				);
			},
			nextStep() {
				if (this.customData.name) {
					const {
						name,
						type,
						position
					} = this.customData
					this.$.open("/pages/investigation/task" + "?id=" + '' +
						'&sectionId=' + '' +
						'&taskName=' + name +
						'&type=' + 'add' +
						'&sectionCode=' + '' + '&sectionType=' + type + '&latitude=' +
						position.split(',')[1] + '&longitude=' + position.split(
							',')[0] + '&position=' + position
					);
				} else {
					const section = this.sectionsList.filter(i => i.sectionCode == this.sectionCode)
					if (!section) return this.$.toast('坐标信息获取失败')
					const {
						position
					} = section[0]
					if (!position) return this.$.toast('坐标信息获取失败')
					const {
						latitude,
						longitude
					} = position[0]
					if (!latitude || !longitude) return this.$.toast('坐标信息获取失败')
					if (!this.sectionCode) return this.$.toast('请选择路段或路口')
					this.$.open("/pages/investigation/task" + "?id=" + '' +
						'&sectionId=' + this.sectionCode +
						'&taskName=' + this.curSections.name +
						'&type=' + 'add' +
						'&sectionCode=' + this.sectionCode + '&sectionType=' + this.curSections.type +
						'&latitude=' +
						latitude + '&longitude=' + longitude);
				}
			},
			changeCode(code) {
				this.sectionCode = code
				this.isChanging = false
			},
			moveUserToMapViewCenter() {
				// #ifdef APP-PLUS
				this.mapContext.getCurrentCenter((state, point) => {
					if (state == 0) {
						console.log('当前地图中心点', point)
						// https: restapi.amap.com/v3/place/around?location=120.435904,36.167341&key=53ab1f73d92932ae491775223381c09a
						// this.$request
						// .globalRequest(
						// 	'https://restapi.amap.com/v3/place/text?keywords=北京大学&city=beijing&offset=20&page=1&key=	53ab1f73d92932ae491775223381c09a&extensions=all', {},
						// 	'GET').then(res => {
						// }).catch(err => {
						// 	console.log('errerrerrerrerrerrerrerr', err)
						// })

						if (!Object.keys(this.currentPoint).length) {
							this.currentPoint = {
								latitude: point.latitude,
								longitude: point.longitude,
								iconPath: "/static/map/d3.png",
							}
							clearTimeout(this.timer)
							this.timer = setTimeout(() => {
								this.getList();
							}, 500)
						}

						// this.latitude = point.latitude
						// this.longitude = point.longitude
						// clearTimeout(this.timer)
						// this.timer = setTimeout(() => {
						// 	this.getList();
						// }, 500)
					}
				})
				// #endif
			},
			regionchange(e) {
				console.log('地图视野变化地图视野变化地图视野变化')
				if (this.customData.name) {
					return
				}
				this.moveUserToMapViewCenter()
			},

			getList() {
				if (!this.longitude || !this.latitude) {
					return
				}
				this.sectionCode = null
				this.sectionsList = []
				const data = {
					x: this.longitude,
					y: this.latitude,
					search: this.search
				};
				this.$.showLoading()
				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 {
					const locationInfo = await locationRequest()
					const [longitude, latitude] = wgs84LL2gcjLL2(locationInfo.longitude, locationInfo.latitude);
					this.longitude = longitude
					this.latitude = latitude
				} catch (e) {
					//TODO handle the exception
				}
				// #endif
				// #ifdef H5
				this.getList()
				// #endif
				// 当前中心点变化，自动调取接口 见moveUserToMapViewCenter
				// this.getList()
			}
		},
		onLoad() {
			this.initPage()
			uni.$off()
			uni.$on('isRefresh', (data) => {
				console.log('监听到事件来自返回的参数：', data);
				const {
					approve,
					roadName,
					position
				} = data
				this.customData = {
						type: approve,
						name: roadName,
						position: position,
						customFlag: true
					},
					this.isChanging = false

				this.longitude = position.split(',')[0]
				this.latitude = position.split(',')[1]
				this.sectionCode = ''
				this.sectionsList = []
			})
		}
	}
</script>

<style lang="scss" scoped>
	.create-investigation {
		height: 100vh;
		width: 100vw;
		display: flex;
		flex-direction: column;

		.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;
			min-height: 280rpx;
			//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;
				}
			}
		}
	}
</style>
<style lang="scss">
	.amap-logo,
	.amap-copyright {
		display: none !important;
	}
</style>