<template>
	<view class="home-wrap base-container">
		<view class="home-top">
			<view class="home-search">
				<view class="search-wrap">
					<up-search placeholder="搜索品种" v-model="typeSearch"></up-search>
				</view>
			</view>
			<!-- <map
			    id="mapId"
			    :latitude="latitude"
			    :longitude="longitude"
				:scale="scale"
			    @markertap="onMarkerTap"
			    @callouttap="onCalloutTap"
			    @labeltap="onLabelTap"
			    :markers="markers"
			    :include-points="includePoints"
				:enable-poi="false"
				:enable-traffic="false"
				:enable-satellite="true"
				:enable-building="false"
			    show-location
			    style="width: 100%; height: 280rpx;clip-path: inset(0rpx round 16rpx);"
			  ></map> -->
			  <video src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/map-video.mp4" object-fit="cover" :show-fullscreen-btn="false"
			  	:autoplay="true" class="map-video" loop muted :show-progress="false" :show-play-btn="false">
			  </video>
			<view class="map-tips" @click="toPage('allGardenMap')">
				飞鸟入驻管理果场详情，点击查看
			</view>
		</view>
		<view class="type-wrap">
			 <up-scroll-list indicatorColor="#F3C11D33" indicatorActiveColor="#F3C11D" :indicatorWidth="30" :indicatorBarWidth="13">
				<view class="item-type">
					<image class="type-img" :src="`${config.BASIC_IMG}home/type-icon.png`" alt="" />
					<view class="type-text">
						全部
					</view>
				</view>
				<view class="item-type" v-for="(item, index) in typeList" :key="index">
					<image class="type-img" :src="item.image" alt="" />
					<view class="type-text">
						{{item.name}}
					</view>
				</view>
				
			</up-scroll-list>
		</view>
		<!-- 好味热卖 -->
		<view class="home-hot">
			<hot-component-vue :farmId="766"></hot-component-vue>
		</view>
		
		<!-- 有味果园 -->
		<view class="garden-wrap">
			<view class="garden-content">
				<view class="hot-title">
					<view class="title-l">
						有味果园
					</view>
					<view class="title-btn" @click="toPage('gardenList')">
						查看全部<up-icon size="10" name="arrow-right"></up-icon>
					</view>
				</view>
				<view class="garden-list">
					<view
						class="garden-item"
						v-for="farm in gardenList"
						:key="farm.farmId || farm.id"
						@click="goGardenItem(farm)"
					>
						<view class="garden-l" v-if="farm.coverVideo">
							<video :src="farm.coverVideo" :show-progress="false" :show-play-btn="false"
								:show-center-play-btn="false" object-fit="cover" :show-fullscreen-btn="false"
								 disablePictureInPicture :autoplay="true" class="video-dom"
								loop muted>
							</video>
						</view>
						<view class="garden-l" v-else>
							<image class="garden-img" :src="`${config.BASIC_IMG}home/garden.png`" mode=""></image>
							<text class="img-text">无人机实拍视频</text>
						</view>
						<view class="garden-r">
							<view class="garden-title">
								{{ farm.name }}
							</view>
							<view class="garden-info">
								品种：荔枝（{{ farm.pz }}）
							</view>
							<view class="garden-info">
								位置：{{ (farm.cityName + farm.countyName) || '—' }}
							</view>
							<view class="garden-btn-group">
								<view class="btn-second">
									有味指数
									<text>{{ farm.envScore || '—' }}分</text>
								</view>
								<view class="btn-primary" @click.stop="goSourceReport(farm)">
									溯源报告
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import config from "@/api/config.js"
import HOME from '@/api/home'
import hotComponentVue from './hotComponent.vue'
import { onLoad } from "@dcloudio/uni-app"

const typeSearch = ref(null)
 
function toPage(path) {
  uni.navigateTo({
    url: `/pages/tabBar/home/subPages/${path}`
  });
}

function goGardenItem(farm) {
	const id = farm?.farmId
	uni.navigateTo({
		url: `/pages/tabBar/home/subPages/gardenItem?id=${id}`
	});
}

function goSourceReport(farm) {
	const id = farm?.farmId
	uni.navigateTo({
		url: `/pages/tabBar/home/subPages/sourceReport?id=${id}`
	});
}
 
const latitude = ref(23.099994)
const longitude = ref(113.324520)
const markers = ref([])
const includePoints = ref([])
const mapCtx = ref(null)
const mapPoint = '../../../static/map/point.png'
const farmList = ref([]) // 新增果园列表数据
const scale = ref(10)
const gardenList = ref([])

onLoad(async () => {
  // #ifdef MP-WEIXIN
  // mapCtx.value = uni.createMapContext('mapId')
  
  // mapCtx.value.on('markerClusterClick', res => {
  //   console.log('markerClusterClick', res)
  // })
  
  getTypeList()
  
  getFarmData()
  
  // bindEvent()
  // #endif
})

const typeList = ref([])
function getTypeList() {
	HOME.fetchTypeList().then(({data}) => {
		typeList.value = data
	})
}
 
function getFarmData() {
  HOME.getAllFarm().then(({data}) => {
	gardenList.value = data.filter(item => item.recommend !== null)
 //     farmList.value = (data || []).sort((a, b) => {
	//   // 优先排序：lighten为true的排前面，然后按recommend排序
	//   if (a.lighten !== b.lighten) return b.lighten ? 1 : -1
	//   return (b.recommend || 0) - (a.recommend || 0)
	// })
 //    if(farmList.value.length > 0) {
 //      // 设置地图中心点为第一个果园的位置
 //      const firstPoint = parsePoint(farmList.value[0].point)
 //      latitude.value = firstPoint.latitude
 //      longitude.value = firstPoint.longitude
      
 //      // 生成标记点
 //      generateMarkers(farmList.value)
 //    }
  })
}

// 解析POINT字符串为经纬度对象
function parsePoint(pointStr) {
  if(!pointStr) return {longitude: 113.324520, latitude: 23.099994}
  
  const regex = /POINT\(([^ ]+) ([^ ]+)\)/
  const match = pointStr.match(regex)
  if(match) {
    return {
      longitude: parseFloat(match[1]),
      latitude: parseFloat(match[2])
    }
  }
  return {longitude: 113.324520, latitude: 23.099994} // 默认值
}

// 生成标记点数据
function generateMarkers(farms) {
  const newMarkers = farms.map((farm, index) => {
    const point = parsePoint(farm.point)
    return {
      id: farm.farmId || index + 1, // 使用farmId作为唯一标识
      latitude: point.latitude,
      longitude: point.longitude,
      iconPath: mapPoint, // 使用果园图标
      width: 20,
      height: 20,
      joinCluster: true,
      // callout: { // 添加气泡标签
      //   content: farm.name,
      //   color: '#000',
      //   fontSize: 14,
      //   borderRadius: 4,
      //   bgColor: '#FFCB3C',
      //   padding: 8,
      //   display: 'ALWAYS'
      // },
      label: {
        content: farm.name, // 显示果园名称
        color: '#000',
        fontSize: 12,
        bgColor: '#FFCB3C',
        borderRadius: 8,
        padding: 5,
        anchorX: 0,
        anchorY: -50,
        borderWidth: 1,
        borderColor: '#FFCB3C',
        textAlign: 'center'
      },
      customData: farm // 存储原始数据用于点击事件
    }
  })
  
  // 更新包含的点位范围
  includePoints.value = newMarkers.map(marker => ({
    latitude: marker.latitude,
    longitude: marker.longitude
  }))
  
  // #ifdef MP-WEIXIN
  mapCtx.value.addMarkers({
    markers: newMarkers,
    clear: true,
    complete(res) {
      console.log('添加标记点完成', res)
    }
  })
  // #else
  markers.value = newMarkers
  // #endif
}
 
const bindEvent = () => {
  // #ifdef MP-WEIXIN
  mapCtx.value.initMarkerCluster({
    enableDefaultStyle: false,
    zoomOnClick: true,
    gridSize: 40,
    complete(res) {
      console.log('initMarkerCluster', res)
    }
  })
  
  mapCtx.value.on('markerClusterCreate', res => {
    console.log('clusterCreate', res)
    const clusters = res.clusters
    const clusterMarkers = clusters.map(cluster => {
      // 获取聚合中的第一个果园
      const firstMarker = farmList.value.find(m => m.farmId === cluster.markerIds[0])
      return {
        ...cluster.center,
        width: 20,
        height: 20,
        clusterId: cluster.clusterId,
		iconPath: mapPoint, // 使用果园图标
		label: {
		  content: firstMarker?.name, // 显示果园名称
		  color: '#000',
		  fontSize: 12,
		  bgColor: '#FFCB3C',
		  borderRadius: 8,
		  padding: 5,
		  anchorX: 0,
		  anchorY: -50,
		  borderWidth: 1,
		  borderColor: '#FFCB3C',
		  textAlign: 'center'
		},
        customData: {
          isCluster: true,
          markerIds: cluster.markerIds,
          firstMarkerData: firstMarker?.customData
        }
      }
    })
    
    mapCtx.value.addMarkers({
      markers: clusterMarkers,
      clear: false,
      complete(res) {
      }
    })
  })
  // #endif
}
 
const onMarkerTap = (e) => {
  const markerId = e.detail.markerId
  const marker = markers.value.find(m => m.id === markerId)
  if(marker && marker.customData) {
    console.log('点击了果园:', marker.customData.name)
    // 可以在这里跳转到果园详情页
    uni.navigateTo({
      url: `/pages/tabBar/home/subPages/gardenItem?id=${marker.customData.farmId}`
    })
  }
}

const onCalloutTap = (e) => {
  console.log('点击了气泡:', e)
  onMarkerTap(e) // 调用相同的处理逻辑
}

const onLabelTap = (e) => {
  console.log('点击了标签:', e)
  onMarkerTap(e) // 调用相同的处理逻辑
}

const removeMarkers = () => {
  // #ifdef MP-WEIXIN
  mapCtx.value.addMarkers({
    clear: true,
    markers: []
  })
  // #else
  markers.value = []
  // #endif
}
</script>

<style lang="scss" scoped>
	.home-wrap {
		background-color: #F2F3F5;
		padding: 0 0 16rpx 0;
		.home-top {
			padding: 20rpx 24rpx 0 24rpx;
			background: linear-gradient(#FFFFFF, rgba(242, 243, 245, 0));
			position: relative;
		}
		.map-video {
			width: 100%;
			height: 280rpx;
			border-radius: 16rpx;
		}
		.map-tips {
			position: absolute;
			bottom: 6rpx;
			left: 24rpx;
			height: 70rpx;
			width: calc(100% - 48rpx);
			background: linear-gradient(rgba(102, 102, 102, 0), rgba(0, 0, 0, 0.55));
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #FFFFFF;
			padding-left: 20rpx;
			box-sizing: border-box;
			border-radius: 0 0 16rpx 16rpx;
		}
		.home-search {
			display: flex;
			align-items: center;
			width: 100%;
			border: 2rpx solid #FFD95E;
			border-radius: 40rpx;
			margin-bottom: 40rpx;
			.search-wrap {
				flex: 1;
				// padding-left: 22rpx;
				::v-deep {
					.u-search {
						.u-search__content {
							background-color: transparent !important;
							.u-search__content__input {
								background-color: transparent !important;
								
							}
						}
						.u-search__action {
							text-align: center;
							line-height: 52rpx;
							border-radius: 40rpx;
							font-size: 28rpx;
							background-color: #FFD95E;
							margin: 6rpx 8rpx;
							width: 112rpx;
							height: 52rpx;
						}
					}
				}
			}
			.search-btn {
				text-align: center;
				line-height: 52rpx;
				border-radius: 40rpx;
				font-size: 28rpx;
				background-color: #FFD95E;
				margin: 6rpx 8rpx;
				width: 112rpx;
				height: 52rpx;
			}
		}
		.type-wrap {
			margin: 20rpx;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 16rpx;
			height: 200rpx;
			box-sizing: border-box;
			
			.item-type {
				text-align: center;
				font-size: 24rpx;
				.type-img {
					width: 92rpx;
					height: 92rpx;
				}
			}
			.item-type + .item-type {
				padding-left: 22rpx;
			}
		}
		.home-hot {
			padding: 0 20rpx 20rpx;
		}
		
		.garden-wrap {
			margin: 0 20rpx 20rpx;
			background: linear-gradient(#FFFFFF, rgba(255, 255, 255, 0));
			padding: 2rpx;
			border-radius: 16rpx;
			.garden-content{
				background: linear-gradient(#fff6d8 30rpx,  #FFFFFF 120rpx);
				border-radius: 16rpx;
				padding: 20rpx;
				box-sizing: border-box;
				.garden-list {
					.garden-item {
						display: flex;
						.garden-l {
							position: relative;
							.video-dom {
								width: 234rpx;
								height: 200rpx;
								object-fit: cover;
								border-radius: 10rpx;
							}
							.garden-img {
								width: 254rpx;
								height: 200rpx;
								object-fit: cover;
								border-radius: 10rpx;
							}
							.img-text {
								position: absolute;
								left: 0%;
								top: 0%;
								background: rgba(0, 0, 0, 0.3);
								backdrop-filter: 8rpx;
								border-radius: 10rpx 0 10rpx 0;
								font-size: 20rpx;
								color: #FFFFFF;
								padding: 6rpx 14rpx;
							}
						}
						.garden-r {
							padding-left: 20rpx;
							.garden-title {
								font-size: 28rpx;
								line-height: 42rpx;
								color: #000000;
								font-weight: 600;
								padding-bottom: 10rpx;
							}
							.garden-info {
								color: rgba(0, 0, 0, 0.5);
								font-size: 24rpx;
								line-height: 36rpx;
							}
							.garden-btn-group {
								padding-top: 20rpx;
								display: flex;
								align-items: center;
								.btn-second {
									padding: 0 20rpx;
									border-radius: 40rpx;
									font-size: 24rpx;
									color: #C49600;
									background: rgba(255, 217, 94, 0.2);
									height: 56rpx;
									line-height: 56rpx;
								}
								.btn-primary {
									padding: 0 20rpx;
									border-radius: 40rpx;
									font-size: 24rpx;
									color: #000000;
									background: #FFD95E;
									font-weight: bold;
									height: 56rpx;
									line-height: 56rpx;
								}
							}
						}
					}
					.garden-item + .garden-item {
						margin-top: 20rpx;
					}
				}
			}
			
		}
		
		
		.hot-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-bottom: 20rpx;
			.title-l {
				font-family: 'PangMenZhengDao';
				font-size: 32rpx;
				.title-color {
					color: #F3C11D ;
				}
			}
			.title-btn {
				color: rgba(0, 0, 0, 0.6);
				font-size: 24rpx;
				display: inline-flex;
				align-items: center;
			}
		}
	
		
		::v-deep {
			.u-scroll-list__indicator {
				margin-top: 20rpx;
			}
		}
	}
</style>