<template>
	<view class="content">
		<!-- 顶部导航 -->
		<uni-nav-bar :border="false" @clickLeft="toUserCenter" background-color="#fff" title="智能快洗" :status-bar="true" :fixed="true"
		 color="rgb(255,0,0)">
			<view style="padding-left: 20rpx;" slot="left">
				<u-image width="40rpx" height="60rpx" mode="aspectFit" src="/static/img/person.png"></u-image>
			</view>
		</uni-nav-bar>
		<!-- 页面主体 -->
		<view class="pageContent">
			<map id="map" :latitude="lat" :longitude="lng" scale="10" show-compass :markers="markers" @markertap="markertap"
			 show-location style="width: 100%; height:100%;">
				<!-- 信息提示 -->
				<cover-view class="work-message" v-if="workStatus=='working'" @click="toWork">
					<cover-view class="work-message-in">
						<cover-view class="view">洗车机正在工作中...</cover-view>
						<cover-view class="view">点击进入</cover-view>
					</cover-view>
				</cover-view>
				<!-- 左边控件 -->
				<view class="cover-view">
					<view class="flex-wrp">
						<cover-view @click="intoList" class="flex-item">
							<cover-image class="img" src="/static/img/index-list.png"></cover-image>
							<cover-view>网点列表</cover-view>
						</cover-view>
						<cover-view @click="openPop" class="flex-item">
							<cover-image class="img" src="/static/img/index-call.png"></cover-image>
							<cover-view>联系客服</cover-view>
						</cover-view>
						<!-- <cover-view class="flex-item">
							<cover-image class="img" src="/static/img/index-discount.png"></cover-image>
							<cover-view>优惠活动</cover-view>
						</cover-view> -->
					</view>
				</view>
				<!-- 地图移动后返回原位置控件 -->
				<view class="cover-location">
					<cover-image class="img" @click="moveToLocation" src="/static/img/location.png"></cover-image>
				</view>
				<view class="cover-bottom">
					<button @click="scanCode" type="warn">
						<u-icon name="scan" color="#fff" size="38"></u-icon>
						扫码洗车
					</button>
				</view>
			</map>
			<!-- 用户未授权提示框 -->
			<u-modal v-model="showPop" @confirm="intoSetting" :show-cancel-button='false' 
			 confirm-text="设置" title="温馨提示" content="无法获取位置信息,请设置允许使用位置信息" width="70%"></u-modal>
		</view>
	</view>
</template>

<script>
	import uniNavBar from "@/components/uni-nav-bar/uni-nav-bar.vue"
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import {
		checkLogin
	} from '@/api/login.js'
	import {
		getMapStoreList
	} from '@/api/store.js'
	import {
		getLookUpDatas
	} from '@/api/data.js'
	export default {
		components: {
			uniNavBar,
			uniPopup
		},
		data() {
			return {
				workStatus: 'stop',
				mapCtx: null, // 地图对象
				markers: [], // 标注点
				lng: '',
				lat: '',
				showPop: false // 是否显示用户未授权提示框
			}
		},
		onReady() {
			this.mapCtx = uni.createMapContext('map')
		},
		onShow() {
			this.workStatus = this.$store.state.vuex_workStatus
			this.getUserLocation()
		},
		onLoad() {
			// 获取订单状态数据字典
			this.getCodeList('ORDER_STATUS')
			// 获取支付方式数据字典
			this.getCodeList('PAY_TYPE')
			// 获取网点标签数据字典
			this.getCodeList('STORE_LABEL')
		},
		methods: {
			// 获取数据字典
			getCodeList(code) {
				getLookUpDatas({
					type: code
				}).then(res => {
					if (res.status == 200) {
						console.log(res.data, 'res.data')
						switch (code) {
							case 'ORDER_STATUS':
								this.$u.vuex('vuex_payStatus', res.data)
								break;
							case 'PAY_TYPE':
								this.$u.vuex('vuex_payType', res.data)
								break;
							case 'STORE_LABEL':
								this.$u.vuex('vuex_storeLabel', res.data)
								break;
							default:
								break;
						}
					}
				})
			},
			// 如果机器正在运行，提示并点击跳转的运行界面
			toWork() {
				uni.navigateTo({
					url: "/pages/work/index/index"
				})
			},
			// 用户位置信息授权
			getUserLocation() {
				let _this = this
				// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userLocation" 这个 scope  H5及APP平台不适用
				// H5及APP平台适配代码
				// #ifndef H5 || APP-PLUS
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success(res) {
									// 用户已经同意小程序使用位置信息，后续调用 uni.getLocation 接口不会弹窗询问
									_this.getLocation()
								},
								// 用户拒绝授权位置信息时默认展示青海西宁位置地图
								fail: (err) => {
									_this.showPop = true
								}
							})
						} else {
							_this.getLocation()
						}
					}
				})
				// #endif
			},
			// 打开位置设置界面
			intoSetting () {
				let _this = this
				uni.openSetting({
					success(res) {
						console.log(res,'222')
						let data = res.authSetting
						if (data['scope.userLocation']) {
							_this.showPop = false
							_this.getLocation()
						} else {
							_this.showPop = true
						}
					},
					fail() {
						_this.showPop = true
					}
				})
			},
			// 获取用户位置
			getLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log(res, 'rrrr')
						this.showPop = false
						let latitude = res.latitude;
						let longitude = res.longitude;
						this.lng = longitude
						this.lat = latitude
						this.markers = this.getMarkersData()
					},
					// 定位失败默认展示青海西宁位置地图
					fail: (err) => {
						this.lng = '101.760521'
						this.lat = '36.636193'
						this.markers = this.getMarkersData()
					}
				});
			},
			// 点击标点进入网点详情
			markertap(e) {
				console.log(e)
				uni.navigateTo({
					url: `/pages/store/storeDetail?id=${e.markerId}`
				})
			},
			// 获取所有标记点数据
			getMarkersData() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					lat: this.lat,
					lng: this.lng
				}
				getMapStoreList(params).then(res => {
					uni.hideLoading()
					if (res.status == 200) {
						let markData = res.data
						let markers = [];
						for (let item of markData) {
							let marker = this.createMarker(item);
							markers.push(marker)
						}
						this.markers = markers
						console.log(this.markers, '111111')
					} else {
						this.toashMsg(res.message)
					}
				})

			},
			// 点击回到定位坐标点
			moveToLocation() {
				this.mapCtx.moveToLocation()
			},
			// 进入个人中心
			toUserCenter() {
				// 检验是否登录或登录是否过期
				checkLogin().then(res => {
					if (res.status == '200') {
						uni.navigateTo({
							url: '/pages/userCenter/index'
						})
					} else if (res.status == '9001') {
						uni.navigateTo({
							url: `/pages/login/login?lanuch=${false}&path=` + encodeURIComponent('/pages/userCenter/index')
						})
					}
				})
			},
			// 打开网点列表
			intoList() {
				uni.navigateTo({
					url: '/pages/store/storeList'
				})
			},
			// 联系客服
			openPop() {
				let _this = this
				uni.showActionSheet({
					itemList: ['电话客服'],
					success: function(res) {
						//电话客服
						if (res.tapIndex == 0) {
							_this.callPhone()
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			// 电话客服
			callPhone() {
				uni.makePhoneCall({
					phoneNumber: '114'
				})
			},
			// 扫码洗车
			scanCode () {
				let _this = this
				// 检验是否登录或登录是否过期
				checkLogin().then(res => {
					if (res.status == '200') {
						uni.scanCode({
						    success: function (res) {
						        console.log('条码类型：' + res.scanType);
						        console.log('条码内容：' + res.result);
								// if(res.scanType !== 'WX_CODE'){
								// 	_this.toashMsg("无法识别此二维码")
								// }
								uni.navigateTo({
									url: res.result
								})
						    }
						});
						
						// uni.navigateTo({
						// 	url: `/pages/getOrder/getOrder?scene=100037,9998`
						// })
					} else if (res.status == '9001') {
						uni.navigateTo({
							url: `/pages/login/login?lanuch=${false}&path=` + encodeURIComponent('/pages/index/index')
						})
					}
				})
			},
			// 创建标记点 OPEN ：正常营业  CLOSED:暂停营业  TO_BE_OPENED:待开业
			createMarker(point) {
				let latitude = point.lat;
				let longitude = point.lng;
				let iconPath = ''
				if (point.businessStatus === 'CLOSED') {
					iconPath = '/static/img/store-dky.png'
				} else if (point.businessStatus === 'OPEN') {
					let today = new Date().toLocaleDateString() // 获取今天日期
					let beginTime = today + ' ' + point.beginTime
					let endTime = today + ' ' + point.endTime
					let beginTimeStamp = new Date(beginTime).getTime()  // 获取开始时间戳
					let endTimeStamp = new Date(endTime).getTime()  // 获取结束时间戳
					let nowTimeStamp = new Date().getTime() // 获取当前时间戳
					// 结束时间小于开始时间时 为跨天 结束时间应加1天
					endTimeStamp = endTimeStamp <=beginTimeStamp ? (endTimeStamp+24*60*60*1000) : endTimeStamp
					// 根据当前时间判断目前是否在营业时间范围内
					if (nowTimeStamp>=beginTimeStamp && nowTimeStamp<=endTimeStamp) {
						iconPath = '/static/img/store.png'
					} else {
						iconPath = '/static/img/store-dky.png'
					}
				} else {
					iconPath = '/static/img/store-zt.png'
				}
				let marker = {
					iconPath: iconPath,
					id: point.id || 0,
					name: point.name || '',
					latitude: latitude,
					longitude: longitude,
					width: 30,
					height: 49,
					callout: {
						content: point.name,
						fontSize: 14,
					}
				};
				return marker;

			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 0;

		.pageContent {
			width: 100%;
			flex: 1;

			.work-message {
				position: absolute;
				top: 6%;
				width: 80%;
				left: 50%;
				margin-left: -40%;
				background: rgba(0, 0, 0, 0.6);
				border-radius: 100rpx;
				color: #eee;

				.work-message-in {
					display: flex;
					align-items: center;
					padding: 26rpx;

					.view {
						&:first-child {
							flex-grow: 1;
							text-align: center;
						}

						&:last-child {
							font-size: 24rpx;
							color: #fff;
							display: flex;
							align-items: center;
						}
					}
				}
			}

			.cover-view {
				position: absolute;
				top: calc(60% - 150rpx);
				left: calc(50% - 360rpx);

				.flex-wrp {
					display: flex;
					flex-direction: column;
					background: rgba(0, 0, 0, 0.3);
					border-radius: 10rpx;
					padding: 10rpx 0;
				}

				.flex-item {
					width: 110rpx;
					height: 110rpx;
					font-size: 24rpx;
					color: #F8F8F8;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.img {
						width: 50rpx;
						height: 50rpx;
						margin-bottom: 10rpx;
					}
				}
			}

			.cover-location {
				position: absolute;
				top: calc(75%);
				left: calc(85%);

				.img {
					width: 80rpx;
					height: 80rpx;
				}
			}

			.cover-bottom {
				position: absolute;
				bottom: calc(60rpx);
				width: 80%;
				left: calc(9%);

				uni-button[type=warn] {
					background: red;

					u-icon {
						margin-right: 15rpx;
					}
				}
			}

		}


	}
</style>
