<template>
	<view class="g_pl_16 container g_bg_page">
		<scroll-view class="cities-scroll" scroll-with-animation="true" style="box-sizing: border-box" :scroll-into-view="az" scroll-y ref="scrollViewRef">
			<view class="">
				<view class="headTxt">当前城市</view>
				<view class="" hover-class="none" hover-stop-propagation="false">
					<view @click="selectQuanGuo" :class="{ itemCity: true, active: selectedCity === '全国' }">全国</view>
					<view class="g_flex_row_center" v-if="currentCity" @click="selectCity({ shortName: currentCity })" :class="{ itemCity: true, active: selectedCity === currentCity }">
						<i class="iconfont icon-dizhi1 g_mr_4"></i>
						{{ currentCity }}
					</view>
				</view>

				<view class="cities-list">
					<block v-for="group in cities">
						<view class="headTxt" :id="`letter-${group.name[0] == '热' ? 're' : group.name[0]}`">{{ group.name }}</view>
						<block v-for="city in group.list">
							<view @click="selectCity(city)" :class="{ itemCity: true, active: selectedCity === city.shortName }">{{ city.shortName }}</view>
						</block>
					</block>
				</view>
			</view>
			<view class="" style="height: 120px"> </view>
		</scroll-view>
		<!-- 添加字母索引 -->
		<view class="index-list" v-if="false">
			<block v-for="(letter, index) in letters">
				<!-- , activeIndex: currentIndex === index -->
				<view :class="{ indexItem: true }" @click="scrollToLetter(letter)">
					{{ letter }}
				</view>
			</block>
		</view>

		<g-panel-fixed>
			<view class="g_flex_row_center">
				<rh-button primaryColor='#00b666' btnText="重置" size="small" @clickBtn="back"></rh-button>
				<rh-button primaryColor='#00b666' btnText="确定" type="primary" class="g_ml_20" size="small" @clickBtn="setCity"></rh-button>
			</view>
		</g-panel-fixed>
	</view>
</template>
<script>
// import { cityList } from "../utils/city.js";

export default {
	data() {
		return {
			cities: [],
			cdnBaseImg: this.G.store().cdnBaseImg,
			selectedCity: "全国",
			currentIndex: 0,
			letters: [],
			az: "",
			currentInfo: {}, // 当前位置信息
			currentCity: "",
		};
	},
	onLoad() {
		this.initializeCities();

		this.getLocation().then((res) => {
			console.log("res", res);
			this.getCity();
		});

		// this.calculateLetters();
	},
	methods: {
		setCity() {
			uni.setStorageSync("selectedCity", this.selectedCity);
			console.log(`城市 ${this.selectedCity} 已 保存到缓存`);
			uni.navigateBack({ delta: 1 });
		},
		getCity() {
			let that = this;
			this.G.Get(this.api.getCityNameByLatLng, { lng: this.currentInfo.longitude, lat: this.currentInfo.latitude }, (res) => {
				if (res) {
					that.currentCity = res.replace("市", "");
				}
				console.log("res");
			});
		},
		getLocation() {
			let that = this;
			console.log("123123");
			return new Promise((resolve, reject) => {
				uni.authorize({
					// 检测是否授权位置信息
					scope: "scope.userLocation",
					success() {
						console.log("用户成功授权位置信息");
						uni.getLocation({
							type: "wgs84",
							success(res) {
								that.currentInfo = {
									latitude: res.latitude,
									longitude: res.longitude,
									timestamp: new Date().getTime(),
								};
								console.log("获取当前经纬度：", that.currentInfo);
								resolve();
							},
							fail(err) {
								console.log(err);
							},
							complete() {
								resolve();
							},
						});
					},
					fail(err) {
						console.log(err);
						console.log("用户拒绝授权位置信息，再次提示用户授权");
						uni.showToast({
							title: "请开启定位权限以显示距职位距离",
							icon: "none",
						});
						resolve();
						// that.showRefuseLocationPermission();
					},
				});
			});
		},
		back() {
			this.selectedCity = "全国";
			uni.setStorageSync("selectedCity", "全国");

			// uni.navigateBack({ delta: 1 });
		},
		selectQuanGuo() {
			this.selectedCity = "全国";
			console.log("全国被选中");
		},
		selectCity(city) {
			this.selectedCity = city.shortName;
			console.log(`城市 ${city.shortName} 被选中`);
		},
		initializeCities() {
			this.G.Get(this.api.get_city_list, {}, (res) => {
				console.log(res);
				this.letters.push("热");
				res.forEach((item) => {
					if (!this.letters.includes(item.name[0])) {
						this.letters.push(item.name[0]);
					}
				});
				this.cities = res;
				const cachedSelectedCity = uni.getStorageSync("selectedCity");
				if (cachedSelectedCity) {
					this.selectedCity = cachedSelectedCity;
				} else {
					this.selectedCity = "全国";
				}
			});
			// const hotCities = originalCities.find(group => group.name === '热门城市');

			// if (hotCities) {
			//   hotCities.name = '热';
			//   this.cities = originalCities.filter(group => group.name !== '热门城市');
			//   this.cities.unshift(hotCities);
			// } else {
			//   this.cities = originalCities;
			// }
		},
		// calculateLetters() {
		// 	this.letters = [];
		// 	this.cities.forEach((group) => {
		// 		const firstLetter = group.name.charAt(0).toUpperCase();
		// 		if (!this.letters.includes(firstLetter)) {
		// 			this.letters.push(firstLetter);
		// 		}
		// 	});
		// },
		scrollToLetter(letter) {
			var that = this;
			if (letter == "热") {
				letter = "re";
			}
			const id = `letter-${letter}`;
			console.log(id);
			this.az = id;
			// console.log(that.$refs.scrollViewRef);
			// this.$nextTick(() => {
			//   this.$refs.scrollViewRef.scrollIntoView(id, 300);
			// });
		},
	},
};
</script>
<style lang="scss">
.container {
	.itemCity {
		width: calc(33.33% - 10px);
		float: left;
		margin-right: 10px;
		background: #fff;
		border-radius: 30px;
		font-size: 16px;
		font-weight: 400;
		text-align: center;
		padding: 8px 0;
		color: #1d1d1d;
		margin-bottom: 10px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;

		&.active {
			background: #00b666;
			color: #ffffff;
		}
	}

	.headTxt {
		font-size: 18px;
		font-weight: 400;
		color: #999999;
		line-height: 25px;
		margin-top: 10px;
		margin-left: 16px;
		margin-bottom: 10px;
		clear: both;
	}

	.cities-scroll {
		// height: calc(100vh - constant(safe-area-inset-bottom) - 72px);
		padding-bottom: 87px;
		// height: calc(100vh - 100px);
		// overflow-y: auto;
	}

	.index-list {
		position: fixed;
		right: 10px;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		// background-color: #f5f5f5;

		.indexItem {
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 50%;
			margin: 2px;
			&.activeIndex {
				background: #00b666;
				color: #ffffff;
			}
		}
	}
}
</style>
