<template>
	<view class="map">
		<view class="page-body">
			<view class="page-section page-section-gap">
				<map id="map" style="width: 100%; height: 300px;" show-scale="true" show-location="true"
					:circles="circleArray" @regionchange="onRegionchange" scale='14' :latitude="latitude"
					:longitude="longitude" :markers="markers">
				</map>
				<cover-image class="img-map2" src="../../static/campus/orientation.png" @click="clickcontrol"></cover-image>
			</view>

		</view>
		<view>
			<uni-card title="当前位置实时信息">
				 <view style="color: #000;font-weight: bold;">经纬度:<text style="color: #6A6A6A;">{{ `（${latitude}，${longitude}）` }}</text></view>
				 <view style="color: #000;font-weight: bold;">详细地址:<text style="color: #6A6A6A;">{{ address }}</text></view>
				 <view style="height: 100px;display: flex;">
				 	<u-upload width="80px" height="80px" :fileList="fileList3" @afterRead="afterRead" @delete="deletePic"
				 	  	@clickPreview="clickPreview" name="3" multiple :maxCount="1"  ></u-upload>
				 </view>
			</uni-card>			
		</view>
		<view style="text-align: center;">
			<!-- <view v-if="distance > 500 || distance === ''" class="punchabsent">未在范围内</view> -->
			<view  class="punch" @click="tapScan">打卡</view>
			<view style="color: red">{{ codeText }}</view>
			<view style="color: red">{{ codeTime }}</view>
		</view>
		
	</view>
</template>

<script>
	// let QQMapWX = require("../utils/qqmap-wx-jssdk.min.js")
	// import QQMapWX from "../utils/qqmap-wx-jssdk.js"
	const QQMapWX = require('@/utils/qqmap-wx-jssdk.js')
	import {
		postIotserver
	} from '@/api/login';
	import {
		mapGetters
	} from 'vuex';
	import {
		timestampFormatTime
	} from '@/utils/index.js';
	export default {
		data() {
			return {
				fileList3: [],
				baseURl: 'https://www.lonsungsh.com:8083',
				imageID: [], //上传图片的id集合
				imageUrlsDate: [],
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 0, //纬度
				longitude: 0, //经度			
				markers: [{
					id: 0,
					latitude: 0,
					longitude: 0,
					width: 15,
					height: 20,
					callout: {
						content: '已进入打卡范围',
						color: '#FFFFFF',
						fontSize: 12,
						borderColor: '#69BFBE',
						bgColor: '#69BFBE',
						padding: 5,
						borderRadius: 3,
						display: 'ALWAYS',
						textAlign: 'center',
					}
				}],
				address: '',
				// 圆圈的范围
				circleArray: [],
				codeText: '',
				codeTime: '',
				distance: undefined,
				qqmapsdk: null
			}
		},
		onLoad() {
			this.qqmapsdk = new QQMapWX({
				key: 'IBCBZ-W5C3W-X32R4-35XWR-SK5E2-BIFDO'
			})

		},
		computed: {
			// 拿取vuex数据
			...mapGetters({
				userInfo: 'users/getLoginInfo',
				schoolInfo: 'users/getschoolList',
			})
		},
		created(){
			// uni.chooseLocation({
			// 	success(res) {
			// 		console.log(res);
			// 	}
			// })
			var obj = {
				// 模拟环创企业广场
				// latitude: 28.36121,
				// longitude: 112.8179,
				// 模拟荣盛花语		
				// latitude: 28.228445,
				// longitude: 112.877754,
				latitude: this.schoolInfo.latitude?this.schoolInfo.latitude:'',
				longitude: this.schoolInfo.longitude?this.schoolInfo.longitude:'',
				radius: 500,
				fillColor: '#69BFBE6A',
				color: '#acb0b7',
				strokeWidth: 2
			}
			this.circleArray.push(obj)
			console.log(this.circleArray);
			uni.authorize({
				scope: "scope.userLocation",
				success: (res) => {
					wx.getLocation({
						isHighAccuracy: true, // 开启地图精准定位
						altitude: true,
						type: 'gcj02', // 地图类型写这个
						success: (res) => {
							uni.showLoading({
								title: '定位中...',
								mask: true,
							})
							console.log(res);
							setTimeout(() => {
								    this.latitude = Number(res.latitude.toFixed(6)),
									this.longitude =Number( res.longitude.toFixed(6))
									this.qqmapsdk.reverseGeocoder({
										 location:{
											  latitude:res.latitude,
											  longitude:res.longitude
										 },
										 success:(data)=>{
											 this.address = data.result.formatted_addresses.recommend;
											 // this.latitude = data.location.lat,
											 // this.longitude = data.location.lng
										 }
									})
								uni.hideLoading()
								const distance = this.getDistance(this.circleArray[0]
									.latitude, this
									.circleArray[0].longitude, this.latitude, this.longitude)
								console.log(distance.m);
								this.distance = distance.m
							}, 1000)
						},

					});
				}
			})
		},
		onShow() {},
		methods: {
			onRegionchange(e) {},
			clickcontrol: function() {
				uni.createMapContext("map").moveToLocation({ //moveToLocation将地图中心移动到当前定位点，需要配合map组件的show-location使用
					latitude: this.latitude,
					longitude: this.longitude,
				});
			},
			deletePic(event) {
				const keyDelete = event.index
				let UrlsDateLIst = this.imageUrlsDate.filter((value, index, arr) => index !== keyDelete);
				this.imageUrlsDate = UrlsDateLIst;
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			clickPreview(event) {
				// console.log(111);
				const {index} = event.currentTarget.dataset
				console.log(index);
				uni.previewImage({
					urls: this.imageUrlsDate,
					current: this.imageUrlsDate
				})
				
			},
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				var that = this;
				const picUploadData = {
					creator: that.userInfo.name,
					business: 'school.revise',
					type: 'image',
					deviceid: that.userInfo.id,
					createtime: timestampFormatTime(),
					description: '',
					comment: ''
				};
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.baseURl + '/mdev/picture/upload',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data;charset=utf-8'
						},
						formData: {
							jsondata: JSON.stringify(picUploadData),
						},
						success: (res) => {
							setTimeout(() => {
								const resImage = JSON.parse(res.data)?.data;
								console.log(resImage);
								if (!that.imageUrlsDate.includes(resImage.uri)) {
									that.imageUrlsDate.push(resImage.uri);
								}
								if (!that.imageID.includes(resImage.id)) {
									that.imageID.push(resImage.id);
								}
								
								resolve(that.imageUrlsDate,that.imageID)
							}, 1000)
			
						}
					});
				})
			},
			tapScan() {
				let _this = this;
				if(this.fileList3.length > 0){
					wx.scanCode({
					success: function(res) {
						if (res.result) {
							const datalist = {
								tagId: res.result,
								personId: _this.userInfo.id ? _this.userInfo.id : Math.round(Math.random() * 1000000),
								personName: _this.userInfo.name,
								personType: _this.userInfo.personType,
								longitude: _this.longitude,
								latitude: _this.latitude,								
								address:_this.address,
								images: JSON.stringify(_this.imageID),
								imageUrls: JSON.stringify(_this.imageUrlsDate),
							};
							if (_this.userInfo.name) {
								postIotserver(datalist)
									.then((res) => {
										console.log(res.data.station, '222');
										const innerAudioContext = uni.createInnerAudioContext();
										innerAudioContext.autoplay = true;
										innerAudioContext.src = require('@/static/video/video.wav'); //音频地址
										innerAudioContext.onPlay(() => {
											console.log('开始播放');
										});
										_this.codeText = res.data.station + '---打卡成功'
										_this.codeTime = '当前时间:' + timestampFormatTime()
									})
									.catch((err) => {
										console.log(err, '5555');
										uni.showToast({
											title: err.msg + '请不要重复打卡'
										});
									});
							} else {
								uni.showToast({
									title: '请登录账户'
								});
							}
						}
					}
				}); 
				}else{
					uni.showToast({
						title: '请先上传照片'
					});  
				}
			},
			getDistance(la1, lo1, la2, lo2) {
				console.log(la1, lo1, la2, lo2);
				let La1 = la1 * Math.PI / 180.0;
				let La2 = la2 * Math.PI / 180.0;
				let La3 = La1 - La2;
				console.log(La3);
				let Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(
					Math.sin(
						Lb3 / 2), 2)));

				s = s * 6378.137;
				s = Math.round(s * 10000) / 10000;
				console.log(s, Math.round(s * 1000));
				return {
					km: s,
					m: Math.round(s * 1000)
				};
			}
		},
	}
</script>

<style lang="scss">
	.map {
		position: relative;

		.img-map2 {
			width: 60rpx;
			height: 60rpx;
			position: fixed;
			top: 0;
			right: 1vh;
			background-color: #FFFFFF;
			border-radius: 5px;
		}
		.punchabsent {
			text-align: center;
			width: 100px;
			height: 100px;
			border: 4px solid #ff0000;
			border-radius: 50%;
			line-height: 100px;
			position: absolute;
			left: 50%;
			margin-left: -53px;
			margin-top: 50px;
		}

		.punch {
			text-align: center;
			width: 100px;
			height: 100px;
			border: 4px solid #cfb56a;
			border-radius: 50%;
			line-height: 100px;
			position: absolute;
			left: 50%;
			margin-left: -53px;
			margin-top: 50px;
		}
	}
</style>