<template>
	<view class="hotel-list column" style="background: #F3F1EF;">
		<view class="hotel-listHeader">
				<hotelHeaders :title="pageTitle"></hotelHeaders>
				<hotelSearch 
				:msg="searchObj" 
				:MapType="MapType"
				@change="change"
				@getItem="getItem"></hotelSearch>
		</view>
		<view style="height: 1px;flex: 1;overflow: hidden;position: relative;">
            <!-- 
				:latitude="latitude" 
				:longitude="longitude" 
				:markers="covers" 

				:longitude="center.longitude"
            	:latitude="center.latitude"
			-->
			<map id="myMap" ref="myMapRef" style="width: 100%; height: 100%;" 
            :longitude="center.longitude"
            :latitude="center.latitude"
            :markers="markers"
            @callouttap="handleCalloutClick"
            >
            </map>
			<img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638761008788457858.png"
            class="hotelPosition" @click="getLocation"/>
			<view class="hotelMapListBox">
				<swiper class="swiper" circular 
				:indicator-dots="indicatorDots" 
				:autoplay="autoplay" 
				:interval="interval"
				:duration="duration"
				:current="current"
				@change="changeCurrent"
				:previous-margin="'14rpx'"
				:next-margin="'14rpx'">
					<swiper-item 
					v-for="(item,index) in HotelList" :key="index"
					class="hotelMapListSwp"
					:class="[
						prevCurrent==index?'activePrev':'',
						current==index?'active':'',
						nextCurrent==index?'activeNext':'',]">
						<view class="hotelMapList">
							<hotel-good :item="item" :searchObj="searchObj" :isMap="1"></hotel-good>
						</view>
					</swiper-item>
				</swiper>
			</view>
		</view>
		
	</view>
</template>

<script>
	import rangeSlider from "./components/range-slider.vue";
	import canlendar from "./components/time/index";
	import hotelGood from "./components/hotel-good.vue";
	import Address from "./components/address/smh-address-indexed.vue";
	import hotelHeaders from "@/components/header/header";
    import hotelSearch from "./components/search.vue";
	export default {
		data() {
			return {
				pageTitle: '',
				city: "",
				searchObj: {
					pageIndex: 1,
					pageSize: 15,
					KeyWords: "", //关键字
				},
				day: 0,
				startDay: "",
				endDay: "",
				HotelList: [], //酒店数据
				tempRateAndPrice: {
					price: {},
					priceText: "不限",
					rate: [],
				},
				loadText: {
					loadmore: "轻轻上拉，加载更多",
					loading: "努力加载中",
					nomore: "没有更多商品了",
				},
				showLoading: false,
				status: "loadmore",
				page_count: 0,
				dayObj: {},
				mc: '',
                center: { longitude: 116.397428, latitude: 39.90923 },
                markers: [],
				markersObj:{
					id: null,
					latitude: 39.909,
					longitude: 116.39742,
					iconPath: '',
					title: '',
					alpha: 0,
					width: 20,
					height: 30,
					callout:{
						content:'¥ 99999起',
						bgColor: '#FF3166',
						borderWidth: 1,
						borderColor: '#E2D5D2',
						color: '#fff',
						fontSize: '12px',
						fontWeight: 'bold',
						anchorX: 0,
						anchorY: 0,
						borderRadius: 7,
						padding: 5,
						display: 'ALWAYS',
					},
				},
				bubble:[
					'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638761641584224459.png',
					'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638761646347047352.png',
					'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638761646386246237.png',
				],
				calloutStyle:{
					content:'',
					bgColor: '',
					borderWidth: 1,
					borderColor: '#E2D5D2',
					color: '',
					fontSize: '12px',
					fontWeight: 'bold',
					anchorX: 0,
					anchorY: 0,
					borderRadius: 7,
					padding: 5,
					display: 'ALWAYS',
				},
				editCallout1:{
					bgColor: '#FF3166',
					color: '#fff',
				},
				editCallout2:{
					bgColor: '#FEEEF2',
					color: '#FF3166',
				},
				editCallout3:{
					bgColor: '#F3F1EF',
					color: '#C7C6C6',
				},
				indicatorDots: false,
				autoplay: false,
				interval: 2000,
				duration: 500,
				prevCurrent: null,
				current: 0,
				nextCurrent: null,
				padding: [20, 20, 20, 20],
				MapType: 0,
				includePoints: [],
				scale: 13,
				mapCtx: null,
			};
		},
		components: {
			rangeSlider,
			canlendar,
			hotelGood,
			Address,
			hotelHeaders,
            hotelSearch,
		},
		onLoad(options) {
			this.mc = this.$uiConfig.mainColor;
			if (options && options.msg) {
				this.searchObj = JSON.parse(decodeURIComponent(options.msg))
				this.pageTitle = this.searchObj.CityName
			}
			uni.getStorage({
				key: "Time",
				success: (res) => {
					let obj = JSON.parse(res.data);
					this.startDay = obj.startDay;
					this.endDay = obj.endDay;
					this.day = obj.day;
					this.dayObj = obj
					this.searchObj.QStartDate = obj.start;
					this.searchObj.QEndDate = obj.end;
				},
			});
			this.MapType = options.MapType?options.MapType:0;
		},
		created() {
			uni.setNavigationBarTitle({
				title: "酒店",
			});
			
			
		},
		mounted() {
			// #ifdef MP-WEIXIN
			this.initMiniProgramMap();
			// #endif
		},
		methods: {
			initMiniProgramMap(){
				let that = this
				const query = wx.createSelectorQuery().in(this);
				query.select('#myMap').fields({
					node: true,
					size: true
				}, (res) => {
					that.mapCtx = wx.createMapContext('myMap');
				}).exec();
			},
			fitMapToBounds() {
				if (!this.mapCtx || this.includePoints.length === 0) return;
				this.mapCtx.includePoints({
					points:this.includePoints,
					padding: [20,40,20,40],
				});
			},
			getItem(parameters,obj) {
				this.searchObj = parameters
				this.dayObj = {
					...obj,
					startTime: `${obj.year}-${obj.startDay}`,
					endTime: `${obj.year}-${obj.endDay}`
				}
				uni.setStorage({
					key: "Time",
					data: JSON.stringify(this.dayObj),
				});
			},
            handleCalloutClick(marker) {
				for (let i = 0; i < this.markers.length; i++) {
					if(this.markers[i].id==marker.detail.markerId){
						this.current = i
					}
				}
				this.setNewMarkers()
            },
			setNewMarkers(){
				for (let i = 0; i < this.markers.length; i++) {
					if(i==this.current){
						// this.center = {
						// 	longitude: this.markers[i].longitude,
						// 	latitude: this.markers[i].latitude,
						// }
						this.markers[this.current] ={
							...this.markers[i],
							callout:{
								...this.markers[i].callout,
								...this.editCallout1,
							}
						}
					}else{
						this.markers[i] ={
							...this.markers[i],
							callout:{
								...this.markers[i].callout,
								...this.editCallout2,
							}
						}
					}
				}
				this.$forceUpdate()
			},
            getLocation() {
				let that = this
                wx.getLocation({
                    type: 'wgs84', // 精度模式
                    success: (res) => {
						that.fitMapToBounds();
                        // 更新地图中心点
                    },
                    fail: (err) => {
                        wx.showModal({
                            title: '提示',
                            content: '授权失败，请检查定位权限'
                        });
                    }
                });
            },
			changeCurrent(e) {
				this.prevCurrent = this.current
				this.current = e.detail.current;
				this.setNewMarkers()
				if(this.HotelList.length-1==this.current&&this.searchObj.pageIndex < this.page_count){
					this.lower()
				}else{
					let length = this.HotelList.length
					if((length-1)==this.current){
						this.nextCurrent = 0
					}else this.nextCurrent = this.current+1
				}
			},
			research() {
				this.getList(1);
			},
			lower() {
				// TODO: 滚动到了底部，实现翻页加载
				if (this.searchObj.pageIndex < this.page_count) {
					this.status = "loading";
					this.searchObj.pageIndex++;
					this.getList();
				} else {
					this.status = "nomore";
				}
			},
			change(item) {
				this.searchObj = {
					...item,
				}
				if(item.CityName) this.pageTitle = item.CityName
				this.getList();
			},
			//获取列表数据
			async getList(type) {
				if(this.showLoading) return
				this.showLoading = true
				uni.showLoading();
				this.searchObj.QStars = this.tempRateAndPrice.rate.toString();
				if (type == 1||this.searchObj.pageIndex==1) {
					this.HotelList = [];
					this.markers = []
					this.includePoints = []
				}
				await this.apipost( "dmc_post_B2BAndB2CGetDidaHotelPage", this.searchObj,
					(res) => {
						uni.hideLoading()
						if (res.resultCode == 1) {
							this.showLoading = false
							let length = 0
							if (this.searchObj.pageIndex === 1) {
								this.HotelList = res.data.pageData;
								length = this.HotelList.length
								if(res.data.pageData.length==0){
									uni.showToast({
										title: '暂无相关数据',
										icon: 'none',
										duration: 2000
									});
								}
							} else {
								this.HotelList = this.HotelList.concat(res.data.pageData);
								length = this.HotelList.length
							}
							this.setMarkers(res.data.pageData)
							this.page_count = res.data.pageCount;
							this.prevCurrent = length-1
							if((length-1)==this.current){
								this.nextCurrent = 0
							}else this.nextCurrent = this.current+1
						}
					},
					(err) => {
						this.showLoading = false
						uni.hideLoading()
					}
				);
			},
			async setMarkers(pageData){
				if(pageData.length==0) return
				for (let i = 0; i < pageData.length; i++) {
					this.includePoints.push({
						latitude: pageData[i].latitude,
						longitude: pageData[i].longitude,
					})
					let obj = JSON.parse(JSON.stringify(this.markersObj))
					obj = {
						...obj,
						id: pageData[i].hotelid,
						latitude: pageData[i].latitude,
						longitude: pageData[i].longitude,
						callout:{
							...obj.callout,
							content: `CNY ${pageData[i].unitprice}起`,
							...this.editCallout2
						}
					}	
					if(i==0&&this.searchObj.pageIndex===1){
						obj.callout = {
							...obj.callout,
							...this.editCallout1,
						}
						// this.center = {
						// 	longitude: pageData[0].longitude,
						// 	latitude: pageData[0].latitude,
						// }
					}
					this.markers.push(obj)
				}
				setTimeout(() => {
					this.$nextTick(() => {
						this.fitMapToBounds();
					});
				}, 500);

				this.$forceUpdate()
			}
		},
	};
</script>

<style lang="scss" scoped>
@import url("@/asset/css/flex.css");
.hotel-list{
    height: 100vh;
	overflow: hidden;
}
.hotel-listHeader{
    background: #F3F1EF ;
}
.hotelPosition{
    position: fixed;
    right: 19rpx;
    bottom: 403rpx;
    width: 94rpx;
    height: 108rpx;
    z-index: 9;
}
.hotelMapListBox{
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 9;
	height: 396rpx;
}
.hotelMapListSwp{
	
}
.hotelMapListSwp.activePrev .hotelMapList{
	
}
.hotelMapListSwp.active .hotelMapList{
	margin-left: 17rpx;
	margin-right: 17rpx;
	margin-top: 0;
}
.hotelMapListSwp.activeNext .hotelMapList{
	
}
.hotelMapList{
	background: #fff;
	padding: 33rpx 33rpx;
	border-radius: 14rpx;
	margin-top: 24rpx;
}
.hotelScroll{
	height: 300rpx;
}
.swiper {
	height: 328rpx;
}
.swiper-item {
	height: 304rpx;
}
/deep/.search-box .u-input{
		font-size: 24rpx;
	}
/deep/.hotel-listHeader .u-dropdown__menu{
	justify-content: space-between;
}
/deep/.hotel-listHeader .u-dropdown__menu__item {
	flex: inherit !important;
}
/deep/.hotel-listHeader .u-flex{
	justify-content: flex-start;
}

</style>
