<template>
	<view class="map-popup-box">
		<view class="icon-title-navBar-box">
			<view @click="goUpPage" class="nav-bar-icon"></view>
			<text class="nav-bar-title">选择地址</text>
		</view>
		<uni-popup ref="filterPopup" type="top" :animation="false" :is-mask-click="false"
			mask-background-color="rgba(0, 0, 0, 0.4)">
			<view class="white-popup">
				<view class="icon-title-navBar-box">
					<view @click="closePop" class="nav-bar-icon"></view>
					<text class="nav-bar-title">选择城市</text>
				</view>
				<t-index-address @select="select"></t-index-address>
			</view>
		</uni-popup>
		<!-- 查询职业 -->
		<view class="phone-search-box city-search-box">
			<view @click="openPopup" class="city-select-btn">
				{{currentCity}}
			</view>
			<view class="city-input-box">
				<input class="search-input" placeholder="请输入地址" v-model="data.keyword" />
				<view class="search-icon" @click="handleClick">
					<uni-icons type="search" size="24" color="#fff"></uni-icons>
				</view>
			</view>
		</view>
		<map style="width: 100%; height: 300px;" :latitude="data.latitude" :longitude="data.longitude"
			:markers="data.covers" :show-location="true"> </map>

		<view v-if="result" class="map-card-list">
			<!--  #ifdef H5   -->
			<view v-for="(item,index) in result.data" key="index" @click="xuanzeAdress(item)" class="map-card-box">
				<view>
					<view class="map-card-title"><text v-if="index==0" class="dqwz-text">当前位置</text>{{item.title}}
					</view>
					<view class="map-card-address">{{item.address}}</view>
				</view>
				<icon class="map-active-icon" v-if="index==0"></icon>
			</view>
			<!--   #endif   -->
			<!--  #ifdef APP   -->
			<view v-for="(item,index) in result.data.data" key="index" @click="xuanzeAdress(item)" class="map-card-box">
				<view>
					<view class="map-card-title"><text v-if="index==0" class="dqwz-text">当前位置</text>{{item.title}}
					</view>
					<view class="map-card-address">{{item.address}}</view>
				</view>
				<icon class="map-active-icon" v-if="index==0"></icon>
			</view>
			<!--   #endif   -->
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from "vue"
	import myIcon from "@/static/images/common/markIcon.png"
	import {
		jsonp
	} from "@/utils/common.js"

	import {
		onLoad,
		onHide,
		onShow
	} from "@dcloudio/uni-app"
	import {
		useCustomMap
	} from "@/components/customMap/useMap.js"
	import config from "@/config.js"
	const emits = defineEmits(['close', 'xuanzeAdress', 'currentWeizhi'])
	const {
		getPositionSearchByKeyword
	} = useCustomMap();

	const result = ref(null);
	const filterPopup = ref(null);
	let currentCity = ref('选择城市');

	function select(data) {
		console.log('data', data);
		currentCity.value = data.name; // 更新当前城市
		filterPopup.value.close()
		getCityLocation(data.name);
	}



	function openPopup(data) {
		console.log('data', data);
		filterPopup.value.open("top")
	}

	function closePop(data) {
		console.log('data', data);
		filterPopup.value.close()
	}


	function getCityLocation(city) {
		console.log('222222');
		console.log('city', city);
		const Key = config.mapKey
		const url = `https://apis.map.qq.com/ws/geocoder/v1`;
		const url2 = `https://apis.map.qq.com/ws/geocoder/v1/?address=${city}&key=${Key}`;
		// #ifdef H5
		jsonp(url, {
			address: `${city}`,
			key: Key,
			output: 'jsonp'
		}, 'ccc1').then(res => {
			console.log('res1222222', res);
			if (res.status === 0) {
			const cityLocation = res.result.location;
			console.log('cityLocation', cityLocation);
			if (cityLocation) {
				data.latitude = cityLocation.lat;
				data.longitude = cityLocation.lng;
				data.covers[0].latitude = cityLocation.lat;
				data.covers[0].longitude = cityLocation.lng;
				// 重新搜索附近的地点
				getPositionSearchByKeyword(data.keyword || '公司',
					`nearby(${cityLocation.lat},${cityLocation.lng},1000)`,
					onSuccess, onError, {
						page: 1,
						size: 3,
					});
			}
			} else {
				console.error('失败：', res);
		
			}
		}).catch(err => {
			console.log('err', err);
		}).finally(() => {
		
		})
		
		// #endif
		// #ifdef APP
		uni.request({
			url: url2,
			method: 'get',
			timeout: 20000,
		}).then(res => {
			console.log('res', res);
			if (res.data && res.data.result && res.data.result.location) {
				const cityLocation = res.data.result.location;
				console.log('cityLocation', cityLocation);
				if (cityLocation) {
					data.latitude = cityLocation.lat;
					data.longitude = cityLocation.lng;
					data.covers[0].latitude = cityLocation.lat;
					data.covers[0].longitude = cityLocation.lng;
					// 重新搜索附近的地点
					getPositionSearchByKeyword(data.keyword || '公司',
						`nearby(${cityLocation.lat},${cityLocation.lng},1000)`,
						onSuccess, onError, {
							page: 1,
							size: 3,
						});
				}
			}
		}).catch(err => {
			console.log('err')

		}).finally(() => {

		})
		// #endif
	}

	function handleClick() {
		if (data.keyword) {
			getPositionSearchByKeyword(data.keyword, `nearby(${data.latitude},${data.longitude},1000)`, onSuccess,
				onError, {
					page: 1,
					size: 3,
				})
		}
	}

	function onSuccess(res) {
		console.log('数据', res);
		result.value = res
		// #ifdef H5
		if (res && res.data && res.data.length > 0) {
			// 获取第一个搜索结果的经纬度
			const firstResult = res.data[0];
			const newLatitude = firstResult.location.lat; // 纬度
			const newLongitude = firstResult.location.lng; // 经度

			// 更新地图的中心点
			data.latitude = newLatitude;
			data.longitude = newLongitude;

			// 更新标记点
			data.covers = [{
				latitude: newLatitude,
				longitude: newLongitude,
				iconPath: myIcon, // 使用你的图标路径
				width: 30,
				height: 30
			}];
		}
		// #endif
		// #ifdef APP
		if (res.data && res.data.data && res.data.data.length > 0) {
			// 获取第一个搜索结果的经纬度
			const firstResult = res.data.data[0];
			const newLatitude = firstResult.location.lat; // 纬度
			const newLongitude = firstResult.location.lng; // 经度

			// 更新地图的中心点
			data.latitude = newLatitude;
			data.longitude = newLongitude;

			// 更新标记点
			data.covers = [{
				latitude: newLatitude,
				longitude: newLongitude,
				iconPath: myIcon, // 使用你的图标路径
				width: 30,
				height: 30
			}];
		}
		// #endif
	}

	function onError(err) {
		console.log('错误', err)
	}

	function goUpPage(err) {
		console.log('错误', err)
		emits('close');

	}

	function xuanzeAdress(item) {
		console.log('item', item);
		emits('xuanzeAdress', item.address);
		emits('currentWeizhi', item.location);

	}

	const data = reactive({
		keyword: '', // 关键字
		id: 0, // 使用 marker点击事件 需要填写id
		title: 'map',
		latitude: 0,
		longitude: 0,
		covers: [{
			latitude: 0,
			longitude: 0,
			iconPath: myIcon,
			width: 30,
			height: 30
		}]
	})

	function getCityName(latitude, longitude) {
		const Key = config.mapKey
		const url1 = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${Key}`;
		const url = `https://apis.map.qq.com/ws/geocoder/v1`;
		//const url = `https://apis.map.qq.com/ws/geocoder/v1/`;
		// #ifdef H5
		jsonp(url, {
			location: `${latitude},${longitude}`,
			key: Key,
			output: 'jsonp'
		}, 'ccc').then(res => {
			console.log('res11111', res);
			if (res.status === 0) {
				const city = res.result.address_component.city;
				currentCity.value = city; // 更新当前城市
				console.log('当前城市：', city);
			} else {
				console.error('逆地理编码失败：', res);

			}
		}).catch(err => {
			console.log('err', err);
		}).finally(() => {

		})
		// #endif
		// #ifdef APP
		uni.request({
			url: url1,
			success: (res) => {
				if (res.data.status === 0) {
					console.log('当前城市：', res);
					const city = res.data.result.address_component.city;
					currentCity.value = city; // 更新当前城市
					console.log('当前城市：', city);
				} else {
					console.error('逆地理编码失败：', res.data.message);
					uni.showToast({
						title: '获取城市信息失败',
						icon: 'none',
					});
				}
			},
			fail: (err) => {
				console.error('请求失败：', err);
				uni.showToast({
					title: '请求失败',
					icon: 'none',
				});
			}
		});
		// #endif
	}
	// 初始化
	function initLocation() {
		console.log('init')
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				console.log('res', res)
				data.longitude = res.longitude;
				data.latitude = res.latitude;
				data.covers[0].longitude = res.longitude;
				data.covers[0].latitude = res.latitude;
				console.log('当前位置的经度：' + res.longitude);
				console.log('当前位置的纬度：' + res.latitude);
				getCityName(res.latitude, res.longitude)
				// 获取当前位置附近的数据
				getPositionSearchByKeyword('公司', `nearby(${res.latitude},${res.longitude},1000)`, onSuccess,
					onError, {
						page: 1,
						size: 3,
					});
			}
		});
	}

	onLoad(() => {
		console.log('初始化',config)
		initLocation();
	})
</script>

<style>

</style>