<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">
			<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" />
					<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="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" :data-appid="items.appoint_id">
				<view class="item_goodsItem_tit">
					<image :src="picUrl + item.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数据不变 ...
				],
				current: 0,
				flag: false,
				page_num: 1,
				page_size: 10,
				serverList: [], // 服务列表
				CommunityList: [], // 小区列表
				iptMsg: "",
				bannerList: [],
				currentIdx: 0,
				currentCity: "",
				city: "",
				top: 0,
				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:"",
			}
		},


		onShow() {

			if (uni.getStorageSync('city')) {
				this.currentCity = {
					city: uni.getStorageSync('city')
				};
			} else {
				uni.setStorageSync('city', uni.getStorageSync('Usercity'))
			}
		},


		methods: {
			swipers(e) {
				this.currentIdx = e.detail.current
			},
			getBanner() {
				request(apiArr2.getBanner, "POST", {}).then(res => {
					this.bannerList = res.list
				})
			},
			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 = this.picUrl + item.pic
					})
					that.CommunityList = that.CommunityList.concat(res.rows || []);
					that.flag = flag;
					that.page_num = that.page_num + 1;
					console.log(that.CommunityList);
				});
			},
			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) {
					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) {
								var city = res.data.result.address_component.city;
								userlocat = {
									userlat: latitude,
									userlng: longitude,
									city: city,
								};
								that.city = userlocat;
								uni.setStorageSync('userlocat', userlocat);
								uni.setStorageSync('Usercity', city);
							},
							fail(err) {
								console.log(err);
							}
						});
					}
				});
			},

			getBannerList() {
				let that = this
				request(apiArr.getBanner, "POST", {
					city_id:this.currentProviceCity.provinceId,
					area_id:this.currentProviceCity.cityId,
				}).then(res => {

					if (res.rows.length) {
						res.rows.forEach(item => {
							item.pic_src = this.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 = this.picUrl + item.icon_src
							
							console.log(item.icon_src,'banner1');
						})

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

			desc(e) {
				
				console.log(e);
				uni.navigateTo({
					url: e.currentTarget.dataset.url
				});
			},

			// 获取省份信息
			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 [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)
					
					
					let 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,'cascaderOptions');
					
					this.currentProviceCity = this.getProvinceCityId(cascaderOptions,uni.getStorageSync('city'))
					
					
					this.getButtonList()
					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; // 如果没找到匹配的城市
			}

		},
		onLoad(options) {
			this.init()
			this.getCommunityList()
			this.getHostInfo()
			const meun = menuButtonInfo();
			this.top = meun.height + meun.top;

			
		},
		onShow() {
			if (uni.getStorageSync('city')) {
				let obj = {
					city: uni.getStorageSync('city')
				}
				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>