<template>
	<view class="page">
		<u-navbar title="电子围栏" :border-bottom="false" :background="bgc" title-color='#000' title-size='36'
			height='45'></u-navbar>
		<custom-map :areaInfo="areaInfo" @on-polygon-complete="handlePolygonComplete"></custom-map>
	</view>
</template>

<script>
import CustomMap from '../gongzuotai/components/CustomMap.vue'
export default {
	components: {
		CustomMap
	},
	data() {
		return {
			bgc: {
				backgroundColor: "#fff",
			},
			areaId: '',
			areaInfo: {}
		}
	},
	onLoad(e) {
		if (e.areaId) {
			this.areaId = e.areaId
			this.getArea()
		}
	},
	methods: {
		getArea() {
			this.$u.get(`/bst/area/${this.areaId}`).then((res) => { 
				if (res.code == 200) {
					this.areaInfo = res.data
				} else {
					uni.showToast({
						title: res.msg || '获取区域信息失败',
						icon: 'none'
					})
				}
			}).catch(error => {
				uni.showToast({
					title: '获取区域信息失败',
					icon: 'none'
				})
			});
		},
        
		
	    // 计算多边形中心点
	    calculateCenter(path) {
	      if (!path || path.length === 0) return null;
	      let total = path.length;
	      let X = 0, Y = 0, Z = 0;
	      path.forEach(point => {
	        let lng = (point[0] * Math.PI) / 180;
	        let lat = (point[1] * Math.PI) / 180;
	        let x = Math.cos(lat) * Math.cos(lng);
	        let y = Math.cos(lat) * Math.sin(lng);
	        let z = Math.sin(lat);
	        X += x;
	        Y += y;
	        Z += z;
	      });
	      X = X / total;
	      Y = Y / total;
	      Z = Z / total;
	      let Lng = Math.atan2(Y, X);
	      let Hyp = Math.sqrt(X * X + Y * Y);
	      let Lat = Math.atan2(Z, Hyp);
	      return [
	        (Lng * 180) / Math.PI,
	        (Lat * 180) / Math.PI
	      ]
	    },

		
		handlePolygonComplete(data) {
			console.log(data,'datadata');
			// 构造边界字符串
			const boundaryStr = data.points.map(point =>
				`[${point.longitude},${point.latitude}]`
			).join(',')
			let arr = JSON.parse(`[${boundaryStr}]`)
			let center = this.calculateCenter(arr) // 计算多边形中心点
			this.areaInfo.longitude = center[0]
			this.areaInfo.latitude = center[1]
			console.log(center,'center');
            
			// 构造请求数据
			const params = {
				...this.areaInfo,
				boundaryStr:   `[${boundaryStr}]` // 直接使用 boundaryStr
			}
			// 发送保存请求
			this.$u.put('/bst/area', params).then(res => {
				if (res.code === 200) {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res.msg || '保存失败',
						icon: 'none'
					})
				}
			}).catch(() => {
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			})
		}
	}
}
</script>

<style lang="scss">
page {
	width: 100%;
	height: 100%;
}

.page {
	width: 100%;
	height: 100%;
}
 </style>