<template>
	<view class="box" :style="{paddingTop: top + 'px'}">

		<!-- 背景图 -->
		<!-- <view class="indexBg">
			<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/Index_bg.png" mode="widthFix" />
		</view> -->

		<!-- 搜索框部分 -->
		<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 v-if="!currentCity.city">
					{{city ? city.city : '选择城市'}}
				</view>
				<view v-if="currentCity.city">
					{{currentCity.city}}
				</view>
			</view>
		<!-- 	<view class="searchBox_msg">
				<view class="iptbox">
					<input type="text" v-model="iptMsg" @input="iptChange" :placeholder="currentPlaceholder" />
					<image @tap="searchCurrent"
						src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/water_filter/dervice/deriveSearch.png"
						mode="widthFix" />
				</view>
				<view class="map" @tap="opMap">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/Index_map.png" mode="widthFix" />
					地图
				</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">
			<view class="tabItem" v-for="(item, index) in tabList" :key="index" @tap="desc" :data-url="item.link_url">
				<view class="tabImg">
					<image :src="item.icon_src" mode="widthFix" />
				</view>
				<view class="tabname">{{item.title}}</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 class="line"></view>

		<!-- 精选服务 -->
		<view class="Tit">精选服务</view>
		<view class="serverList">
			<view class="serverItem serverItem1" @tap="cf">
				<view class="serverTit">榴园厨房</view>
				<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/server_img1.png" mode="widthFix" />
			</view>
			<view class="serverItem serverItem2" @tap="wybx">
				<view class="serverTit">物业报修</view>
				<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/server_img2.png" mode="widthFix" />
			</view>
			<view class="serverItem serverItem3" @tap="shopEnter">
				<view class="serverTit">商家入驻</view>
				<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/indexSubcontract/_assets/Merchantsettlement.png"
					mode="widthFix" />
			</view>
			<view class="serverItem serverItem4" @tap="water_filter">
				<view class="serverTit">人人爱净水</view>
				<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/server_img4.png" mode="widthFix" />
			</view>
		</view>

		<!-- 列表选项卡 -->
		<view class="List_tabList">
			<view :class="['List_tabItem', current == 0 ? 'List_active' : '']" @tap="changeCurrent" data-idx="0">小区</view>
			<view :class="['List_tabItem', current == 1 ? 'List_active' : '']" @tap="changeCurrent" data-idx="1">服务</view>
			<view :class="['List_tabItem', current == 2 ? 'List_active' : '']" @tap="changeCurrent" data-idx="2">店铺</view>
			<view :class="['List_tabItem', current == 3 ? 'List_active' : '']" @tap="changeCurrent" data-idx="3">团购</view>
			<view :class="['List_tabItem', current == 4 ? 'List_active' : '']" @tap="changeCurrent" data-idx="4">预定</view>
		</view>

		<!-- 列表内容 -->
		<view class="List" v-if="current == 0">
			<tabularCard v-for="(item, index) in CommunityList" :key="index" :item="item"
				:isLast="index === CommunityList.length -1" />
		</view>

		<view class="list" v-if="current == 1">
			<view class="item_goodsItem" v-if="serverList.length > 0" v-for="(items, index) in serverList" :key="index"
				@tap="ServerDesc(items.appoint_id)" :data-id="items.appoint_id">
				<view class="item_goodsItem_tit">
					<image :src="items.photo" mode="aspectFill" />
				</view>
				<view style="flex: 1;">
					<view class="item_goodsItem_name">{{items.title}}</view>
					<view class="item_goodsItem_msg">
						￥
						<view>{{items.price}}</view>
						<text>/{{items.unit}}</text>
					</view>
				</view>
			</view>
			<van-empty v-if="serverList.length == 0" description="暂无内容" />
		</view>

		<view class="empty" v-if="current != 0 && current != 1">
			<van-empty description="暂无内容" />
		</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/doorToDoor.js'

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

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


	export default {
		components: {
			nav
		}, //2.注册组件
		data() {
			return {
				// s: uni.getSystemInfoSync().statusBarHeight, // 状态栏高度
				// n: (uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight) * 2 + uni
				// 	.getMenuButtonBoundingClientRect().height, // 导航栏高度
				// t: uni.getMenuButtonBoundingClientRect().top, // 胶囊局顶部距离
				// h: uni.getMenuButtonBoundingClientRect().height, // 胶囊高度
				// picUrl: picUrl,
				city: "",
				qqmap_key: '',
				tabList: [
					// ... 保持原有tabList数据不变 ...
				],
				nearbyLocation: '',
				current: 0,
				flag: false,
				page_num: 1,
				page_size: 10,
				serverList: [], // 服务列表
				CommunityList: [], // 小区列表
				iptMsg: "",
				currentIdx: 0,
				currentCity: "",
				city: "",
				top: 0,
				localHeight: 44,
				userlocat: "",

				bannerList: [],
				buttonList: [],

				tabList: [{
						img: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img1.png",
						name: "社区列表",
						url: "/packages/community/index/index?title=社区列表&types=2"
					},
					{
						img: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img2.png",
						name: "社区服务",
						url: "/packages/communityService/index/index"
					},
					{
						img: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img3.png",
						name: "周边商家",
						url: ""
					},
					// {
					//     img:"https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img4.png",
					//     name:"社区团购",
					//     // url:""
					// },
					// {
					//     img:"https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img5.png",
					//     name:"餐饮美食",
					//     url:""
					// },
					{
						img: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img6.png",
						name: "智慧康养",
						url: ""
					},
					{
						img: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img11.png",
						name: "我的预约",
						url: "/packages/community/repairList/index"
					},
					{
						img: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img8.png",
						name: "便民服务",
						url: ""
					},
					// {
					//     img:"https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img9.png",
					//     name:"积分兑换",
					//     // url:""
					// },
					// {
					//     img:"https://wechat-img-file.oss-cn-beijing.aliyuncs.com/tabItem_img10.png",
					//     name:"官方商城",
					//     url:""
					// },
				],
				title: 'Hello',
				currentCity: "",
				currentProviceCity: "",

				HotWords: [],
				currentPlaceholder: '',
				placeholderIndex: 0
			}
		},

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

			iptChange(e) {
				this.iptMsg = e.detail.value
			},
			searchCurrent() {
				this.flag = false
				this.page_num = 1
				this.serverList = []
				this.current = 1
				this.getServerList()
			},
			opMap() {
				uni.chooseLocation({
					success(res) {
						console.log(res)
					}
				})
			},
			map() {
				// if (uni.getStorageSync('userId')) {
				uni.navigateTo({
					url: '/pages/shopcity/shopcity'
				});
				// } else {
				// 	uni.navigateTo({
				// 		url: '/pages/login/login'
				// 	})
				// }
			},
			getCommunityList() {
				let that = this;
				request(apiArr.list, "POST", {
					page_num: that.page_num,
					page_size: that.page_size
				}).then(res => {
					let flag = false;
					if (res.rows && res.rows.length == that.page_size) {
						flag = true;
					} else {
						flag = false;
					}
					res.rows.forEach(item => {
						item.pic = picUrl + item.pic
					})
					that.CommunityList = that.CommunityList.concat(res.rows || []);
					that.flag = flag;
					that.page_num = that.page_num + 1;

				});
			},
			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();
						}
					}
				});
			},
			changeCurrent(e) {
				const idx = e.currentTarget.dataset.idx;
				this.current = idx;
				this.flag = false;
				this.page_num = 1;
				this.serverList = [];
				this.CommunityList = [];
				this.iptMsg = '';

				if (idx == 0) {
					this.getCommunityList();
				} else if (idx == 1) {
					if (!uni.getStorageSync('ctoken')) {
						uni.navigateTo({
							url: '/pages/login/login'
						});
						return;
					}
					this.getServerList();
				}
			},

			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);
								var city = res.data.result.address_component.city;
								userlocat = {
									userlat: latitude,
									userlng: longitude,
									city: city,
								};
								that.city = userlocat;
								that.nearbyLocation = address_component.district + address_component.street_number;
								uni.setStorageSync('userlocat', userlocat);
								uni.setStorageSync('Usercity', city);
								uni.setStorageSync('city', city);
							},
							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) {
				console.log('eeee', 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) {
							console.log('1231231', 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 作为区的显示文本
										}))
								}))
						}))
						console.log('接口返回数据处理 省市区', cascaderOptions);
					};

					// 如果读的接口返回数据，则不二次进行处理， 否则对缓存数据进行二次处理
					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 作为区的显示文本
										}))
								}))
						}))
						console.log('读缓存数据处理的省市区', cascaderOptions)
					}

					this.currentProviceCity = this.getProvinceCityId(cascaderOptions, uni.getStorageSync('city'))
					console.log('currentProviceCitycurrentProviceCity', 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; // 如果没找到匹配的城市
			},

			// 获取服务列表
			async getServerList() {
				const res = await request(apiArr2.getServerById, 'POST', {
					page_num: this.page_num,
					page_size: this.page_size,
					title: this.iptMsg,
				});
				console.log('获取服务列表', res);
				let flag = false;
				if (res.rows && res.rows.length == this.page_size) {
					flag = true
				} else {
					flag = false
				}
				res.rows.forEach(item => {
					item.photo = picUrl + item.photo
				});
				console.log('res.rowsres.rows ', res.rows);
				this.serverList = this.serverList.concat(res.rows || []);
				this.flag = flag;
				this.page_num = this.page_num + 1;
			},

			//服务详情
			ServerDesc(id) {
				NavgateTo(`/packages/communityService/reservation/index?id=${id}`);
			},

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

						}
					}
				})
			},

			getHotWords() {
				request(apiArr.getHotWords, "POST").then(res => {
					let msg = res.search_hot_word
					this.HotWords = msg.split(",")
					this.rotatePlaceholder()
				})
			},

			rotatePlaceholder() {
				const interval = setInterval(() => {
					const nextIndex = (this.placeholderIndex + 1) % this.HotWords.length;
					this.currentPlaceholder = this.HotWords[nextIndex]
					this.placeholderIndex = nextIndex
				}, 30000); // 每2秒切换一次

				this.placeholderInterval = interval
				this.currentPlaceholder = this.HotWords[0]
			},


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

			//物业报修
			wybx() {
				NavgateTo('/packages/community/oneRepair/index')
			},
			//商家入驻
			shopEnter() {
				this.NotOpen();
				// wx.navigateTo({
				//   url: '/packages/indexSubcontract/shopEnter/index',
				// })
			},
			//人人爱净水
			water_filter() {
				this.NotOpen();
			},

		},
		onLoad(options) {
			this.init()
			this.getCommunityList()
			this.getHostInfo()
			const meun = menuButtonInfo();
			console.log('meunmeun', meun);
			this.top = meun.top;
			// this.top = meun.height + meun.top;
			this.localHeight = meun.height;
			this.getHotWords()
		},
		onShow() {
			console.log(this.currentCity, '   this.currentCity')
			if (uni.getStorageSync('city')) {
				let obj = {
					city: uni.getStorageSync('city')
				}
				if (this.currentCity && this.currentCity.city !== uni.getStorageSync('city')) {
					console.log('缓存中的城市，与 新选择的城市 不一致, 缓存中的城市', this.currentCity);
					console.log('新选择的的城市', uni.getStorageSync('city'));
					this.init();
				}
				this.currentCity = obj;
			} else {
				uni.setStorageSync('city', uni.getStorageSync('Usercity'))
			}
		},
		onReachBottom() {
			if (this.current == 0) {
				if (this.flag) {
					this.getCommunityList()
				}
			} else if (this.current == 1) {
				if (this.flag) {
					this.getServerList()
				}
			}
		}

	}
</script>

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