<template>
	<view class="home-wrap base-container">
		<view class="home-top">
			<view class="home-search">
				<view class="search-wrap">
					<input />
				</view>
				<view class="search-btn">
					搜索
				</view>
			</view>
			<view class="map-wrap">
				 <map
				      id="myMap"
					  class="map-dom"
				      :latitude="center.latitude"
				      :longitude="center.longitude"
				      :markers="clusters"
				      :polyline="[]"
				      :include-points="includePoints"
				      @regionchange="onRegionChange"
				      show-location
				    ></map>
			</view>
		</view>
		<view class="type-wrap">
			<!-- <swiper class="swiper" circular :indicator-dots="true" :autoplay="false" :interval="5000"
				:duration="duration">
				<swiper-item>
					<view class="swiper-item">
						<view class="item-type">
							<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon.png" alt="" />
							<view class="type-text">
								全部
							</view>
						</view>
						<view class="item-type">
							<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-2.png" alt="" />
							<view class="type-text">
								龙眼
							</view>
						</view>
						<view class="item-type">
							<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-3.png" alt="" />
							<view class="type-text">
								葡萄
							</view>
						</view>
						<view class="item-type">
							<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon.png" alt="" />
							<view class="type-text">
								水蜜桃
							</view>
						</view>
						<view class="item-type">
							<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-2.png" alt="" />
							<view class="type-text">
								龙眼
							</view>
						</view>
						<view class="item-type">
							<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-3.png" alt="" />
							<view class="type-text">
								葡萄
							</view>
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="swiper-item">
						<van-button type="primary">按钮</van-button>
					</view>
				</swiper-item>
			</swiper> -->
			 <up-scroll-list indicatorColor="#fae6a4" indicatorActiveColor="#F3C11D" :indicatorWidth="30" :indicatorBarWidth="13">
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon.png" alt="" />
					<view class="type-text">
						全部
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-2.png" alt="" />
					<view class="type-text">
						龙眼
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-3.png" alt="" />
					<view class="type-text">
						葡萄
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon.png" alt="" />
					<view class="type-text">
						水蜜桃
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-2.png" alt="" />
					<view class="type-text">
						龙眼
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-3.png" alt="" />
					<view class="type-text">
						葡萄
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-3.png" alt="" />
					<view class="type-text">
						葡萄1
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon.png" alt="" />
					<view class="type-text">
						水蜜桃2
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-3.png" alt="" />
					<view class="type-text">
						葡萄
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon.png" alt="" />
					<view class="type-text">
						水蜜桃
					</view>
				</view>
				<view class="item-type">
					<image class="type-img" src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/type-icon-2.png" alt="" />
					<view class="type-text">
						龙眼
					</view>
				</view>
			</up-scroll-list>
		</view>
		<!-- 好味热卖 -->
		<view class="hot-wrap">
			<view class="hot-content">
				<view class="hot-title">
					<view class="title-l">
						好味<text class="title-color">热卖</text>
					</view>
					<view class="title-btn">
						限时抢购中<up-icon size="10" name="arrow-right"></up-icon>
					</view>
				</view>
				<view class="hot-list">
					<up-scroll-list indicatorColor="#fae6a4" indicatorActiveColor="#F3C11D" :indicatorWidth="30" :indicatorBarWidth="13">
						<view class="hot-panel">
							<view class="hot-item">
								<image class="hot-img" src="/static/home/hot-1.png" mode=""></image>
								<view class="item-info">
									<view class="info-text">
										<!-- <up-text :lines="2" color="#000000" size="12" text="海南妃子笑新鲜顺丰发货海南妃子笑海南妃子笑"></up-text> -->
										<view class="ellipsis-l2">
											海南妃子笑新鲜顺丰发货海南妃子笑海南妃子笑
										</view>
									</view>
									<view class="info-price">
										<view class="price-text">
											<text class="price-unit">￥</text>108
										</view>
										<view class="info-sold">
											已售1251
										</view>
									</view>
								</view>
							</view>
							<view class="hot-item">
								<image class="hot-img" src="/static/home/hot-2.png" mode=""></image>
								<view class="item-info">
									<view class="info-text">
										<view class="ellipsis-l2">
											海南妃子笑新鲜顺丰发货海南妃子笑海南妃子笑
										</view>
									</view>
									<view class="info-price">
										<view class="price-text">
											<text class="price-unit">￥</text>108
										</view>
										<view class="info-sold">
											已售1251
										</view>
									</view>
								</view>
							</view>
							<view class="hot-item">
								<image class="hot-img" src="/static/home/hot-1.png" mode=""></image>
								<view class="item-info">
									<view class="info-text">
										<view class="ellipsis-l2">
											海南妃子笑新鲜顺丰发货海南妃子笑海南妃子笑新鲜顺丰发货
										</view>
									</view>
									<view class="info-price">
										<view class="price-text">
											<text class="price-unit">￥</text>108
										</view>
										<view class="info-sold">
											已售1251
										</view>
									</view>
								</view>
							</view>
							<view class="hot-item">
								<image class="hot-img" src="/static/home/hot-2.png" mode=""></image>
								<view class="item-info">
									<view class="info-text">
										<view class="ellipsis-l2">
											海南妃子笑新鲜顺丰发货海南妃子笑海南妃子笑新鲜顺丰发货
										</view>
									</view>
									<view class="info-price">
										<view class="price-text">
											<text class="price-unit">￥</text>108
										</view>
										<view class="info-sold">
											已售1251
										</view>
									</view>
								</view>
							</view>
						</view>
					</up-scroll-list>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import QQMapWX from 'qqmap-wx-jssdk'


// 广州中心坐标
const GUANGZHOU_CENTER = {
  latitude: 23.12911,
  longitude: 113.26436
}

// 模拟广州的景点数据
const GUANGZHOU_POIS = [
  { id: 1, name: '广州塔', latitude: 23.10641, longitude: 113.32466 },
  { id: 2, name: '白云山', latitude: 23.19746, longitude: 113.30249 },
  { id: 3, name: '越秀公园', latitude: 23.13927, longitude: 113.26436 },
  { id: 4, name: '沙面岛', latitude: 23.10788, longitude: 113.24365 },
  { id: 5, name: '陈家祠', latitude: 23.12632, longitude: 113.24849 },
  { id: 6, name: '北京路', latitude: 23.12389, longitude: 113.26799 },
  { id: 7, name: '上下九', latitude: 23.11696, longitude: 113.24899 },
  { id: 8, name: '荔枝博览园', latitude: 22.99405, longitude: 113.32486 },
  { id: 9, name: '中山纪念堂', latitude: 23.13146, longitude: 113.26336 },
  { id: 10, name: '海心沙', latitude: 23.11446, longitude: 113.32136 }
]

// 响应式数据
const qqmapsdk = ref(null)
const mapContext = ref(null)
const center = ref(GUANGZHOU_CENTER)
const allMarkers = ref([])
const clusters = ref([])
const includePoints = ref([])
const currentZoom = ref(16)


// 初始化地图
const initMap = () => {
  qqmapsdk.value = new QQMapWX({
    key: 'Q5GBZ-2LP6I-LOKGM-UE3UC-TXH7Z-WCFG2' // key
  })
}

// 加载点位数据
const loadPoints = () => {
  allMarkers.value = GUANGZHOU_POIS.map(item => ({
    ...item,
    iconPath: '../../../static/map/point.png',
    width: 30,
    height: 30,
    callout: {
      content: item.name,
      color: '#ffffff',
      bgColor: '#007AFF',
      padding: 5,
      borderRadius: 4,
      display: 'ALWAYS'
    }
  }))
  
  updateClusters()
}

// 更新聚合点
const updateClusters = () => {
  if (currentZoom.value >= 15) {
    // 放大时显示所有点
    clusters.value = allMarkers.value
  } else {
    // 缩小时显示聚合点
    const clusterRadius = 60 / currentZoom.value
    const clustered = []
    
    allMarkers.value.forEach(marker => {
      let isClustered = false
      
      clustered.forEach(cluster => {
        const distance = getDistance(
          cluster.latitude, cluster.longitude,
          marker.latitude, marker.longitude
        )
        
        if (distance < clusterRadius) {
          isClustered = true
          cluster.markers.push(marker)
          cluster.callout.content = `${cluster.markers.length}个地点`
        }
      })
      
      if (!isClustered) {
        clustered.push({
          ...marker,
          markers: [marker],
          callout: {
            ...marker.callout,
            content: marker.name
          }
        })
      }
    })
    
    clusters.value = clustered.map(cluster => ({
      id: cluster.id,
      latitude: cluster.latitude,
      longitude: cluster.longitude,
      iconPath: cluster.markers.length > 1 ? '../../../static/map/point.png' : '../../../static/map/point.png',
      width: cluster.markers.length > 1 ? 40 : 30,
      height: cluster.markers.length > 1 ? 40 : 30,
      callout: cluster.callout,
      clusterData: cluster.markers
    }))
  }
  
  // 设置地图包含所有点
  includePoints.value = allMarkers.value.map(m => ({
    latitude: m.latitude,
    longitude: m.longitude
  }))
}

// 计算两点间距离
// 更精确的距离计算函数（Haversine公式）
const getDistance = (lat1, lng1, lat2, lng2) => {
  // 将经纬度转换为弧度
  const toRad = d => d * Math.PI / 180
  const R = 6371 // 地球半径(km)
  
  const dLat = toRad(lat2 - lat1)
  const dLng = toRad(lng2 - lng1)
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  
  return R * c * 1000 // 返回米
}

// 地图区域变化事件
const onRegionChange = (e) => {
  if (e.type === 'end') {
    uni.createMapContext('myMap').getScale({
      success: (res) => {
        currentZoom.value = res.scale
        updateClusters()
      }
    })
  }
}

// 搜索地点
const onSearch = (e) => {
  qqmapsdk.value.search({
    keyword: e.value,
    location: center.value,
    success: (res) => {
      allMarkers.value = res.data.map(item => ({
        id: item.id,
        name: item.title,
        latitude: item.location.lat,
        longitude: item.location.lng,
        iconPath: '../../../static/map/point.png',
        callout: {
          content: item.title,
          color: '#ffffff',
          bgColor: '#007AFF',
          padding: 5,
          borderRadius: 4,
          display: 'ALWAYS'
        }
      }))
      
      updateClusters()
    }
  })
}

// 清除搜索
const clearSearch = () => {
  loadPoints()
}

// 生命周期钩子
onMounted(() => {
  // #ifdef MP-WEIXIN
  mapContext.value = uni.createMapContext('myMap', this)
  initMap()
  loadPoints()
  
  // 获取地图区域
  if (mapContext.value && mapContext.value.getRegion) {
    mapContext.value.getRegion({
      success: res => console.log('地图范围:', res),
      fail: err => console.error('地图异常:', err) 
    })
  }
  // #endif
})

const typeList = reactive([  
    'https://cdn.uviewui.com/uview/swiper/swiper3.png',  
    'https://cdn.uviewui.com/uview/swiper/swiper2.png',  
    'https://cdn.uviewui.com/uview/swiper/swiper1.png',  
]);  
</script>

<style lang="scss" scoped>
	.home-wrap {
		background-color: #F2F3F5;
		padding: 0;
		.home-top {
			padding: 20rpx 24rpx;
			background: linear-gradient(#FFFFFF, rgba(242, 243, 245, 0));
		}
		.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;
			}
			.search-btn {
				text-align: center;
				line-height: 52rpx;
				border-radius: 40rpx;
				font-size: 28rpx;
				background-color: #FFD95E;
				margin: 6rpx 8rpx;
				width: 112rpx;
				height: 52rpx;
			}
		}
		.map-wrap {
			height: 280rpx;
			.map-dom {
				width: 100%;
				height: 100%;
			}
		}
		.type-wrap {
			margin: 20rpx;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 16rpx;
			height: 200rpx;
			box-sizing: border-box;
			.swiper-item {
				display: flex;
				align-items: center;
			}
			
			.swiper {
				height: 170rpx;
			}
			::v-deep {
				.u-scroll-list__indicator {
					margin-top: 20rpx;
				}
			}
			
			.item-type {
				text-align: center;
				font-size: 24rpx;
				.type-img {
					width: 92rpx;
					height: 92rpx;
				}
			}
			.item-type + .item-type {
				padding-left: 22rpx;
			}
		}
		
		.hot-wrap {
			margin: 0 20rpx 20rpx;
			background: linear-gradient(#FFFFFF, rgba(255, 255, 255, 0));
			padding: 2rpx;
			border-radius: 16rpx;
			.hot-content {
				background: linear-gradient(#fff1c3 4%,  #FFFFFF 28%);
				border-radius: 16rpx;
				padding: 20rpx;
				height: 236rpx;
				.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;
					}
				}
				.hot-list {
					.hot-panel {
						width: 100%;
						display: flex;
						.hot-item {
							width: calc(50% - 10rpx);
							display: flex;
							white-space: nowrap;
							.hot-img {
								flex: none;
								width: 116rpx;
								height: 116rpx;
								object-fit: cover;
								border-radius: 10rpx;
							}
							.item-info {
								padding-left: 10rpx;
								width: 200rpx;
								.info-text {
									color: #000000;
									font-size: 24rpx;
								}
								.info-price {
									display: flex;
									align-items: baseline;
									justify-content: space-between;
									.price-text {
										color: #FF7700;
										font-size: 36rpx;
										.price-unit {
											font-size: 23rpx;
										}
									}
									.info-sold {
										font-size: 20rpx;
										color: #C4C4C4;
									}
								}
							}
						}
						.hot-item + .hot-item {
							margin-left: 20rpx;
						}
					}
				}
			}
		}
	}
</style>