<template>
	<view class="home-base-bg">
		<InputAndSwiper type='0' :bannerURL="swiperList"></InputAndSwiper>
		<view class="home-content">
			<view class="service">
				<u-image src="/static/statistics/sy_icon_lxkf.png" width="108rpx" height="108rpx"></u-image>
				<button open-type="contact" bindcontact="handleContact" session-from="sessionFrom" class="service-btn">
				</button>
			</view>
			<HomeNavCard></HomeNavCard>
			<HomeNoticeBar :text="notice" />
			<Statistics :statNum="statNum" />
			<view class="show-and-search">
				<view class="show-tab list-tab" :class="{ 'tab-activate': chooseIndex === 0 }" @click="this.chooseIndex=0">
					<text>店铺列表</text>
				</view>
				<view class="search-tab list-tab" :class="{ 'tab-activate': chooseIndex === 1 }" @click="this.chooseIndex=1">
					<text>找店列表</text>
				</view>
			</view>
			<SearchShopList v-if="chooseIndex" :searchInfoList="searchInfoList" />
			<ShowShopList v-else :shopInfoList="shopInfoList" />
		</view>
		<TabBar :current-page="0"></TabBar>
	</view>
</template>

<script>
	import HomeNoticeBar from "./HomeMainContent/HomeNoticeBar.vue"
	import HomeNavCard from "./HomeMainContent/HomeNavCard.vue"
	import Statistics from "./HomeMainContent/Statistics.vue"

	import QQMapWX from "@/utils/qqmap-wx-jssdk.min.js"
	export default {
		components: {
			HomeNavCard,
			HomeNoticeBar,
			Statistics
		},
		data() {
			return {
				notice: [],
				chooseIndex: 0,
				statNum: {},
				swiperList: [],
				shopInfoList: [],
				searchInfoList: [],
				shopPageSize: 5,
				searchPageSize: 5,
				shopPageNum: 1,
				searchPageNum: 1,
				shopListLength: '',
				shopSearchListLength: '',
				isAuth: false,
			}
		},
		onLoad() {
			this.getBanner()
			this.getNotice()
			this.getStat()
			this.getShopList()
			this.getSearchList()
			this.open()
			this.getClassList()
		},
		onShow() {
			if (this.isAuth) {
				if (!uni.getStorageSync('city_code')) {
					uni.getSystemInfo({
						success: (res) => {
							if (!res.locationEnabled || !res.locationAuthorized) {
								uni.showModal({
									content: '检测到您没打开手机系统定位权限，请确保手机系统定位已开启',
									confirmText: "确认",
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											this.getUserLocation();
										} else {
											console.log('取消');
											return false;
										}
									}
								})
							} else {
								this.getUserLocation()
							}
						}
					})
				}
			}
		},
		onReachBottom() {
			if (this.chooseIndex == 0 && this.shopListLength !== 0) {
				this.shopPageNum++
				this.getShopList()
			}
			if (this.chooseIndex == 1 && this.shopSearchListLength !== 0) {
				this.searchPageNum++
				this.getSearchList()
			}
		},
		methods: {
			getBanner() {
				this.$api.getBanner().then(res => {
					res.data.data.forEach(item => {
						item.img = this.$api.imgUrl + item.img
					})
					this.swiperList = res.data.data
					// .map(item => this.$api.imgUrl + item.img)
				})
			},
			getNotice() {
				this.$api.getHotInfo().then(res => {
					this.notice = res.data.data.map(item => item.title)
				})
			},
			getStat() {
				this.$api.getStat().then(res => {
					this.statNum = res.data.data
				})
			},
			getShopList() {
				const query = this.$u.queryParams({
					type: 1,
					pageSize: this.shopPageSize,
					pageNum: this.shopPageNum
				})
				this.$api.getShopList(query).then(res => {
					// res.data.data.forEach(item => {
					// 	item.pics = this.$api.imgUrl + item.pics
					// })
					this.shopListLength = res.data.data.length
					this.shopInfoList = [...this.shopInfoList, ...res.data.data]
				})
			},
			getSearchList() {
				const query = this.$u.queryParams({
					type: 2,
					pageSize: this.searchPageSize,
					pageNum: this.searchPageNum
				})
				this.$api.getShopList(query).then(res => {
					this.shopSearchListLength = res.data.data.length
					// 用于触底刷新  为数据赋值：通过展开运算符的形式，进行新旧数据的拼接
					this.searchInfoList = [...this.searchInfoList, ...res.data.data]
					console.log(this.searchInfoList);
				})
			},
			getClassList() {
				this.$api.getClassList().then(res => {
					let data = res.data.data
					data.sort((a, b) => {
						return a.id - b.id
					})
					data = data.map(item => item.name)
					uni.setStorageSync('classList', JSON.stringify(data))
				})
			},
			getRegionList() {
				var that = this
				uni.request({
					url: 'https://apis.map.qq.com/ws/district/v1/getchildren?id=' + uni.getStorageSync('city_code') + '&key=' +
						that.$api.key,
					success(res) {
						uni.setStorageSync('regionList', JSON.stringify(res.data.result[0].map(item => item.fullname)));
					},
					fail(err) {
						console.log('请求区域失败：', err);
					}
				})
			},
			getUserLocation() {
				var that = this
				let qqmapsdk = new QQMapWX({
					key: that.$api.key
				});
				uni.getFuzzyLocation({
					type: 'wgs84',
					success(res) {
						console.log('res.latitude', res.latitude);
						console.log('res.longitude', res.longitude);
						uni.setStorageSync('latitude', res.latitude);
						uni.setStorageSync('longitude', res.longitude);
						qqmapsdk.reverseGeocoder({
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: (re) => {
								console.log("解析地址成功", re);
								console.log(re.result.ad_info.city);
								console.log(re.result.ad_info.district);
								let city = re.result.ad_info.city
								let district = re.result.ad_info.district
								console.log('city-code', re.result.ad_info.city_code.substring(3));
								uni.setStorageSync('city_code', re.result.ad_info.city_code.substring(3));
								uni.setStorageSync('city', city.slice(0, 2));
								uni.setStorageSync('district', district);
								that.getRegionList()
								// that.position = city.slice(0, 2) + district.slice(0, 2)
							},
							fail: (re) => {
								console.log(re, '失败信息');
							}
						})
					},
					fail(err) {
						console.log("获取经纬度失败", err);
						uni.getSystemInfo({
							success: (res) => {
								if (!res.locationEnabled || !res.locationAuthorized) {
									uni.showModal({
										content: '检测到您没打开手机系统定位权限，请确保手机系统定位已开启',
										confirmText: "确认",
										showCancel: false,
										success: (res) => {
											if (res.confirm) {
												// uni.openSetting({
												// 	success: (res) => {
												// 		console.log(res);
												that.getUserLocation();
												// }
												// })
											} else {
												console.log('取消');
												return false;
											}
										}
									})
								} else {
									that.getUserLocation()
								}
							}
						})
					},
				});
			},
			//提示用户开启定位服务
			open() {
				var that = this
				uni.getSetting({
					success: function(res) {
						if (res.authSetting['scope.userFuzzyLocation']) {
							console.log('用户已经授权定位权限');
							uni.getSystemInfo({
								success: (res) => {
									if (!res.locationEnabled || !res.locationAuthorized) {
										uni.showModal({
											content: '检测到您没打开手机系统定位权限，请确保手机系统定位已开启',
											confirmText: "确认",
											showCancel: false,
											success: (res) => {
												if (res.confirm) {
													// uni.openSetting({
													// 	success: (res) => {
													// 		console.log(res);
													that.getUserLocation();
													// }
													// })
												} else {
													console.log('取消');
													return false;
												}
											}
										})
									} else {
										that.getUserLocation()
									}
								}
							})
							// that.getUserLocation()
						} else {
							console.log('用户未授权定位权限');
							uni.authorize({
								scope: 'scope.userFuzzyLocation',
								success: function() {
									this.isAuth = true
									console.log('授权成功');
									uni.getSystemInfo({
										success: (res) => {
											if (!res.locationEnabled || !res.locationAuthorized) {
												// uni.showToast({
												// 	title: '请确保手机系统定位已开启',
												// 	icon: 'none',
												// 	duration: 2000,
												// })
												uni.showModal({
													content: '检测到您没打开手机系统定位权限，请确保手机系统定位已开启',
													confirmText: "确认",
													showCancel: false,
													success: (res) => {
														if (res.confirm) {
															// uni.openSetting({
															// 	success: (res) => {
															// 		console.log(res);
															that.getUserLocation();
															// }
															// })
														} else {
															console.log('取消');
															return false;
														}
													}
												})
											} else {
												that.getUserLocation()
											}
										}
									})
								},
								fail: function() {
									console.log('授权失败');
									uni.showModal({
										content: '检测到您没打开手机系统定位权限，请确保手机系统定位已开启',
										confirmText: "确认",
										showCancel: false,
										success: (res) => {
											if (res.confirm) {
												uni.openSetting({
													success: (res) => {
														console.log(res);
														that.getUserLocation();
													}
												})
											} else {
												console.log('取消');
												return false;
											}
										}
									})
									return false;
								}
							})
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.home-base-bg {
		background-color: $uni-bg-color-grey;
		width: 100%;

		.home-content {
			margin: 0 10px;

			.service {
				position: fixed;
				right: 17rpx;
				top: 1109rpx;
				z-index: 1;

				.service-btn {
					position: absolute;
					top: 0;
					background-color: inherit;
					border-radius: 50%;
					width: 108rpx;
					height: 108rpx;
				}

				.service-btn::after {
					border: none;

				}
			}
		}

		.show-and-search {
			display: flex;

			.list-tab {
				z-index: 2;
				width: 259rpx;
				height: 70rpx;
				background: #B7EBD2;
				border-radius: 11px 100px 0px 0px;
				color: #fff;
				font-size: 15px;
				line-height: 21px;
				font-weight: 500;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.search-tab {
				z-index: 1;
				transform: translateX(-61rpx);
			}

			.tab-activate {
				background: linear-gradient(#E86262, #CC3333);
				z-index: 3;
			}
		}
	}
</style>