<template>
	<view class="container" :style="{marginTop: top + 'px'}">
		<view class="white_container">
			<!-- 搜索框部分 -->
			<view class="searchBox" :style="{height: localHeight + 'px'}">
				<view class="searchBox_add" @tap="map">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/Index_add.png" mode="widthFix" />
					<view >
						{{currentCity.cityName || '选择城市'}}
					</view>
				</view>
			</view>
			<!-- 轮播图 -->
			<view class="swiper">
				<swiper @animationfinish="swipers">
					<swiper-item v-for="(item, index) in bannerList" :key="index" @click="details(item)">
						<image :src="item.pic_src" mode="widthFix" />
					</swiper-item>
				</swiper>
			
				<view class="cirList">
					<view :class="['cir', currentIdx == index ? 'active' : '']" v-for="(item, index) in bannerList" :key="index">
					</view>
				</view>
			</view>
			
			<!-- 宫格列表 -->
			<view class="tabList">
				<u-grid col="5" :border="false">
					<u-grid-item
						v-for="(item, index) in tabList"
						@click="desc(item.link_url)"
						:key="index"
					>
					<image class="grid_Pic" :src="item.icon_src" mode=""></image>
					<text>{{item.title}}</text>
					</u-grid-item>
				</u-grid>
			</view>
		</view>
		
		<view class="white_container margin_top20 padding_bottom32">
			<view v-if="!currentCity.district" class="Tit">定位错误 未知区域</view>
			<view v-else class="Tit">
				<view class="local">{{currentCity.district}}</view>附近
				<view class="Tit_desc">公积金补贴商户</view>
			</view>
			<view class="serverList">
				<image class="serverList_left" src="http://127.0.0.1:5500/assets/index_Group_1169.png" alt="" />
				<view class="serverList_right">
					<view class="serverItem serverItem1" @tap="cf">
						<view class="serverTit">便利超市</view>
						<image src="http://127.0.0.1:5500/assets/index_Group_1167.png" mode="widthFix" />
					</view>
					<view class="serverItem serverItem2" @tap="cf">
						<view class="serverTit">茶馆咖啡</view>
						<image src="http://127.0.0.1:5500/assets/index_Group_1166.png" mode="widthFix" />
					</view>
					<view class="serverItem serverItem3" @tap="cf">
						<view class="serverTit">休闲娱乐</view>
						<image src="http://127.0.0.1:5500/assets/index_Group_1168.png" mode="widthFix" />
					</view>
					<view class="serverItem serverItem4" @tap="cf">
						<view class="serverTit">蔬菜水果</view>
						<image src="http://127.0.0.1:5500/assets/index_Group_1298.png" mode="widthFix" />
					</view>
					<view class="serverItem serverItem5" @tap="cf">
						<view class="serverTit">养生健身</view>
						<image src="http://127.0.0.1:5500/assets/index_Group_1165.png" mode="widthFix" />
					</view>
					<view class="serverItem serverItem6" @tap="cf">
						<view class="serverTit">更多</view>
						<image src="http://127.0.0.1:5500/assets/index_Group_1283.png" mode="widthFix" />
					</view>
				</view>
			</view>
			<view class="merchant" @click="headershopEnterClick">商户申请入驻</view>
		</view>
		
		<view class="white_container margin_top20 main padding_bottom32">
			<image v-for="(item, index) in 8" :key="index" class="list_pic" src="http://127.0.0.1:5500/assets/index_Mask_group.png" mode=""></image>
		</view>
		<view class="more">下拉加载后续10条，共计30条</view>
		<nav-footer />
	</view>

</template>


<script>
	import {
		NavgateTo
	} from '../../utils/index';

	import {
		util,
		picUrl,
		request,
		menuButtonInfo
	} from '../../utils/index.js';
	import {
		apiArr
	} from '../../api/community.js';

	import {
		apiArr as apiArr2
	} from '../../api/v2Home.js'

	import {
		apiArr as citys
	} from '../../api/area.js';

	import nav from '../../components/nav/nav'; //1.导入组件


	export default {
		components: {
			nav
		}, //2.注册组件
		data() {
			return {
				city: "",
				qqmap_key: '',
				tabList: [],
				nearbyLocation: '', // 城区附近地址
				flag: false,
				currentIdx: 0,
				currentCity: "", // ? 什么作用
				top: 0,
				localHeight: 44,
				userlocat: "",

				bannerList: [],
				buttonList: [],

				currentProviceCity: "",
			}
		},

		methods: {
			swipers(e) {
				this.currentIdx = e.detail.current
			},

			map() {
				uni.navigateTo({
					url: '/pages/shopcity/shopcity'
				});
			},

			getHostInfo() {
				const that = this;
				uni.request({
					url: apiArr.get_host_info,
					method: 'POST',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					dataType: 'json',
					success: (result) => {
						let wxapp = result.data.all.wxapp;
						if (wxapp) {
							this.qqmap_key = wxapp.qqmap_key;
							this.getUserLocation();
						}
					}
				});
			},
	

			getUserLocation() {
				let that = this
				const {
					qqmap_key
				} = this;
				let userlocat = uni.getStorageSync('userlocat');

				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						const latitude = res.latitude;
						const longitude = res.longitude;
						uni.request({
							url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${qqmap_key}&get_poi=0`,
							success: function(res) {
								const {  data:{ result: { address_component } } } = res;
								console.log('获取地址', address_component);
								
								// 精确到xx路 信息
								let preciseLocation = {
									cityName: address_component.city, // 市区
									district: address_component.district + address_component.street_number, // 详细地址
									address: address_component.city + address_component.district + address_component.street_number, // 详细地址
									lat: latitude,
									lng: longitude,
								};
								that.currentCity = preciseLocation;
								uni.setStorageSync('location', preciseLocation);
							},
							fail(err) {
								console.log(err);
							}
						});
					}
				});
			},

			getBannerList() {
				let that = this
				request(apiArr.getBanner, "POST", {
					// city_id:this.currentProviceCity?.provinceId, //TODO 如果传入省id，配置的河北保定轮播图就会在 定位到河北别的省份展示出保定的轮播图，等PD确定展示逻辑，在决定是否传递省id
					area_id: this.currentProviceCity?.cityId,
				}).then(res => {

					if (res.rows.length) {
						res.rows.forEach(item => {
							item.pic_src = picUrl + item.pic_src
						})
						this.bannerList = res.rows
					}

				})
			},

			details(e) {
				if (e.link_url) {
					// #ifdef APP-PLUS
					uni.navigateTo({
						url: '/pages/webview/webview?url=' + encodeURIComponent(e.link_url)
					});
					// #endif

					// #ifdef H5
					window.open(e.link_url, '_blank');
					// #endif

					// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU
					// 小程序中可能需要用户手动复制链接或使用web-view
					uni.showModal({
						title: '提示',
						content: '即将打开外部链接，请复制后在浏览器中打开: ' + e.link_url,
						confirmText: '复制链接',
						success(res) {
							if (res.confirm) {
								uni.setClipboardData({
									data: e.link_url,
									success() {
										uni.showToast({
											title: '复制成功',
											icon: 'success'
										});
									}
								});
							}
						}
					});
					// #endif
				}
			},

			getButtonList() {
				let that = this
				request(apiArr.getButton, "POST", {
					city_id: this.currentProviceCity?.provinceId,
					area_id: this.currentProviceCity?.cityId

				}).then(res => {
					if (res.rows.length) {
						res.rows.forEach(item => {
							item.icon_src = picUrl + item.icon_src
						})

						this.tabList = res.rows
					}
				})
			},

			desc(e) {
				if (!e) {
					this.NotOpen();
					return
				}
				if (e == '/packages/communityService/index/index') {
					if (!uni.getStorageSync('city')) {
						wx.showModal({
							title: '提示',
							content: '请先选择您的城市',
							confirmText: "去选择",
							complete: (res) => {
								if (res.cancel) {}
								if (res.confirm) {
									NavgateTo('/pages/index/shopcity')
								}
							}
						})
						return
					}
				}

				// 周边商家跳转时需获取当前经纬度坐标
				if (e == '/packages/aroundShop/index/index') {
					uni.getLocation({
						type: "gcj02",
						success(res) {
							NavgateTo(`${e}?lat=${res.latitude}&log=${res.longitude}`)
						}
					})
					return;
				}


				console.log('选择城市');
				NavgateTo(`${e}`)

			},



			// 获取省份信息
			async getProvList() {
				const res = await request(citys.city, 'POST', {}, {
					silent: false
				});
				return res;
			},

			// 获取市区信息
			async getCityList() {
				const res = await request(citys.area, 'POST', {}, {
					silent: false
				});
				return res;
			},

			// 获取 县/区 信息
			async getDistList() {
				const res = await request(citys.business, 'POST', {}, {
					silent: false
				});
				return res;
			},

			async init() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				try {
					const proviceList = uni.getStorageSync('proviceList');
					const cityList = uni.getStorageSync('cityList');
					const businessList = uni.getStorageSync('businessList');

					let cascaderOptions = null;

					// 有缓存数据时 不进行接口请求
					if (!proviceList || !cityList || !businessList) {
						const [provRes, cityRes, distRes] = await Promise.all([
							this.getProvList(),
							this.getCityList(),
							this.getDistList(),
						])

						uni.setStorageSync('proviceList', provRes.rows)
						uni.setStorageSync('cityList', cityRes.rows)
						uni.setStorageSync('businessList', distRes.rows)

						cascaderOptions = provRes?.rows.map(province => ({
							value: province.city_id, // 使用 city_id 作为省的值
							label: province.name, // 使用 name 作为省的显示文本
							children: cityRes?.rows
								.filter(city => city.city_id === province.city_id) // 注意：这里需要确认关联字段
								.map(city => ({
									value: city.area_id, // 使用 area_id 作为市的值
									label: city.area_name, // 使用 area_name 作为市的显示文本
									children: distRes?.rows
										.filter(district => district.area_id === city.area_id) // 注意：这里需要确认关联字段
										.map(district => ({
											value: district.business_id, // 使用 business_id 作为区的值
											label: district.business_name // 使用 business_name 作为区的显示文本
										}))
								}))
						}))
					};

					// 如果读的接口返回数据，则不二次进行处理， 否则对缓存数据进行二次处理
					if (!cascaderOptions) {
						cascaderOptions = proviceList.map(province => ({
							value: province.city_id, // 使用 city_id 作为省的值
							label: province.name, // 使用 name 作为省的显示文本
							children: cityList
								.filter(city => city.city_id === province.city_id) // 注意：这里需要确认关联字段
								.map(city => ({
									value: city.area_id, // 使用 area_id 作为市的值
									label: city.area_name, // 使用 area_name 作为市的显示文本
									children: businessList
										.filter(district => district.area_id === city.area_id) // 注意：这里需要确认关联字段
										.map(district => ({
											value: district.business_id, // 使用 business_id 作为区的值
											label: district.business_name // 使用 business_name 作为区的显示文本
										}))
								}))
						}))
					}

					this.currentProviceCity = this.getProvinceCityId(cascaderOptions, uni.getStorageSync('city'))
					await this.getButtonList()
					await this.getBannerList()

					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					console.log('页面初始化失败', error);
				}
			},

			getProvinceCityId(areaList, cityName) {
				// 遍历省份列表
				for (const province of areaList) {
					// 检查省份下的城市列表
					if (province.children && province.children.length > 0) {
						for (const city of province.children) {
							if (city.label === cityName) {
								return {
									provinceId: province.value,
									cityId: city.value
								};
							}
						}
					}
				}
				return null; // 如果没找到匹配的城市
			},


			NotOpen() {
				uni.showModal({
					title: '提示',
					content: '此功能暂未开通！',
					showCancel: false,
					complete: (res) => {
						if (res.cancel) {

						}
					}
				})
			},

			//   榴园厨房
			cf() {
				NavgateTo('/kitchen/index/index');
			},
			
			headershopEnterClick() {
				NavgateTo('/packages/shopEnter/index/index');
			},

		},
		onLoad(options) {
			uni.showLoading({
				title:'加载中'
			})
			this.init()
			this.getHostInfo()
			const meun = menuButtonInfo();
			this.top = meun.top;
			this.localHeight = meun.height;
		},
		onShow() {
			console.log('this.currentCity', this.currentCity)
			if (uni.getStorageSync('location')) {
				if (this.currentCity && this.currentCity.cityName !== uni.getStorageSync('city')) {
					console.log('缓存中的城市，与 新选择的城市 不一致, 缓存中的城市', this.currentCity);
					console.log('新选择的的城市', uni.getStorageSync('location'));
					this.init();
				}
				this.currentCity = uni.getStorageSync('location');
			}
		},
		
		onReachBottom() {}
	}
</script>

<style>
	@import url("./index.css");
</style>