<template>
	<view class="container" :style="{ marginTop: top + 'px' }" v-if="loading">
		<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" autoplay circular>
					<swiper-item v-for="(item, index) in bannerList" :key="index" @click="headerServerClick(item)">
						<image :src="item.pic_src" mode="aspectFill" />
					</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="rowNum" :border="false">
					<u-grid-item v-for="(item, index) in tabList" @click="headerServerClick(item)" :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">

				<view class="serverList_left">
					<swiper>
						<swiper-item v-for="(item, index) in homeLeftList" :key="index">
							<image :src="item.pic_src" alt="" mode="aspectFit" />
						</swiper-item>
					</swiper>
				</view>



				<view class="serverList_right">
					<view :class="['serverItem', `serverItem${index +1}` ]" @tap="headerServerClick(item)" v-for="(item, index) in homeRightList" :key="index">
						<view class="serverTit">{{ item.title }}</view>
						<image :src="item.pic_src" mode="" />
					</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 bottomList" :key="index" class="list_pic" :src="item.pic_src" mode="">
			</image>
		</view>
		<view class="more" v-if="flag">下拉加载后续10条，共计{{ bottomTotal }}条</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 {
			loading: false,
			city: "",
			qqmap_key: '',
			tabList: [], // 金刚位列表信息
			nearbyLocation: '', // 城区附近地址
			flag: false,
			currentIdx: 0,
			currentCity: "", // 地址信息
			top: 0,
			localHeight: 44,
			userlocat: "",

			bannerList: [],
			buttonList: [],

			currentProviceCity: "",


			rowNum: 0,
			colNum: 0,

			homeLeftList: [],//中间左侧的广告
			homeRightList: [], // 中间右侧广告
			bottomPageSize: 10,
			bottomPageNum: 1,
			bottomList: [],
			bottomTotal: 0,
			flag: false,
		}
	},

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

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

		init() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			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('location');

			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					const latitude = userlocat ? userlocat.lat : res.latitude;
					const longitude = userlocat ? userlocat.lng :res.longitude;
					uni.request({
						url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${qqmap_key}&get_poi=0`,
						success: async (res) => {
							const { data: { result: { address_component, ad_info } } } = res;

							// 精确到xx路 信息
							let preciseLocation = {
								cityName: address_component.city, // 市区
								region: address_component.province + address_component.city + address_component.district, // 省市区
								// 无街道xx号的地方，则定位到xx街道附近 无精确到xx号
								district: address_component.district + `${address_component.street_number ? address_component.street_number : address_component.street}`, // 详细地址
								address: address_component.city + address_component.district + address_component.street_number, // 详细地址
								lat: latitude,
								lng: longitude,
							};
							that.currentCity = preciseLocation;
							uni.setStorageSync('location', preciseLocation);
							uni.setStorageSync('ad_code', ad_info.adcode);
							// TODO: 这里需要强依赖 ad_code 去查询，必须保障代码先后执行顺序正确
							const [bannerList, homeLeftList, homeRightList, bottomList, buttonList] = await Promise.all([
								this.getHomeBanner(),// 轮播图查询
								this.getHomeMidLeft(), // 中部左侧查询
								this.getHomeMidRight(), // 中部右侧查询
								// this.getHomePop()
								this.getHomeBottom(true), // 底部广告查询
								this.getButtonNum(), // 金刚位设置查询 及 金刚位按钮查询
							]);
							this.bannerList = bannerList;
							this.homeLeftList = homeLeftList;
							this.homeRightList = homeRightList;
							that.bottomList = bottomList;
							this.tabList = buttonList;
							this.loading = true;
							uni.hideLoading();
						},
						fail(err) {
							console.log(err);
						}
					});
				}
			});
		},

		headerServerClick(e) {
			console.log('当前点击内容', e);
			if (!e.link_url) {
				this.NotOpen();
				return
			}
			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
				if(e.appid) {
					uni.navigateToMiniProgram({
						appId: e.appid,
						path: e.link_url,
						//需要传递给目标小程序的数据
						extraData: {
							'data1': 'test'
						},
						success(res) {
							console.log('打开成功', res)
						}
					})
				}else{
					NavgateTo(e.link_url)
					// NavgateTo('/packages/localLife/index/index')
				}
				// 小程序中可能需要用户手动复制链接或使用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
			}
		},




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

					}
				}
			})
		},

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

		headershopEnterClick() {
			NavgateTo('/packages/shopEnter/index/index');
		},


		async getHomeBanner() {
			const res = await request(apiArr2.getHomeBanner, "POST", {
				ad_code: uni.getStorageSync('ad_code'),
				ad_position: 1,
				longitude: uni.getStorageSync('location').lng,
				latitude: uni.getStorageSync('location').lat,
				page_num: 1,
				page_size: 10
			}, { silent: false });

			if (res.rows.length) {
				let filterRes = this.filterShowList(res?.rows, 1);
				filterRes.forEach(item => {
					item.pic_src = picUrl + item.pic_src
				})
				return filterRes
			} else {
				return []
			}
		},

		async getHomeMidLeft() {
			const res = await request(apiArr2.getHomeBanner, "POST", {
				ad_code: uni.getStorageSync('ad_code'),
				ad_position: 2,
				longitude: uni.getStorageSync('location').lng,
				latitude: uni.getStorageSync('location').lat,
				page_num: 1,
				page_size: 10
			}, { silent: false });
			if (res.rows.length) {
				let filterRes = this.filterShowList(res?.rows, 1);
				filterRes.forEach(item => {
					item.pic_src = picUrl + item.pic_src
				})
				return filterRes
			} else {
				return []
			}
		},

		async getHomeMidRight() {
			const res = await request(apiArr2.getHomeBanner, "POST", {
				ad_code: uni.getStorageSync('ad_code'),
				ad_position: 3,
				longitude: uni.getStorageSync('location').lng,
				latitude: uni.getStorageSync('location').lat,
				page_num: 1,
				page_size: 10
			}, { silent: false });
			if (res.rows.length) {
				let filterRes = this.filterShowList(res?.rows, 1);
				filterRes.forEach(item => {
					item.pic_src = picUrl + item.pic_src
				})
				return filterRes.slice(0, 6)
			} else {
				return []
			}
		},

		// 小程序首页弹窗内容
		async getHomePop() {
			await request(apiArr2.getHomeBanner, "POST", {
				ad_code: uni.getStorageSync('ad_code'),
				ad_position: 4,
				longitude: uni.getStorageSync('location').lng,
				latitude: uni.getStorageSync('location').lat,
				page_num: 1,
				page_size: 10
			}, { silent: false }).then(res => {
				console.log(res);
			})
		},

		// 底部推荐信息
		async getHomeBottom(val = false) {
			const res = await request(apiArr2.getHomeBanner, "POST", {
				ad_code: uni.getStorageSync('ad_code'),
				ad_position: 5,
				longitude: uni.getStorageSync('location').lng,
				latitude: uni.getStorageSync('location').lat,
				page_num: this.bottomPageNum,
				page_size: this.bottomPageSize
			}, { silent: val ? false : true });
			if (res.rows.length === 0) {
				return [];
			};
			if (res.rows.length == this.bottomPageSize) {
				this.flag = true
			} else {
				this.flag = false
			}
			let filterRes = this.filterShowList(res?.rows, 1);
			filterRes.forEach(item => {
				item.pic_src = picUrl + item.pic_src
			})
			this.bottomPageNum++
			this.bottomTotal = res.total
			return filterRes
		},



		async getButtonNum() {
			const res = await request(apiArr2.getButtonNum, "POST", {}, { slice: false });
			this.rowNum = res.nav_row_num
			this.colNum = res.nav_row_total
			return await this.getHomeButton()
		},

		async getHomeButton() {
			const res = await request(apiArr2.getHomeButton, "POST", {
				ad_code: Number(uni.getStorageSync('ad_code')),
				page_num: 1,
				page_size: 50
			}, { slice: false });
			// 过滤出已发布的按钮列表
			const filterRes = this.filterShowList(res?.rows, 1);
			// 根据所需展示数量对数据进行截取
			let newList = filterRes.slice(0, this.rowNum * this.colNum);
			console.log('111', newList);
			if (newList.length !== 0) {
				newList.forEach(item => {
					item.icon_src = picUrl + item.icon_src
				})
				return newList;
			} else {
				return []; 
			}
		},

		/**
		 * 首页过滤方法
		 * @param {Array} list 请求地址
		 * @param {any} type 过滤值
		 * @returns {Array} 返回符合条件的数组内容
		*/
		filterShowList(list, type) {
			if (list && list.length == 0) return [];
			return list.filter((item) => item.show_status == type);
		}

	},
	onLoad(options) {
		this.init()
		const meun = menuButtonInfo();
		this.top = meun.top;
		this.localHeight = meun.height;
	},
	onShow() {
		this.flag = false
		this.bottomPageNum = 1
		console.log('当前页面展示的城市信息', this.currentCity)
		console.log('缓存中存储的城市信息', uni.getStorageSync('location'));
		const storageLocation = uni.getStorageSync('location');
		// 存在缓存城市信息， 并且不是第一次加载页面则调用该方法
		if (storageLocation && this.loading) {
			// 非同一城市名称 或者 同一城市详细地址不同则重新请求接口
			if (this.currentCity && this.currentCity.cityName !== storageLocation.cityName || this.currentCity.address !== storageLocation.district) {
				this.init();
			}
			this.currentCity = storageLocation;
		}
	},

	async onReachBottom() {
		if (this.flag) {
			const res = await this.getHomeBottom();
			this.bottomList = this.bottomList.concat(res);
		} else {
			uni.showToast({
				title: '没有更多了',
				icon: 'none'
			})
		}
	}
}
</script>

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