<template>
	<ax-body hide-indicator-area :style="[StyleSheet]">
		<!-- 标题栏 -->
		<template #title>
			<view class="titlebar">
				<image src="@/static/img/title.png" class="page-title"></image>
				<!-- <text class="page-subtitle">“特惠充电享不停”</text> -->
			</view>
		</template>
		<view class="base">
			<!-- 搜索块 -->
			<view id="search" class="app-flex search-view">
				<view class="locate-city">
					<image src="@/static/img/locate.svg" class="_icon"></image>
					<text class="__name">{{city.data[city.index].text}}</text>
				</view>
				<label class="search-bar" @click="$app.url.goto('/pages/search/search')">
					<input placeholder-class="app-placeholder" placeholder="输入目的地/电站名" />
					<image src="@/static/img/search.svg" class="_icon-search"></image>
				</label>
			</view>
		</view>
		<!-- 主滚动 -->
		<view class="main-scroll-wrap">
			<scroll-view class="root-scroll app-hide-scrollbar" @scrolltolower="scrollLock=true" @scrolltoupper="scrollLock=false" scroll-y>
				<view class="contet-root">
					<!-- 内容顶部 -->
					<view id="roller" class="base">
						<!-- 快捷栏 -->
						<view class="shortcut-bar">
							<view class="_item" @click="$app.url.goto('/pages/order/order')">
								<image src="@/static/img/shortcut1.png" class="_icon"></image>
								<view class="_name">订单中心</view>
							</view>
							<view class="_item" @click="$app.url.goto('/pages/coupon-buy/coupon-buy')">
								<image src="@/static/img/shortcut2.png" class="_icon"></image>
								<view class="_name">购充电券</view>
							</view>
							<view class="_item" @click="customerService()">
								<image src="@/static/img/shortcut3.png" class="_icon"></image>
								<view class="_name">在线客服</view>
							</view>
							<view class="_item" @click="$app.url.goto('/pages/feedback/feedback')">
								<image src="@/static/img/shortcut4.png" class="_icon"></image>
								<view class="_name">意见反馈</view>
							</view>
						</view>
						<!-- 版头广告 -->
						<swiper class="banner" v-if="banners.length>0" autoplay="true" >
							<swiper-item v-for="(item,index) in banners" :key="index">
								<view class="swiper-item">
									<image   @load="bannerLoadCompleted()" :src="showImg(item.pic)" class="swiper-item-image" mode="widthFix"></image>
								</view>
							</swiper-item>
						</swiper>
					</view>
					<view id="fixed" class="base">
						<!-- 选项条 -->
						<view class="app-flex options-bar">
							<view class="app-flex middle option-wrap">
								<view v-for="(item,index) in sorts.data" :key="index" @click="changeSort(index)" 
								class="option-item" :class="{active:sorts.index==index}">{{item.name}}</view>
							</view>
							<view class="app-flex c-center separ"></view>
							<view @click="$app.url.goto('/pages/map/map',false)" class="app-flex middle map-mode">
								<image src="@/static/img/map.svg" class="_icon"></image>
								<text>地图模式</text>
							</view>
						</view>
					</view>
					<!-- 电站列表 -->
					<view id="list-box" class="list-scroll-wrap">
						<scroll-view class="list-scroll" :scroll-y="scrollLock">
							<view class="list">
								<view v-for="(item,index) in list.data" :key="index" @click="gotoSiteDetail(item)" class="item">
									<view class="contet">
										<view class="name">
											<view class="icon"><image src="@/static/img/plug.svg" mode="widthFix"></image></view>
											<view class="txt">{{item.name}}</view>
										</view>
										<view class="parkade">
											<view class="icon"><image src="@/static/img/parkade.svg" mode="widthFix"></image></view>
											<!-- <view class="txt"><rich-text :nodes="item.parkTips"></rich-text></view> -->
											<view class="txt">充电减免2小时停车费，超出时长部分计时收费</view>
										</view>
										<view class="app-flex c-between info">
											<view class="app-flex middle">
												<view class="charge"><text class="icon">快</text><text class="value">{{item.params.emptyFast}}</text><text class="max">{{item.params.totalFast}}</text></view>
												<view class="charge"><text class="icon blue">慢</text><text class="value">{{item.params.emptySlow}}</text><text class="max">{{item.params.totalSlow}}</text></view>
											</view>
											<view class="discount" v-if="discountInfo">
												<view>
													{{discountInfo.temp2}}
												</view>
											</view>
											<view class="distance">
												<view class="icon"><image src="@/static/img/distance.svg" mode="widthFix"></image></view>
												<text>{{item.params.rangeShow}}</text>
											</view>
										</view>
									</view>
									<view class="price">
										<!-- v-if="user_info.firmId===null" -->
										<view class="app-flex middle" style="color: #FF5D50;" v-if="user_info===null||user_info.firmId===null">
											<text class="value">{{item.params.nowPrice?item.params.nowPrice.toFixed(4):"0.0000"}}</text>
											<text class="unit">元/度</text>
										</view>
										<view class="app-flex middle" v-else>
											<view class="card-bottom-text">
												<text>{{item.params.firmPrice.toFixed(4)}}</text>
												<text class="mini-text">元/度</text>
											</view>
											<view class="operation-price-btn">
												企业专享价
											</view>
											<view class="ordinary-price">{{item.params.nowPrice?item.params.nowPrice.toFixed(4):"0.0000"}}</view>
										</view>
										<view>{{item.params.priceShow}}</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<!-- <view style="height: 158px;"></view> -->
				</view>
			</scroll-view>
		</view>
		<app-navigation id="app-navigation" active="home"></app-navigation>
	</ax-body>
</template>

<script>
	var bmap = require('static/js/bmap-wx.js'); 
	export default {
		async onLoad(options) {
			const permit = await this.queryPermit();
			if(permit.privacy){
				// 没有通过隐私协议
				this.privacy.visible = true;
			}else{
				// 已通过隐私协议
				if(permit.location===true){
					// 可以调用定位能力
					this.updateLocation();
				}else if(permit.location===false){
					// 通过了隐私协议,但是定位被拒绝
					this.location.visible = true;
					this.updateLocation();
				}else if(permit.location===undefined){
					// 没有申请过定位能力
					this.updateLocation();
				}
			}
			
			if (options.hasOwnProperty('q') && options.q) {
			    // 通过下面这步解码，可以拿到url的值
				const url = decodeURIComponent(options.q)
				// 对url中携带的参数提取处理
				console.log("url:"+url)
				var device_no = this.getQueryParams(url,"connectorCode")
				console.log("device_no:"+device_no)
				if(device_no){
					this.getDeviceInfo(device_no)
				}
				
			}
			// this.user_info=this.$app.storage.get('USER_INFO')
		},
		mounted() {
			this.setListHeight();
			this.setAppNavigationHeight();
			this.get_frimid()
			this.get_userinfo()
		},
		data() {
			return {
				user_info:{},
				// 导航栏高度
				appNavigationHeight: 0,
				// 页面滚动锁
				scrollLock: true,
				
				sorts:{
					index: 0,
					data: [{name:'离我最近',code:"range"},{name:'空闲最多',code:"device"},{name:'电费最低',code:"price"}]
				},
				list:{
					height: 0,
					data: []
				},
				banners:[],
				location:{
					visible: false,
					value: '',
				},
				privacy:{
					visible: false,
				},
				city:{
					index: 0,
					data:[
						{text:'贵阳',areaCode:"5201"},
						{text:'六盘水',areaCode:"5202"},
						{text:'遵义',areaCode:"5203"},
						{text:'安顺',areaCode:"5204"},
						{text:'毕节',areaCode:"5205"},
						{text:'铜仁',areaCode:"5206"},
						{text:'黔东南',areaCode:"5226"},
						{text:'黔南',areaCode:"5227"},
						{text:'黔西南',areaCode:"5223"},
					]
				},
				discountInfo:null
			}
		},
		onShow() {
			this.getBanners()
		},
		computed:{
			StyleSheet(){
				return {
					'--app-navigation-heiht': `${this.appNavigationHeight}px`,
					'--list-heiht': `${this.list.height}px`
				}
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') {
				// 来自页面内分享按钮
				console.log(res.target);
			}
			return {
				title: "用券充天天都享会员价", // 标题
				path: "/pages/index/index", // 分享路径
				imageUrl: '../../static/img/share.jpg', // 分享图
				desc: '用券充天天都享会员价'
			};
		},
		onShareTimeline() {
			return {
				title: "用券充天天都享会员价", // 标题
				path: "/pages/index/index", // 分享路径
				imageUrl: '../../static/img/share.jpg'// 分享图
			};
		},
		methods: {
			get_userinfo(){
				this.$api.base("post", "/userApi/getUserAccount", {}, {error:false}).then(res => {
					this.user_info = res.accountInfo
					this.$app.storage.set('USER_INFO', res.accountInfo);
				})
			},
			// 企业用户扫码进入
			get_frimid(){
				if(this.$app.storage.get('FRIM_ID')){
					if(this.$app.storage.get('USER_TOKEN')){
						this.$api.base("post","/userApi/add-firm-user?firmId="+parseInt(this.$app.storage.get('FRIM_ID')),{},{error: false}).then(res=>{
							this.$app.popup.alert(res.msg);
							this.get_userinfo()
							setTimeout(()=>{
								this.$app.storage.remove('FRIM_ID')
							},500)
						}).catch(err=>{
							this.$app.popup.alert(err.msg)
							setTimeout(()=>{
								this.$app.storage.remove('FRIM_ID')
							},500)
						})
					}else{
						uni.showModal({
							title:'未登录',
							content:'你还未进行登录，请去登录',
							showCancel:false,
							success:function(res) {
								if(res.confirm){
									uni.navigateTo({
										url:'/pages/login/login'
									})
								}
							}
						})
					}

				}
			},
			getDeviceInfo(sn){
				this.$api.base("post","/chargeApi/checkDevicesBySn",{"sn":sn},{}).then(res=>{
					var item = res.device;
					//设备状态 0：离网1：空闲2：占用（未充电）3：占用（充电中）4：占用（预约锁定）255：故障
					if(item.deviceStatus == 0 || item.deviceStatus == 255 ){
						return;
					}
					this.$app.url.goto('/pages/terminal/terminal?deviceId='+item.id+"&deviceStatus="+item.deviceStatus);
				})
			},
			getQueryParams(url,key) {  
			    const queryString = url.split('?')[1] || '';  
			    const params = {};  
			    const pairs = queryString.split('&');  
			  
			    pairs.forEach(pair => {  
			        const [key, value] = pair.split('=');  
			        params[decodeURIComponent(key)] = decodeURIComponent(value || '');  
			    });  
			  
			    return params[key];  
			}, 
			showImg(img){
				return this.$config.url.request+img
			},
			// 打开客服
			customerService(){
				const cs = this.$config.customerService;
				this.$app.act.customerService(cs.id,cs.url).catch(err=>{
					console.log(err);
					this.$app.popup.alert('客服中心失联啦,请联系管理员!');
				});
			},
			// 查询许可
			queryPermit(){
				return new Promise((resolve,reject)=>{
					const data = {};
					const check = ()=>{
						if( Object.keys(data).length == 2 ) resolve(data);
					}
					if(uni.getPrivacySetting){
						uni.getPrivacySetting({
							success: res => {
								data.privacy = res.needAuthorization;
							},
							complete: () => {
								if(typeof data.privacy !='boolean' && typeof data.privacy !='undefined') data.privacy = null;
								check();
							},
						});
					}else{
						data.privacy = false;
					}
					uni.getSetting({
						success: res => {
							data.location = uni.getLocation ?　res.authSetting['scope.userLocation']　:　undefined;
						},
						complete: () => {
							if(typeof data.location !='boolean' && typeof data.location !='undefined') data.location = null;
							check();
						},
					})
				});
			},
			// 更新位置
			updateLocation(){
				this.getLocation().then(res=>{
					this.location.value = [res.longitude,res.latitude].join(',');
					this.getStations(res.longitude,res.latitude)
					this.$app.storage.set('USER_LOCATION',this.location.value);
					return this.reverseGeocoder([res.latitude,res.longitude].join(','))
				});
			},
			// 获取定位
			getLocation(){
				return new Promise((resolve,reject)=>{
					// this.loading.visible = true;
					if(uni.getLocation){
						uni.getLocation({
							success: res => resolve(res),
							fail: err => {
								console.log(err)
								console.log('定位失败');
								// this.location.visible = true;
								this.getStations("","")
							},
							complete: () => {
								
							}
						})
					}else{
						console.log('微信版本太低,无定位接口可用');
						resolve({longitude:'',latitude:''});
					}
				});
			},
			reverseGeocoder(latlon){
				console.log(latlon)
				let lat = latlon.split(",")[0]
				let lng = latlon.split(",")[1]
				let baiduLoc = this.convertGcj02ToBd09(lng,lat)
				latlon = baiduLoc.lat+","+baiduLoc.lng
				console.log(latlon)
				return new Promise((resolve,reject)=>{
					var BMap = new bmap.BMapWX({ 
					            ak: 'vtQgaPzonb3H4qeUOWGr53ePcNCsmdMj' 
					        }); 
					BMap.regeocoding({
						location:latlon,
						success:res=>{
							
							let code = res.originalData.result.addressComponent.adcode.substr(0,4)
							for (var i = 0; i < this.city.data.length; i++) {
								if(this.city.data[i].areaCode==code){
									this.city.index = i
									break;
								}
							}
							console.log(res)
						},
						fail:err=>{
							console.log(err)
						}
					})
				});
			},
			getBanners(){
				this.$api.base("post","/userApi/getBanners",{},{}).then(res=>{
					this.banners = res.banners
				})
			},
			convertBdToTx(lng, lat) {  
			    // 百度坐标系（BD09）转火星坐标系（GCJ-02，即腾讯地图使用的坐标系）  
			    // 这里的转换公式是基于经验公式，可能存在一定的误差  
			    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;  
			    let x = lng - 0.0065;  
			    let y = lat - 0.006;  
			    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);  
			    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);  
			    let lngs = z * Math.cos(theta);  
			    let lats = z * Math.sin(theta);  
			    return { lng: lngs, lat: lats };  
			},
			getStations(lng,lat){
				this.$api.base("post","/chargeApi/getStations",{order:this.sorts.index,lat,lng},{}).then(res=>{
					res.stationList.forEach(i=>{
						var txPoint = this.convertBdToTx(i.lng,i.lat)
						i.lng = txPoint.lng
						i.lat = txPoint.lat
					})
					this.list.data = res.stationList
					if(res.discountInfo){
						this.discountInfo = res.discountInfo
					}
				})
			},
			// 设定导航栏高度
			setAppNavigationHeight(){
				this.$nextTick(()=>{
					uni.createSelectorQuery().in(this).select("#app-navigation").boundingClientRect(data=>{
						this.appNavigationHeight = data.height;
					}).exec();
				});
			},
			// 设置列表高度
			setListHeight(){
				this.$app.act.selectorQuery(this,"#list-box,#roller",true).then(res=>{
					const win = uni.getWindowInfo();
					const roller = res.find(i=>i.id=='roller');
					const list = res.find(i=>i.id=='list-box');
					this.list.height = win.windowHeight - list.top - this.appNavigationHeight + roller.height;
				});
			},
			// 版头加载完成
			bannerLoadCompleted(){
				this.setListHeight();
			},
			changeSort(index){
				this.sorts.index = index;
				switch(index){
					case 0:
						this.list.data.sort((a,b)=>a.params.range-b.params.range)
					break;
					case 1:
						this.list.data.sort((a,b)=>b.params.totalEmpty-a.params.totalEmpty)
					break;
					case 2:
						this.list.data.sort((a,b)=>a.params.nowPrice-b.params.nowPrice)
					break;
				}
			},
			scrolltolower(){
				console.log('到底')
			},
			gotoSiteDetail(item){
				this.$app.url.goto('/pages/site/site?item='+JSON.stringify(item));
			},
			// 确认隐私协议
			agreePrivacyAuthorization(){
				this.privacy.visible = false;
				this.updateLocation();
			},
			// 打开隐私协议
			openPrivacyContract(){
				uni.openPrivacyContract();
			},
			// 拒绝隐私协议
			refusePrivacy(){
				this.privacy.visible = false;
			},
			convertGcj02ToBd09(lng, lat) {
			    const x_pi = 3.14159265358979324 * 3000.0 / 180.0;
			    const z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
			    const theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
			    const bd_lng = z * Math.cos(theta) + 0.0065;
			    const bd_lat = z * Math.sin(theta) + 0.006;
			    return {
			        lng: bd_lng,
			        lat: bd_lat
			    };
			}
		}
	}
</script>

<style>
@import url('index.css');
.discount{
	flex: 1;
	text-align: right;
	padding-right: 5px;
}
.discount view{
	display: inline-flex;
	align-items: center;
	height: 22px;
	border: 1px solid #ccc;
	border-radius: 5px;
	font-size: 12px;
	color: #F59C79;
	padding: 0 7px;
	overflow: hidden;
}
</style>
