<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">
				<label class="search-bar" @click="$app.url.goto('/subPackages/other/search/search')">
					<view class="locate-city">
						<image src="@/static/img/locate.svg" class="_icon"></image>
						<text class="__name">{{ city.data[city.index].text }}</text>
					</view>
					<input placeholder-class="app-placeholder" placeholder="| 输入目的地/电站名" />
					<image src="@/static/img/search.svg" class="_icon-search"></image>
				</label>
				<view style="width: 20rpx;"></view>
				<view class="search-map-mode" @click="$app.url.goto('/pages/map/map', false)">
					<image class="search-map-icon" src="@/static/img/map-icon.svg" mode=""></image>
					<text>地图模式</text>
				</view>
			</view>
		</view>
		<view class="arrears-tips" v-if="payment_msg != null">
			<view class="arrears-left">
				<image class="arrears-icon" src="@/static/img/arrears-icon.svg" mode=""></image>
				<view class="arrears-text">
					您有一笔超充订单{{ (payment_msg.maspAmount + payment_msg.maspRealAmount).toFixed(2) }}元待补缴</view>
			</view>
			<view class="arrears-btn" @click="topage_coupon">去补缴</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="buy-charge-coupon" @click="$app.url.goto('/subPackages/coupon/coupon-buy/coupon-buy')">
								<view class="coupon-tag">限时</view>
								<view class="charge-title">
									<image class="title-coupon-text" src="@/static/img/goumaicdq.png" mode=""></image>
									<view class="title-right-text">
										<text class="ax ax-iconline i-arrow-right icon"></text>
									</view>
								</view>
								<view class="charge-text-dsc">特惠价限时购买</view>
								<image class="charge-coupon-img"
									src="https://national-motion.oss-cn-beijing.aliyuncs.com/20251230/ab13df2fa29e47f4ab7073310589b005.png"
									mode=""></image>
							</view>
							<view class="">
								<view class="order-center" @click="$app.url.goto('/subPackages/order/order/order')">
									<view class="order-center-left">
										<view class="charge-title" style="margin-top:0;">
											<image class="title-coupon-text" src="@/static/img/order-center.png"
												mode="">
											</image>
											<view class="title-right-text">
												<text class="ax ax-iconline i-arrow-right icon"></text>
											</view>
										</view>
										<view class="order-center-number">
											查看充电订单
										</view>
									</view>
									<image class="order-center-icon" src="/static/img/order-zx.png" mode=""></image>
								</view>
								<view class="order-center" style="margin-top: 20rpx;"
									@click="$app.url.goto('/subPackages/other/feedback/feedback')">
									<view class="order-center-left">
										<view class="charge-title" style="margin-top:0;">
											<image class="title-coupon-text" src="@/static/img/yijian-fankui.png"
												mode="">
											</image>
											<view class="title-right-text">
												<text class="ax ax-iconline i-arrow-right icon"></text>
											</view>
										</view>
										<view class="order-center-number">
											随时为您服务
										</view>
									</view>
									<image class="order-center-icon" src="/static/img/yijianfankui.png" mode=""></image>
								</view>
							</view>
						</view>
						<!-- 版头广告 -->
						<swiper class="banner" v-if="banners.length > 0" autoplay="true">
							<swiper-item v-for="(item, index) in banners" :key="index"
								@click="$app.url.goto(item.jumpPage)">
								<view class="swiper-item">
									<image @load="bannerLoadCompleted()" :src="item.picture" 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="options-tabs" v-for="(item, index) in sorts.data" :key="index"
								@click="changeSort(index)" :class="{ active: sorts.index == index }">
								<text>{{ item.name }}</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="txt">{{ item.stationName }}</view>
											<view class="firm-price" v-if="item.firmUser">
												企业专享价
											</view>
										</view>
										<view class="parkade">
											<view class="txt">{{ item.tips || '' }}</view>
										</view>
										<view class="app-flex c-between info">
											<view class="app-flex middle">
												<view class="charge"><text class="icon">快</text>{{ item.fastCharging }}
												</view>
												<view class="charge"><text class="icon blue">慢 </text>{{
													item.slowCharging }}
												</view>
											</view>
											<view class="distance">
												<view class="icon">
													<image src="@/static/img/distance.svg" mode="widthFix"></image>
												</view>
												<text>{{ item.distance }}km</text>
											</view>
										</view>
									</view>
									<view class="price">
										<view class="app-flex middle" style="color: #FF5D50;">
											<text class="value">{{ item.platformPrice }}</text>
											<text class="unit" style="color: #2B303A;font-weight: normal;">元/度</text>
										</view>
										<view class="app-flex middle" v-if="item.firmUser">
											<view class="card-bottom-text">
												<text class="card-bottom-text-minitext">{{ item.enterprisePrice
												}}</text> <text style="color: #2B303A;font-size: 18rpx;">元/度</text>
											</view>
										</view>
										<view>{{ item.peakValue }}{{ item.peakTime || '--' }}</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<!-- <view style="height: 158px;"></view> -->
				</view>
			</scroll-view>
			<view class="concat-father" @click="customerService()">
				<image class="concat-icon"
					src="https://national-motion.oss-cn-beijing.aliyuncs.com/20251230/818d10965318468496abbbdef97e908d.png"
					mode=""></image>
			</view>
		</view>
		<ax-popup ref="filter" position="" maskType="black" maskEnable maskClose>
			<view class="ad-popup">
				<view class="close-get" @click="closeAd">X</view>
				<swiper class="ad-swiper" :autoplay="true" :interval="8000" :duration="1000" circular indicator-dots>
					<swiper-item class="ad-swiper-item" v-for="(item, index) in adBanner" :key="index">
						<image class="ad-image" :src="item.picture" @click="goImgLink(item)" mode="widthFix">
						</image>
					</swiper-item>
				</swiper>
			</view>
		</ax-popup>
		<view style="position: fixed;width: 100%;bottom:100rpx;">
			<app-navigation id="app-navigation" active="home"></app-navigation>
		</view>
	</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)
			}

		}
		if (this.closeAdvertising) {
			this.getAdswiper()
		}
		// this.user_info=this.$app.storage.get('USER_INFO')
	},
	mounted() {
		if (this.adBanner.length > 0 && !this.$app.storage.get('AD_STATUS')) {
			this.$refs.filter.open();
		}
		// #ifdef MP-WEIXIN
		this.setListHeight();
		// #endif
		this.setAppNavigationHeight();
		this.get_frimid()
		// this.get_paymentMsg()
		this.getBanners()
	},
	data() {
		return {
			payment_msg: null,
			user_info: {},
			// 导航栏高度
			appNavigationHeight: 0,
			// 页面滚动锁
			scrollLock: true,

			sorts: {
				index: 0,
				data: [{
					name: '离我最近',
					code: "range"
				}, {
					name: '空闲最多',
					code: "device"
				}, {
					name: '电费最低',
					code: "price"
				}]
			},
			list: {
				height: 0,
				data: []
			},
			banners: [],
			adBanner: [],
			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,
			closeAdvertising: false,
			pageNum: 1
		}
	},
	onShow() {
		this.getAdswiper()
	},
	onHide() {
		this.$app.storage.remove('AD_STATUS')
	},
	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: 'https://national-motion.oss-cn-beijing.aliyuncs.com/20251230/7eda17a802dd49e39f8c6bb3d0f1aa4e.jpg', // 分享图
			desc: '用券充天天都享会员价'
		};
	},
	onShareTimeline() {
		return {
			title: "用券充天天都享会员价", // 标题
			path: "/pages/index/index", // 分享路径
			imageUrl: 'https://national-motion.oss-cn-beijing.aliyuncs.com/20251230/7eda17a802dd49e39f8c6bb3d0f1aa4e.jpg' // 分享图
		};
	},
	methods: {
		closeAd() {
			this.closeAdvertising = true
			this.$refs.filter.close()
			this.$app.storage.set('AD_STATUS', this.closeAdvertising);
		},
		// 企业用户扫码进入
		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.get_userinfo()
						setTimeout(() => {
							this.$app.storage.remove('FRIM_ID')
						}, 500)
						this.$app.popup.alert(res.msg);
					}).catch(err => {
						setTimeout(() => {
							this.$app.storage.remove('FRIM_ID')
						}, 500)
						// this.$app.popup.alert(err.msg)
					})
				} else {
					uni.showModal({
						title: '未登录',
						content: '你还未进行登录，请去登录',
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
						}
					})
				}

			}
		},
		getDeviceInfo(sn) {
			this.$api.base("get", "/applet/v1/station/connector/detail", {
				"connectorCode": sn
			}, {}).then(res => {
				//设备状态 0：离网1：空闲2：占用（未充电）3：占用（充电中）4：占用（预约锁定）255：故障
				if (res.data.status == 0 || res.data.status == 255) {
					return;
				}
				this.$app.url.goto('/subPackages/charging/terminal/terminal?deviceId=' + res.data.connectorCode + "&deviceStatus=" + res.data
					.status);
			})
		},
		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
		},
		goImgLink(e) {
			this.$app.url.goto(e.skipUrl);
		},
		// 打开客服
		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);
				}
				// #ifndef H5
				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;
				}
				// #endif
				// #ifdef H5
				data.privacy = false;
				// #endif
				// #ifdef MP-WEIXIN
				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();
					},
				})
				// #endif
				// #ifdef H5
				data.location = true;
				check();
				// #endif
			});
		},
		// 更新位置
		updateLocation() {
			this.getLocation().then(res => {
				this.location.value = [res.longitude, res.latitude].join(',');
				this.get_userinfo()

				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) => {
				// #ifdef H5
				// H5环境下使用浏览器定位API
				if (navigator.geolocation) {
					navigator.geolocation.getCurrentPosition(
						(position) => {
							resolve({
								longitude: position.coords.longitude,
								latitude: position.coords.latitude
							});
						},
						(error) => {
							console.log('H5定位失败', error);
							this.getStations("", "");
							this.get_userinfo()
						}
					);
				} else {
					console.log('浏览器不支持定位');
					resolve({ longitude: '', latitude: '' });
				}
				// #endif

				// #ifndef H5
				if (uni.getLocation) {
					uni.getLocation({
						success: res => resolve(res),
						fail: err => {
							console.log(err)
							console.log('定位失败');
							this.getStations("", "")
							this.get_userinfo()
						}
					})
				} else {
					console.log('微信版本太低,无定位接口可用');
					resolve({ longitude: '', latitude: '' });
				}
				// #endif
			});
		},
		reverseGeocoder(latlon) {
			// #ifdef H5
			// H5环境跳过百度地图处理
			console.log('H5环境跳过百度地图处理');
			return Promise.resolve();
			// #endif

			// #ifndef H5
			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)
					}
				})
			});
			// #endif
		},
		// get_paymentMsg() {
		// 	// maspStatus（1:待补缴，2：已补缴）realPredictServiceCost平台；maspAmount第三方
		// 	this.$api.base("post", "/chargeApi/queryOrderList-arrearage", {}, {}).then(res => {
		// 		this.payment_msg = res.data
		// 	})
		// },
		getBanners() {
			this.$api.base("get", "/applet/v1/homePage/getBannerList/1", {}, {}).then(res => {
				this.banners = res.data
			})
		},
		getAdswiper() {
			this.$api.base("get", "/applet/v1/homePage/getAdvertisingList", {}, {}).then(res => {
				this.adBanner = res.data
				// this.$refs.filter.open()
			})
		},
		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", "/applet/v1/homePage/getStationInfoPage", {
				pageNum: this.pageNum, pageSize: 10, sortType: this.sorts.index + 1, longitude: lng, latitude: lat, userId: parseInt(this.$app.storage.get('USER_INFO').appletUserId)
			}, {}).then(res => {
				if (this.pageNum == 1) {
					this.list.data = res.data.list
				} else {
					this.list.data = this.list.data.concat(res.data.list)
				}
			})
		},
		get_userinfo() {
			this.$api.base("get", "/applet/v1/user/getUserInfo", {}, {
				error: false
			}).then(res => {
				this.user_info = res.data
				this.$app.storage.set('USER_INFO', res.data);
			})
		},
		// 设定导航栏高度
		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;
			this.pageNum = 1
			this.getStations(this.location.value.split(',')[0], this.location.value.split(',')[1])
		},
		scrolltolower() {
			console.log('到底')
			this.pageNum++
			this.getStations(this.location.value.split(',')[0], this.location.value.split(',')[1])
		},
		gotoSiteDetail(item) {
			this.$app.url.goto('/subPackages/charging/new-site/new-site?item=' + JSON.stringify(item));
		},
		topage_coupon() {
			let payment = this.payment_msg.realPredictServiceCost + this.payment_msg.maspAmount
			this.$app.url.goto('/subPackages/coupon/coupon-buy/coupon-buy?payment=' + payment)
		},
		// 确认隐私协议
		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>