<template>
	<view class="container">
		<map id="map" ref="map" style="width: 100%; height: calc(100vh + 50rpx);" scale="13" :markers="markers"
         longitude="112.83100231396601" latitude="36.872032399813556" show-location show-compass show-scale @markertap="markertap" >
		</map>
		<view class="zdxq">
      <view class="zdxqitem" @click="switch2Change('livestock')">
        <image src="../../static/zhandian_xuqin_dingwei.png" mode=""></image>
        <view class="textss">
          畜禽污染监测站
        </view>
      </view>
      <view class="zdxqitem" @click="switch2Change('orient')">
				<image src="../../static/zhandian_nongtian_dingwei.png" mode=""></image>
				<view class="textss">
					农田污染监测站
				</view>
			</view>
      <view class="zdxqitem" @click="switch2Change('watershed')">
        <image src="../../static/zhandian_xiaoliuyu_dingwei.png" mode=""></image>
        <view class="textss">
          小流域监测站
        </view>
      </view>
			<view class="zdxqitem" @click="switch2Change('soil')">
				<image src="../../static/iconsheturangzs.png" mode=""></image>
				<view class="textss">
					长期定位监测点
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/api'
	import configService from '@/common/service/config.service.js';

	export default {
		data() {
			return {
				baseUrl: configService.staticDomainURL,
				center: {
					latitude: 36.5,
					longitude: 111.7
				},
				scale: 14,
				markers: [],
        markersZIndex: 1,
				lastTap: '',
        stationList: [],
				cusLocationList: [],
				soilStationList: [],
        allStationList: [],
				stationTwoList: [],
				mapCtx: null // 添加地图上下文

			};
		},
		onLoad() {
		},
		onReady() {
			// 在onReady中初始化地图上下文
			this.mapCtx = uni.createMapContext('map', this);
		},
		onShow() {
      api.checkLogin(()=>{
        this.$nextTick(() => {
          this.getList()
        })
      }, () => {
        uni.reLaunch({
          url:'/packDetail/pages/login/login'
        })
      })
		},
		methods: {
			getList() {
				this.markers = []
				this.stationList = []
				this.cusLocationList = []
				this.soilStationList = []
				this.allStationList = []

				this.stationTwoList = []

				uni.showLoading({
					title: '加载中'
				});

				this.$http.get('/applet/survStationInfo/stationMap').then(res => {
          this.stationList = [...res.data.data.stationInfo];
          this.cusLocationList = [...res.data.data.cusLocation];
          this.soilStationList = [...res.data.data.deviceList];
          this.allStationList.push(...this.stationList);
          this.allStationList.push(...this.cusLocationList);
          this.allStationList.push(...this.soilStationList);
					// console.log("合并后的stationlist+++++", this.allStationList);
					// console.log("合并后的stationList+++++", this.stationList);
					// console.log("合并后的cusLocationList+++++", this.cusLocationList);
					// console.log("合并后的soilStationList+++++", this.soilStationList);
          //stationType: "orient" 农田
          //stationType: "livestock" 畜禽
          //stationType: "watershed"  小流域
					this.allStationList.forEach((item, index) => {
						item.id = index;
					});

					this.issscd = false
					this.isssscd = false
					this.isSoilShow = false
					this.enterpriseRender();// 企业渲染
					this.stationRender();// 站点渲染
					this.monitorRender() // 监测点渲染

					// 延迟执行以确保标记已经添加到地图
					setTimeout(() => {
						this.adjustMapToFitAllMarkers();
					}, 500);

					uni.hideLoading();
				})
			},
      enterpriseRender() {//企业点位地图渲染
        for (let i = 0; i < this.cusLocationList.length; i++) {
          const item = this.cusLocationList[i];
          item.iconPath = '/static/qiyeIcon.png';
          item.latitude = Number(item.stationLatitude);
          item.longitude = Number(item.stationLongitude);
          item.width = 35;
          item.height = 52;

          const markerItem = {
            id: item.id,
            iconPath: item.iconPath,
            latitude: item.latitude,
            longitude: item.longitude,
            width: item.width,
            height: item.height,
            customCallout: {
              anchorY: 0,
              anchorX: 0,
              display: 'ALWAYS'
            },
            stationType: item.stationType,
            stationName: item.stationName,
            stationCode: item.stationCode,
            joinCluster: false, //点聚合
            zIndex: this.markersZIndex,
          };
          this.markers.push(markerItem);
        }
      },
      stationRender() {// 站房点位置渲染
        // this.markers = this.markers.filter(item => item.stationType !== 'orient');
        if (!this.issscd) {
          for (let i = 0; i < this.stationList.length; i++) {
            const item = this.stationList[i];
            item.iconPath = this.baseUrl +'/'+ item.stationIcon;
            item.latitude = Number(item.stationLatitude);
            item.longitude = Number(item.stationLongitude);
            item.width = 239;
            item.height = 186;
            const markerItem = {
              id: item.id,
              iconPath: item.iconPath,
              latitude: item.latitude,
              longitude: item.longitude,
              width: item.width,
              height: item.height,
              customCallout: {
                anchorY: 0,
                anchorX: 0,
                display: 'ALWAYS'
              },
              stationType: item.stationType,
              stationName: item.stationName,
              stationCode: item.stationCode,
              joinCluster: false, //点聚合
              zIndex: this.markersZIndex + 1,
            };
            this.markers.push(markerItem);

          }
        }
      },
			monitorRender() {// 监测点位渲染
				this.soilStationList.forEach((item, index) => {
						let iconPath = '';
						let width = 35;
						let height = 35;
						// 根据设备类型设置不同的图标
						switch(item.type) {
							case 'soil':
								iconPath = this.baseUrl + '/icon/device/soil.png';
								width = 32;
								height = 47;
								break;
							case 'camera':
								iconPath = this.baseUrl + '/icon/device/cam.png';
								width = 45;
								height = 45;
								break;
							default:
								iconPath = this.baseUrl + '/icon/device/default.png';
						}
						const markerItem = {
							id: item.id,
							iconPath: iconPath,
							latitude: Number(item.latitude),
							longitude: Number(item.longitude),
							width: width,
							height: height,
							customCallout: {
								anchorY: 0,
								anchorX: 0,
								display: 'ALWAYS'
							},
							stationType: 'device',
							stationName: item.name,
							stationCode: item.ids,
							deviceType: item.type,
							joinCluster: false, //点聚合
              zIndex: this.markersZIndex,
						};
						this.markers.push(markerItem);
				});
			},
			markertap(e) {
				const index = e.detail.markerId
				const marker = this.markers.find(m => m.id === index);
				if (marker) {
					if (['orient', 'livestock'].includes(marker.stationType)) {
						uni.navigateTo({
							url: `/packDetail/pages/Site/detail?item=${encodeURIComponent(JSON.stringify(marker))}`
						})
					} else if (marker.stationType === 'device') {
						uni.navigateTo({
							url: `/packDetail/pages/vidio/soilindex`
						})
					}
				}
			},
			switch2Change(name) {// 焦点显示图例
				// 更新对应区域的状态
        //四种监测站:xuqin nongtian xiaoliuyu turang
        let that = this;
        if(name === that.lastTap){
          that.adjustMapToFitAllMarkers();
          that.lastTap = '';
        } else {
          // 聚焦到特定区域
          that.adjustMapToRegion(name);
          that.lastTap = name;
          // 或者使用更精确的方法：this.preciseMapAdjustment(name);

        }
			},
      // 调整地图视野以包含所有标记点（类似setFitView效果）
      adjustMapToFitAllMarkers() {
        if (this.mapCtx && this.markers.length > 0) {
          this.mapCtx.includePoints({
            points: this.markers.map(item => ({latitude: item.latitude, longitude: item.longitude})),
            padding: [60, 60, 60, 60] // 上下左右的边距
          });
        }
      },
      adjustMapToRegion(regionName) {
        // 调整地图视野到特定区域的标记点
        //stationType: "orient" 农田
        //stationType: "livestock" 畜禽
        //stationType: "watershed"  小流域
        let that = this;
        let points = [];
        let markers = [];
        that.markersZIndex ++;
        that.markersZIndex ++;
        if (regionName === 'orient' || regionName === 'livestock' || regionName === 'watershed') {
          // 获取团柏河区域的所有标记点
          markers = this.markers.filter(item => item.stationType === regionName);
        } else if (regionName === 'soil') {
          // 获取所有土壤设备标记点
          markers = this.markers.filter(item => item.type === 'soil' || item.deviceType === 'soil');
        }
        console.log(this.markers)
        if(markers.length > 0){
          points = markers.map(item => {
            item.zIndex = that.markersZIndex;
            return {
              latitude: Number(item.latitude || item.stationLatitude),
              longitude: Number(item.longitude || item.stationLongitude)
            }});
        }
        if (points.length > 0 && this.mapCtx) {
          this.mapCtx.includePoints({
            points: points,
            padding: [80, 110, 80, 110] // 增加边距以获得更好的显示效果
          });
        } else if (points.length === 0) {
          // 如果没有找到对应的标记点，显示提示
          // uni.showToast({
          //   title: `未找到${regionName}相关的监测点`,
          //   icon: 'none'
          // });
        }
      },
		}
	}
</script>

<style lang="scss">
	/* 样式保持不变 */
	.bgimg {
		position: fixed;
		// z-index: -99;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}

	.customCallout {
		width: 349rpx;
		height: 49rpx;
		color: #fff;
		font-size: 24rpx;
		text-shadow: 1rpx 2rpx 0rpx #0D1934;
		font-weight: bold;
		// background-image: url('@/static/zhandian_icon_nongtian_title.png');
		background-repeat: no-repeat;
		background-size: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.customCallout1 {
		width: 349rpx;
		height: 49rpx;
		color: #fff;
		font-size: 24rpx;
		text-shadow: 1rpx 2rpx 0rpx #0D1934;
		font-weight: bold;
		// background-image: url('@/static/zhandian_icon_xuqin_title.png');
		background-repeat: no-repeat;
		background-size: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.zdxq {
		position: fixed;
		left: 33rpx;
		bottom: 36rpx;
	}

	.zdxqitem {
		padding: 8rpx 0 7rpx 17rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 22rpx;
		font-family: Source Han Sans SC;
		font-weight: 500;
		color: #FFFFFF;
		text-shadow: 0rpx 1rpx 0rpx rgba(4, 49, 52, 0.55);
		width: 240rpx;
		background: rgba(0, 0, 0, 0.52);
		border: 1px solid #4B677C;
		border-radius: 6rpx;
		margin-bottom: 10rpx;
		position: relative;
	}

	.crildon {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		margin-right: 15rpx;
	}

	.zdxqitem:last-child {
		margin-bottom: 0;
	}

	.zdxqitem image {
		width: 33rpx;
		height: 50rpx;
		margin-right: 15rpx;
	}

	.zdxqitem:first-child image {
		width: 30rpx;
		height: 40rpx;
		margin-right: 15rpx;
	}

	.textss {
		flex: 1;
		text-align: left;
	}

	.imgs {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: -9;
	}

	.switchs {
		position: fixed;
		top: 36rpx;
		right: 40rpx;
		display: flex;
		align-items: center;
	}
</style>