<template>
	<view class="container">
		<div class="noticeBox" v-if="showNotice && noticeList.length > 0">
			<div class="notice_content">
				<uv-notice-bar @close="showNotice = false" direction="column" bgColor="#EEF0F4" color="#000"
					:text="noticeList" mode="closable"></uv-notice-bar>
				<!-- 				<div class="title">公告</div>
				<div class="notice">恭喜广州通力电梯加盟</div> -->
			</div>
		</div>
		<uv-sticky>
			<div class="head">
				<div class="title" @click="goChooseAdress">
					<uv-icon name="map" color="#fff" size="18"></uv-icon>
					{{userStore.adressInfo?.adress}}
					<uv-icon name="arrow-right" color="#fff" size="18"></uv-icon>
				</div>
			</div>
		</uv-sticky>
		<div class="mapBox">
			<map style="width: 100%; height: 100%;" @markertap="onMarkerTap" :latitude="latitude" :longitude="longitude"
				:markers="markers">
			</map>
		</div>
		<div class="itemBox">
			<div class="item" v-for="item in list" :key="item.store.id">
				<div class="imgBox">
					<img class="img" :src="item?.store?.main_image || '/static/imgs/dianti.png'" alt="">
				</div>
				<div class="contentBox">
					<div class="titleBox">
						<div class="left">
							<div class="name">{{item?.store?.store_name}}</div>
							<div class="adress_detail">{{item?.store?.address}}</div>
						</div>
						<div class="phoneBox" v-if="item?.store?.contact_phone" @click="handleContact(item?.store?.contact_phone)">
							<uv-icon name="phone-fill" color="#fff" size="20"></uv-icon>
						</div>
					</div>
					<div class="adressBox">
						<div class="adress">地址：{{item?.store?.location}}</div>
						<div class="adress">工作时间：{{item?.store?.business_hours}}</div>
					</div>
					<div class="descBox">
						<div class="left">
							<div class="desc_item" v-for="ele in (item?.store?.tags?.split(',') || [])" :key="ele">{{ele}}</div>
						</div>
						 <div class="distance" @click="navigateToLocation(item)">{{item?.distance?.toFixed(2)}}km</div>
					</div>
				</div>
				<div class="getMore" @click="goDetail(item?.store?.id)">了解更多 {{'>'}}</div>
			</div>
		</div>
		<div class="go_login_box" v-if="showLogin">
			<div class="leftBox">
				<div class="avatar">
					<img class="img" src="/static/imgs/avatar.png" alt="">
				</div>
				<div class="nameBox">
					<div class="title">欢迎来到卡叔电梯</div>
					<div class="desc">登录后获取资料详情</div>
				</div>
			</div>
			<div class="go_login" @click="handleLogin">
				去登录
			</div>
			<div class="closeBox" @click="showLogin = false">
				X
			</div>
		</div>
		<!-- <Login v-if="showLogin" @close="showLogin = false" /> -->
		<uv-load-more :status="loadingStatus" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		onShow,
		onLoad,
		onShareAppMessage,
		onShareTimeline,
		onReachBottom
	} from "@dcloudio/uni-app";
	import {
		useAuthStore,
		useUserStore
	} from "@/store";
	// import Login from '/components/Login/Login.vue'
	import RPC from "@/utils/request";

	const authStore = useAuthStore()
	const userStore = useUserStore()
	const showLogin = ref(!authStore?.isLoggedIn)

	const showNotice = ref(true)
	
	const noticeList = ref([])
	
	RPC.post('/notice/list',{page:1,limit:10,orderby:[{id:"desc"}]}).then(res => {
		noticeList.value = res.rows?.map(item => item.content) || []
	})

	// 分享给朋友
	onShareAppMessage((data) => {
		console.log("🚀 ~ onShareAppMessage ~ data:", data);
		return {
			title: "卡叔电梯",
			path: "/pages/index/index",
			// imageUrl: "https://img-cdn-tx.dcloud.net.cn/uni-app/logo-U.png", // 显示图片长宽比是 5:4
		};
	});

	// 分享到朋友圈
	onShareTimeline((data) => {
		console.log("🚀 ~ onShareTimeline ~ data:", data);
		return {
			title: "卡叔电梯",
			query: "a=1&b=2",
			// imageUrl: "https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/icon.png", // 显示图片长宽比是 1:1
		};
	});

	const handleLogin = () => {
		uni.showLoading({
			title: "登录中...",
		});
		uni.login({
			success: function(loginRes) {
				console.log('loginRes', loginRes);
				RPC.post('/account/miniprogram/phonelogin', {
					code: loginRes.code
				}).then(res => {
					console.log('phonelogin', res)
					uni.showToast({
						title: "登录成功",
						icon: "success",
					});
					authStore.setAccessToken(res.token)
					userStore.setUserInfo(res)
					showLogin.value = false
				}).catch(() => {
					uni.showToast({
						title: "登录失败",
						icon: "error",
					});
				})
			},
			fail: () => {
				uni.hideLoading();
			}
		})
	}


	// 联系电话
	function handleContact(phone) {
		uni.makePhoneCall({
			phoneNumber: phone, // 示例电话号码
			success: () => {
				console.log("拨打电话成功");
			},
			fail: (err) => {
				console.log("拨打电话失败", err);
			},
		});
	}
	const goDetail = (id) => {
		if (!authStore?.isLoggedIn) {
			uni.showToast({
				title: "请先登录",
				icon: "none",
			})
			showLogin.value = true
			return
		}
		uni.$uv.route({
			url: '/pagesA/ProductDetails/ProductDetails',
			params: {
				id: id,
			}
		});
	};

	const goChooseAdress = () => {
		uni.$uv.route({
			url: '/pagesA/choose-adress/choose-adress',
		});
	}
	const latitude = ref(39.90);
	const longitude = ref(116.39);

	const markers = ref([
		// 	{
		// 	id: 11111,
		// 	latitude: 39.90,
		// 	longitude: 116.39,
		// 	iconPath: '/static/imgs/map_adress.png',
		// 	width: 50,
		// 	height: 50,
		// 	title: '当前位置',
		// 	callout: {
		// 		content: '通力电梯（北京旗舰店）',
		// 		display: 'ALWAYS'
		// 	},
		// }, {
		// 	id: 2222,
		// 	latitude: 31.454278,
		// 	longitude: 104.756637,
		// 	iconPath: '/static/imgs/map_adress.png',
		// 	width: 50,
		// 	height: 50,
		// 	title: '当前位置',
		// 	callout: {
		// 		content: '通力电梯（四川旗舰店）',
		// 		display: 'ALWAYS'
		// 	},
		// },
	])

	const updateLocalMarkers = (latitude, longitude) => {
		// markers.value = markers.value.filter(item => item.id !== 999999999999)
		// markers.value.push({
		// 	id: 999999999999,
		// 	latitude: latitude,
		// 	longitude: longitude,
		// 	iconPath: '/static/imgs/map_icon.png',
		// 	width: 30,
		// 	height: 30,
		// 	// title: '当前选中位置',
		// 	// callout: {
		// 	// 	content: '当前选中位置',
		// 	// 	display: 'ALWAYS'
		// 	// },
		// })
		list.value = []
		page.value = 1
		search()
	}

	const navigateToLocation = (item) => {
		// 调用微信小程序的打开地图API
		uni.openLocation({
			latitude: item?.store?.latitude,
			longitude: item?.store?.longitude,
			name: item?.store?.store_name, // 可选
			address: item?.store?.address, // 可选
			scale: 18, // 地图缩放级别，1-28
			success: function() {
				console.log('打开地图成功');
			},
			fail: function(err) {
				console.log('打开地图失败', err);
			}
		});
	}

	function onMarkerTap(e) {
		const markerId = e.detail.markerId
		console.log('点击了 marker：', markerId)
		if (markerId !== 999999999999) {
			goDetail(markerId)
		}
	}

	const getadress = () => {
		uni.getLocation({
			type: 'wgs84',
			isHighAccuracy: true,
			success: function(res) {
				console.log(res)
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
				uni.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/`,
					method: 'GET',
					data: {
						location: `${res.latitude},${res.longitude}`,
						key: 'N6LBZ-JLDCT-SQNXQ-LQUWR-6PQX7-TQBQN'
					},
					success: (res1) => {
						console.log('N6LBZ-JLDCT-SQNXQ-LQUWR-6PQX7-TQBQN')
						console.log('res1', res1)
						if (res1.data.status === 0) {
							console.log(res1)
							// const address = res.data.result.address
							// const formatted = res.data.result.formatted_addresses.recommend
							// console.log('具体地址：', formatted || address)
							userStore.setAdressInfo({
								latitude: res.latitude,
								longitude: res.longitude,
								adress: res1.data.result.address_component
									.street_number || res1.data.result
									.address_component
									.street,
							})
						} else {
							uni.showToast({
								title: '逆解析失败' + res1.data?.message,
								icon: "none",
							})
							console.error('逆解析失败', res1.data?.message)
						}
					},
					fail: (err) => {
						console.error('网络错误', err)
					}
				})
				latitude.value = res.latitude
				longitude.value = res.longitude
				updateLocalMarkers(res.latitude, res.longitude)
			},
		});
	}

	onLoad(() => {
		console.log('index-onLoad')
		getadress()
	})

	onShow(() => {
		const adressInfo = userStore.adressInfo
		console.log('onSHow', adressInfo)
		showLogin.value = !authStore?.isLoggedIn
		if (adressInfo?.latitude && adressInfo?.longitude && adressInfo?.adress) {
			latitude.value = adressInfo.latitude
			longitude.value = adressInfo.longitude
			updateLocalMarkers(adressInfo.latitude, adressInfo.longitude)
		} else {
			getadress()
		}
	})

	const loadingStatus = ref('loadmore')
	const page = ref(1)
	const list = ref([])
	const count = ref(0)
	const search = () => {
		loadingStatus.value === 'loading'
		RPC.post('/store/nearby', {
			page: page.value,
			limit: 10,
			radius: 100,
			latitude: latitude.value,
			longitude: longitude.value
		}).then(res => {
			console.log('/store/nearby', res)
			list.value = [...list.value, ...res.stores]
			console.log(list.value)
			count.value = res.count
			markers.value = [
				{
				id: 999999999999,
				latitude: latitude,
				longitude: longitude,
				iconPath: '/static/imgs/map_icon.png',
				width: 30,
				height: 30,
			},
			 ...(list.value.map(item => {
				return {
					id: item.store?.id,
					latitude: item.store?.latitude,
					longitude: item.store?.longitude,
					iconPath: '/static/imgs/map_adress.png',
					width: 50,
					height: 50,
					callout: {
						content: item.store?.store_name,
						display: 'ALWAYS'
					},
				}
			}))]
			if (list.value.length >= count.value) {
				loadingStatus.value = 'nomore'
			} else {
				loadingStatus.value = 'loadmore'
			}
		}).catch(() => {
			loadingStatus.value = 'loadmore'
		})
		// setTimeout(() => {
		// 	list.value = [1, 2, 3]
		// 	count.value = 10
		// 	if (list.value.length >= count.value) {
		// 		loadingStatus.value = 'nomore'
		// 	}
		// }, 1000)
	}
	// onMounted(() => search())
	onReachBottom(() => {
		if (list.value.length >= count.value || loadingStatus.value === 'loading') return
		console.log('上拉加载:')
		loadingStatus.value = 'loading';
		page.value = ++page.value;
		search()
		// setTimeout(() => {
		// 	list.value = [...list.value, ...[4, 5, 6, 7, 8, 9, 10]]
		// 	count.value = 10
		// 	if (list.value.length >= count.value) {
		// 		loadingStatus.value = 'nomore'
		// 	} else {
		// 		loadingStatus.value = 'loadmore'
		// 	}
		// }, 1500)
	})
</script>

<style lang="scss" scoped>
	.container {
		font-size: 14px;
		min-height: 100vh;
		background-color: #f8f8f8;

		.img {
			width: 100%;
			height: 100%;
		}
	}

	.noticeBox {
		position: fixed;
		top: 100px;
		left: 50%;
		transform: translate(-50%, 0);
		background-color: #fff;
		border-radius: 6px;
		z-index: 999999;
		height: 40px;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 90vw;

		.notice_content {
			background-color: #EEF0F4;
			display: flex;
			align-items: center;
			width: 90%;
			height: 30px;
			border-radius: 6px;
			overflow-x: auto;
			// padding: 0 10px;

			.title {
				background-color: #3F70FF;
				color: #fff;
				margin-right: 20px;
				padding: 3px 10px;
				border-radius: 6px;
			}

			.notice {
				color: #000;
			}
		}
	}

	.head {
		// background-color: rgba(3, 0, 255, 0.6);
		// background: center / 100% 100% url('/static/imgs/head_bg.png') no-repeat;
		background-image: url('data:image/png;base64,[encoded data, 172216 characters]');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		background-position: center;
		height: 90px;
		position: sticky;

		.title {
			position: absolute;
			bottom: 10px;
			font-size: 16px;
			left: 3vw;
			display: flex;
			gap: 5px;
			color: #fff
		}
	}


	.mapBox {
		height: 40vh;
		z-index: 1;
		position: relative;
	}

	.itemBox {
		padding: 10px;

		.item {
			border-radius: 10px;
			overflow: hidden;
			box-shadow: 0px 2px 23px 0px rgba(217, 217, 217, 0.5);
			margin-bottom: 20px;

			.imgBox {
				background-color: skyblue;
				height: 130px;
			}

			.contentBox {
				padding: 10px;

				.titleBox {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						.name {
							font-size: 16px;
							font-weight: 700;
							margin-bottom: 6px;
						}

						.adress_detail {
							font-weight: 400;
						}
					}

					.phoneBox {
						width: 30px;
						height: 30px;
						border-radius: 50%;
						background-color: goldenrod;
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}

				.adressBox {
					display: flex;
					align-items: center;
					margin: 6px 0;

					.adress {
						font-size: 12px;
						margin-right: 20px;
					}
				}

				.descBox {
					display: flex;
					justify-content: space-between;
					font-size: 12px;

					.left {
						flex: 1;
						overflow-x: auto;
						display: flex;

						.desc_item {
							padding: 2px 8px;
							background-color: #F1F2F4;
							margin-right: 10px;
						}
					}

					.distance {
						flex-shrink: 0;
						color: #ccc;
					}
				}
			}

			.getMore {
				height: 40px;
				display: flex;
				justify-content: center;
				align-items: center;
				border-top: 0.5px solid #eee;
				color: #aaa
			}
		}
	}

	.go_login_box {
		width: 80vw;
		background-color: rgba(0, 0, 0, .8);
		position: fixed;
		bottom: 20px;
		left: 50%;
		transform: translate(-50%, 0);
		border-radius: 10px;
		z-index: 999999;
		display: flex;
		justify-content: space-between;
		padding: 8px 10px;
		padding-right: 38px;
		align-items: center;
		overflow: hidden;

		.leftBox {
			display: flex;
			align-items: center;

			.avatar {
				width: 30px;
				height: 30px;
				background-color: #F8F8F8;
				margin-right: 5px;
				border-radius: 50%;
				overflow: hidden;
				display: flex;
				align-items: center;
				justify-content: center;

				.img {
					width: 80%;
					height: 80%;
				}
			}

			.nameBox {
				.title {
					color: #fff;
				}

				.desc {
					color: #949494;
					font-size: 12px;
				}
			}
		}

		.go_login {
			padding: 3px 10px;
			border-radius: 20px;
			background-color: #3F70FF;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.closeBox {
			background-color: #5E5C4B;
			position: absolute;
			top: 0;
			right: 0;
			color: #A6A5A4;
			width: 20px;
			height: 20px;
			border-radius: 6px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
</style>