<template>
	<view>
		<view class="lf-p-t-20 head" v-if="tab_list_father.length">
			<u-tabs :list="tab_list_father" :is-scroll="true" :current="current_father" @change="tabChangeFather()"></u-tabs>
		</view>
		<view>
			<map class="lf-map-height" :longitude="self_longitude" :latitude="self_latitude" :markers="markers_list" :scale="4" @markertap="markertap" @callouttap="callouttap">
			</map>
		</view>
		<view class="lf-m-t-40 lf-p-l-32 lf-p-r-32">
			<view class="lf-row-between lf-m-b-40">
				<view class="lf-font-32 lf-color-222">商品列表</view>
				<view class="lf-font-24 lf-color-blue lf-row-center" style="width: 520rpx; justify-content: flex-end;" v-if="self_latitude && self_longitude && address">
					<text class="lf-iconfont lf-icon-dingwei lf-m-r-10 lf-font-22"></text>
					<text class="lf-line-1">{{ address }}</text>
				</view>
				<view class="lf-font-24 lf-color-blue lf-row-center" @click="getShopDistance()" v-else>
					<text class="lf-iconfont lf-icon-dingwei lf-m-r-10 lf-font-22"></text>
					我的位置
				</view>
			</view>
			<view class="special_tab" style="position: relative;">
				<u-tabs :list="tab_list" active-color="#1998FE" inactive-color='#777777' :is-scroll="true" @click="clicksort" :current="current" @change="tabChange"></u-tabs>
				<view style="position: absolute;right: 44rpx;top: 20rpx;display: flex;flex-direction: column;">
					<u-icon name="arrow-up" style="font-size: 20rpx;" :class="(current == 2 && sort == 0) ? 'lf-color-blue' : ''"></u-icon>
					<u-icon name="arrow-down" style="font-size: 20rpx;" :class="(current == 2 && sort == 1) ? 'lf-color-blue' : ''"></u-icon>
				</view>
			</view>
			<swiper :style="{height: 'calc('+ windowHeight +'px - 110rpx)', width: '100%'}" :current="current" @change="swiperChange">
				<swiper-item v-for="(tabItem, tabIndex) in tab_list" :key="tabIndex">
					<scroll-view class="com" :scroll-y="true" :refresher-enabled="true" :refresher-triggered="tabItem.isRefresher" @scrolltolower="onScrolltolower" @refresherrefresh="onRefresherrefresh">
						<view class="lf-m-t-20"></view>
						<view>
							<!-- 活动列表 -->
							<view class="content">
								<view class="item"  v-for="(item,index) of tabItem.list" :key="index">
									<!-- <view class="cover">
										<image :src="item.picture" class="lf-w-100 lf-h-100" mode="aspectFill"></image>
									</view>
									<view style="width: 420rpx;">
										<view class="lf-font-28 lf-color-333 lf-line-2">{{item.title}}</view>
										<view class="lf-font-24 lf-color-gray lf-line-2 lf-m-t-10" style="min-height: 64rpx;">本套票只包含两个成人不可带小孩本套票只包含两个成人不可带小孩本套票只包含两个成人不可带小孩</view>
										<view class="lf-flex lf-m-t-25">
											<lf-price :price="item.price"></lf-price>
											<text class="lf-font-24 lf-color-gray lf-line-through lf-m-l-15">¥{{item.original_price}}</text>
										</view>
									</view> -->
									<view class="lf-row-between lf-m-t-40">
										<view class="lf-row-between" @click="$url('/pages/goodsDetail/index?goods_id='+item.id);">
											<view class="lf-m-r-20">
												<image style="width: 90rpx;height: 90rpx;border-radius: 10rpx;" :src="item.picture" mode="aspectFill"></image>
											</view>
											<view class="lf-flex-column">
												<view class="lf-font-28 lf-color-222 lf-line-1" style="width: 576rpx;">{{item.title}}</view>
												<view style="width: 100%; display: flex; justify-content: space-between; align-items: flex-end;">
													<view class="lf-font-24 lf-color-999 lf-flex lf-m-t-18" style="width: 440rpx;">
														<view>
															<text class="lf-iconfont lf-icon-dingwei1" style="font-size: 10px!important;"></text>
														</view>
														<view class="lf-line-2 lf-m-l-10" style="max-width: 440rpx;">
															<block v-if="item.address">
																<text>{{ item.address }}</text>
																<text class="lf-m-l-10 lf-m-r-10">|</text>
															</block>
															<text>{{item.distance_m | kmUnit}}</text>
														</view>
													</view>
													<view style="width: 134rpx;">
														<view @click="openMap(item.address,item.latitude,item.logitude)" style="display: flex; justify-content: flex-end;">
															<text class="lf-iconfont lf-icon-daohang"></text>
														</view>
														<view class="lf-font-24 lf-color-price lf-text-right">￥{{ item.price }}</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
							<!-- 加载 -->
							<view class="loading-more">
								<text v-if="tabItem.list.length" :class="{'loading-more-text': loadingClass}">{{ loadingText }}</text>
								<lf-nocontent v-else></lf-nocontent>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
			<!-- 回到顶部 -->
			<u-back-top :scroll-top="pageScrollTop" :custom-style="{background: 'rgba(51, 51 51, 0.3)'}"></u-back-top>
		</view>
	</view>
</template>ß

<script>
	let QQMapWX = require('@/common/qqmap-wx-jssdk.min.js');
	let qqmapsdk = new QQMapWX({
	    key: 'GB3BZ-7W2CU-LW3VH-B7ZIF-XRKSF-D3FOL'
	});
	
	export default {
		data() {
			return {
				tab_list_father: [],
				current_father: 0,
				windowHeight: 0,
				markers_list: [],
				self_latitude: '',
				self_longitude: '',
				//排序
				tab_list: [
					{
						id: 1,
						name: '销量',
						list: [],
						isRefresher: false,
						loadingClass: true,
						loadingText: '正在加载中',
						page: 1,
						isPage: true,
						type: 1
					},
					{
						id: 2,
						name: '距离',
						list: [],
						isRefresher: false,
						loadingClass: true,
						loadingText: '正在加载中',
						page: 1,
						isPage: true,
						type: 4
					},
					{
						id: 4,
						name: '价格',
						list: [],
						isRefresher: false,
						loadingClass: true,
						loadingText: '正在加载中',
						page: 1,
						isPage: true,
						type: 3
					},
				],
				current: 0,
				loadingClass: false,
				loadingText: '已加载全部数据~',
				page: 1,
				isPage: true,
				pageSize: 20,
				sort: 0,
				address: '',
				downloadImages: [] // 已下载过的图片缓存
			}
		},
		onLoad() {
			this.windowHeight = getApp().globalData.windowHeight;
			this.getShopDistance().then(() => {
				this.getCategory();
			}).catch(() => {
				uni.showModal({
					title: '',
					content: '获取位置失败！',
					showCancel: false
				})
			})
			// 腾讯地图KEY： GB3BZ-7W2CU-LW3VH-B7ZIF-XRKSF-D3FOL
		},
		filters: {
			kmUnit(m){
			    var v;
				if(typeof m === 'number' && !isNaN(m)){
					if (m >= 1000) {
			            v = (m / 1000).toFixed(2) + 'km'
			        } else {
			           	v = m + 'm'
			        }
				}else{
					v = '0m'
				}
			    return v;
			}
		},
		methods: {
			// 点击标记时触发
			markertap(e){
				let id = e.detail.markerId;
				this.$url('/pages/goodsDetail/index?goods_id='+ id);
			},
			// 点击marker对应的气泡时触发
			callouttap(e){
				let id = e.detail.markerId;
				this.$url('/pages/goodsDetail/index?goods_id='+ id);
			},
			// 打开地图
			openMap(address, lat, lng) {
				// let { address, lat, lng } = this.goods_detail?.store || {};
				uni.openLocation({
					longitude: Number(lng),
					latitude: Number(lat),
					scale: 20,
					name: address
				});
			},
			//获取当前位置 计算商店距离
			getShopDistance() {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: '正在获取您的位置'
					})
					uni.getLocation({
					 type: 'gcj02',
					 isHighAccuracy: true,
					 success (res) {
					   uni.hideLoading();
					   that.self_latitude = res.latitude;
					   that.self_longitude = res.longitude;
					   that.getAddressInfo();
					   resolve();
					 },
					 fail(err) {
						 console.log(err)
						 uni.hideLoading();
						 reject();
					 }
					})
				})
			},
			// 根据坐标获取地址信息
			getAddressInfo(){
				qqmapsdk.reverseGeocoder({
					location: {
						latitude: this.self_latitude,
						longitude: this.self_longitude
					},
					success: res => {
						this.address = res.result.address;
					},
					fail: err => {
						console.log("调用失败！", err);
					}
				})
			},
			tabChangeFather(index){
				this.current_father = index;
				this.clearTabItem()
				if(this.tab_list_father[index].list.length <= 0){
					this.getActivityList(); // tab下没有数据，请求第一页
				}
			},
			clearTabItem(){
				let tab_item = this.tab_list[this.current];
				tab_item.page = 1;
				tab_item.isPage = true;
				tab_item.isRefresher = true;
				tab_item.loadingClass = true;
				tab_item.loadingText = '正在加载中';
				tab_item.list = [];
				this.markers_list = [];
			},
			getCategory(options = {}) {
				this.$http(this.API.API_CATEGORYLIST).then(res => {
					let res_list = res.data || [];
					let tab_list_father = res_list.map(item => {
						return {
							id: item.id,
							name: item.name,
							list: [],
							isRefresher: false,
							loadingClass: true,
							loadingText: '正在加载中',
							page: 1,
							isPage: true,
							pid: item.pid
						}
					});
					let list = []
					tab_list_father.forEach((item,index) => {
						if(item.pid == 0) {
							list.push(item)
						}
					})
					this.tab_list_father = list;
					this.getActivityList()
				}).catch(err => {
					
				})
			},
			clicksort(index) {
				if(index == 2) {
					if(this.sort == 0) {
						this.sort = 1
					}else {
						this.sort = 0
					}
					this.getActivityList()
				}else {
					return
				}
			},
			tabChange(index){
				this.current = index;
				this.getActivityList()
			},
			// 滑块下标值变化
			swiperChange(event){
				this.current = event.detail.current;
				if(event.detail.source == '') return; // 如果是被动出发，没有事件类型则不做处理
			},
			changeSort(sort) {
				this.sort != this.sort
				this.getActivityList()
			},
			// scroll-view 下拉刷新
			onRefresherrefresh(){
				this.tab_list[this.current].isRefresher = true;
				this.$u.throttle(() => {
					this.clearTabItem();
					this.getActivityList();
				}, 200);
			},
			// 页面触底，加载下一页
			onScrolltolower(){
				let tab_item = this.tab_list[this.current];
				if(tab_item.isPage){
					tab_item.page = tab_item.page + 1;
					this.getActivityList();
				}
			},
			getActivityList(){
				let tab_item1 = this.tab_list_father[this.current_father];
				let tab_item = this.tab_list[this.current];
				let sort_type = this.tab_list[this.current].type;
				console.log('页数',tab_item.id)
				if(this.$shared.isValueType(tab_item) == 'undefined') return;
				this.$http(this.API.API_ADVICELIST, {
					lat: this.self_latitude,
					lng: this.self_longitude,
					page: tab_item.page,
					category_id: tab_item1.id,
					type: sort_type,
					by: this.sort,
				}).then(res => {
					let isPage = res.data.next_page_url == null?false:true;
					tab_item.isPage = isPage;
					if(!isPage){
						tab_item.loadingClass = false;
						tab_item.loadingText = '没有更多数据啦~';
					}
					this.tab_list[this.current].isRefresher = false;
					
					if(tab_item.page == 1){
						tab_item.list = res.data.data;
					}else{
						tab_item.list.push(...res.data.data);
					}
					console.log("res", res);
					// let res_list = res.data.data || [];
					this.createMarkers(tab_item.list);
				}).catch(err => {
					
				})
			},
			// 将iconPath下载到本地，然后生成markers渲染出来
			createMarkers(res_list){
				let markers_self = [];
				let p_list = []; // 异步队列
				// let downloadImages = JSON.parse(JSON.stringify(this.downloadImages)); // PS: 已下载过的图片缓存，如果需要显示market图片时打开这行注释！！！！
				uni.showLoading({
					title: '加载地图信息中'
				})
				res_list.map(item => {
					let itemP = new Promise((resolve, reject) => {
						let tempFilePath = '../../static/market_icon.png';
						let obj = {
							id: item.id,
							name: item.title,
							address: item.address,
							latitude: Number(item.latitude),
							longitude: Number(item.longitude),
							iconPath: tempFilePath,
							width: 30,
							height: 30,
							callout: {
								content: item.title,
								fontSize: 14,
								textAlign: 'center',
								bgColor: "#fff",
								borderRadius: 14,
								padding: 4,
								display: "ALWAYS"
							}
						};
						
						
						/*  PS：此处代码为在market上显示图片，因加载较慢，注释掉
						let image = downloadImages.filter(function(f_item, f_index, f_arr){
							return f_item.id == item.id;
						});
						
						if(image.length > 0){
							// 找到缓存匹配项
							tempFilePath = image[0].url;
							obj.iconPath = image[0].url;
							markers_self.push(obj);
							resolve();
						}else{
							// 未放入缓存，将执行download
							uni.downloadFile({
								url: item.picture,
								complete: result => {
									if (result.statusCode === 200) {
										tempFilePath = result.tempFilePath;
									}
									obj.iconPath = tempFilePath;
									markers_self.push(obj);
									downloadImages.push({
										id: item.id,
										url: tempFilePath
									});
									resolve();
								}
							})
						}
						*/
					   markers_self.push(obj);
					   resolve(); // PS: 如果需要打开注释代码时，请将这两行代码删除！！！！
					});
					p_list.push(itemP);
				});
				Promise.all(p_list).then(res => {
					// this.downloadImages = JSON.parse(JSON.stringify(downloadImages)); // PS: 如果需要显示market图片时打开这行注释！！！！
					this.markers_list = markers_self;
					uni.hideLoading();
				})
			}
		}
	}
</script>

<style lang="scss" scoped> 
	.com{
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		// padding: 0rpx 28rpx;
	}
	.lf-map-height {
		width: 100%;
		height: 500rpx;
	}
	/deep/.special_tab .u-scroll-box {
		display: flex;
		justify-content: center;
		align-items: center;
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
	}
	/deep/.special_tab .u-scroll-box .u-tab-bar {
		background-color: #1998FE!important;
		width: 80rpx!important;
		position: absolute;
		left: 0;
		bottom: -12rpx;
	}
	
	/deep/.special_tab .u-tabs .u-scroll-box .u-tab-bar {
		background-color: #1998FE!important;
		width: 56rpx!important;
		position: absolute;
		height: 5rpx!important;
		left: 8rpx;
		bottom: -4rpx;
	}
	
	/deep/.special_tab .u-tab-item {
		font-size: 28rpx!important;
	}
</style>
