<template>
	<view class="content">
		<up-loading-page loading-text="版本切换中...请稍后" color="#666" :loading="version_loading"></up-loading-page>
		<!-- 头部 :style="{'padding-top':padTop+'px'}" -->

		<view class="tab_headers" :style="{'margin-top':padTop+'px'}">
			马尔塞云平台( {{ check_version }} )
		</view>
		<view class="cu-bar search topNav">
			<view style="font-size: 14px;" class="change_version" @click="subscribeChange">
				切换版本
				<uv-icon name="arrow-down" style="color: #fff"></uv-icon>
			</view>
			<view class="search-form round" style="flex: 1">
				<text class="cuIcon-search"></text>
				<input class="searchPoint" type="text" v-model="search_stationName" placeholder="搜索场站"
					@confirm="getStationName" confirm-type="search" />
			</view>
		</view>
		<!-- 轮播图部分 -->
		<view class="swiperCard" v-if="swiperData.swiperList.length!=0">
			<view class="notice_position" v-if="ischarging_order">
				<uv-notice-bar :text="notice_text" mode="link" @click="handle_chargorder"></uv-notice-bar>
			</view>
			<view class="navStyle">
				<u-swiper class="swiper" :radius="8" :height="150" :list="swiperData.swiperList"
					:display-multiple-items="0" autoplay :circular="true" indicator indicatorMode="line"
					imgMode="scaleToFill" bgColor="rgba(255,255,255,0)"></u-swiper>
			</view>
		</view>

		<view class="section">
			<!--  -->
			<view class="card-nav">
				<view class="bg-white navStyle shadow-warp">
					<view class="flex">
						<view class="flex-sub panel bg-white radius text-center align-center column" @click="searchPeo"
							v-if="check_version == '车队版'">
							<view class='searchImg'> </view>
							<text>换电单</text>
						</view>
						<view class="flex-sub panel bg-white radius text-center align-center column"
							@click="goRecharge">
							<view class='chargeImg'> </view>
							<text>充电单</text>
						</view>
						<view class="flex-sub panel bg-white radius text-center align-center column" @click="subscribe"
							v-if="check_version == '车队版' ">
							<view class='subscribeImg'>
								<view class="cu-tag badge" v-if="recordNum!=0">{{recordNum}}</view>
							</view>
							<text>预约单</text>
						</view>
					</view>
				</view>

			</view>
			<view class="map_content">
				<view class="marker_map">
					<search-destination ref="searchdestination" style="width: 100%; height: 100%;"></search-destination>
				</view>
				<!-- <view class="posi_imgs">
					<image src="../../static/home/scan.png" style="width: 100rpx; height: 100rpx;" mode=""
						@click="handle_scan"></image>
				</view> -->
			</view>
		</view>
		<uv-notify ref="errornotify" :safeAreaInsetTop="true" message="当前无操作权限,请审核通过后再试" type="error"></uv-notify>
		<uv-modal ref="startchargmodal" title="提示" content='当前枪已验证完成,可以进行充电,请点击开始充电'>
			<template v-slot:confirmButton>
				<view class="" style="margin:0 20px 20px 20px;">
					<button type="primary" @click="startconfirm" style="font-size: 24rpx;">开始充电</button>
				</view>
			</template>
		</uv-modal>
		<uv-modal ref="startswapmodal" title="提示" content='当前站已验证完成,可以进行换电,请点击确认开始换电'
			@confirm="handle_swaping_pay"></uv-modal>


	</view>
	<view class="mainBg"></view>
	<cc-myTabbar :tabBarShow="0" @handle_scan="handle_scan"></cc-myTabbar>
	<uv-picker ref="changepicker" :columns="columns" @confirm="confirm_picker"></uv-picker>
</template>

<script setup>
	import config from '@/common/config/config.js';
	import piniaPro from '@/stores/piniaPro.js';
	import {
		globalStore
	} from "@/stores/globalData.js";
	const globalData = globalStore(piniaPro);
	import {
		reactive,
		ref,
		getCurrentInstance
	} from "vue";
	import {
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";


	const search_stationName = ref('')
	const swiperData = reactive({
		swiperList: [
			'https://www.zzpower.net/admin-api/infra/file/4/get/2ce503a12031cad8b576bb804b1bcb8066bb7b2a54a660ccde8396c8032b8939.jpeg',
			'https://www.zzpower.net/admin-api/infra/file/4/get/65739ab905c8b085036e0b7da5570646bbffaea6c9fab666ed2ff85b6792da05.jpeg'
		],
	})
	const padTop = ref() //有无刘海屏头部的padding值
	const homeData = reactive({
		stationList: [{
			distance: 0,
			cover: 0,
			operationStatus: 0,
			stationName: 0,
			stationLocation: 0,
			batteryVo: {
				swapBatTotal: 0,
				batTotal: 0
			},
			longitude: 0,
			latitude: 0
		}],
		stationBeing: [],

	})
	const noneShow = ref(false)
	// swiperData.swiperList = [
	// 	'https://www.zzpower.net/admin-api/infra/file/4/get/2ce503a12031cad8b576bb804b1bcb8066bb7b2a54a660ccde8396c8032b8939.jpeg',
	// 	'https://www.zzpower.net/admin-api/infra/file/4/get/65739ab905c8b085036e0b7da5570646bbffaea6c9fab666ed2ff85b6792da05.jpeg',
	// ]

	// 加载更多的数据
	const status = ref('loadmore')
	const loadingText = ref('努力加载中')
	const loadmoreText = ref('上拉加载更多')
	const nomoreText = ref('实在没有了')

	const page = ref(1) //触底加载增加的页数
	let totalPages = ref()
	let longiNum = ref()
	let latiNum = ref()
	var qqmapsdk
	const cityRes = ref()
	const radios = reactive([{
			checked: true
		},
		{
			checked: false
		},
		{
			checked: false
		}
	]);
	let recordNum = ref(0)
	const notification = ref('')
	const goShift = ref(false)
	const realNameAuthFlag = ref()
	const errornotify = ref(null)
	const columns = reactive([
		[
			'个人版', '车队版'
		]
	])
	const notice_text = ref('当前有正在充电的订单,请点击前往查看')
	const ischarging_order = ref(false)
	onLoad(async () => {
		uni.getSystemInfo({
			success: (e) => {
				let statusBar = e.statusBarHeight
				let customBar = e.statusBarHeight
				padTop.value = statusBar
			}
		})

	})
	onShow(() => {
		check_version.value = uni.getStorageSync("version") || "个人版"
		realNameAuthFlag.value = uni.getStorageSync("realNameAuthFlag")
		if (globalData.isLogin) {
			if (realNameAuthFlag.value == 1) {
				handle_setting()
				clearInterval(timer.value)
				timer.value = null
				handle_loop()
			}
		}
	})
	const timer = ref(null)
	const handle_loop = () => {
		timer.value = setInterval(() => {
			let config_url = ''
			if (uni.getStorageSync("version") == '个人版') {
				config_url = 'app-api/cloud/personal/queryLatestOrder'
			} else {
				config_url = 'app-api/cloud/team/queryLatestOrder'
			}
			uni.$request({
				url: config.baseUrl + config_url,
			}).then((res) => {
				if (res.data.code == 0 && res.data.data != null) {
					// console.log(res, '获取实时信息');
					if (res.data.data.orderStatus == 1) {
						ischarging_order.value = true
						notice_text.value = '当前有正在充电的订单,请点击前往查看'
						chargorder.value = res.data.data.id
					} else if (res.data.data.orderStatus == 4) {
						ischarging_order.value = true
						notice_text.value = '当前有待支付的订单,请点击前往查看'
						chargorder.value = res.data.data.id
					} else {
						ischarging_order.value = false
					}
				}
			})
		}, 20000)
	}

	const handle_setting = async () => {
		let data = {
			refreshToken: uni.getStorageSync('refreshToken')
		}
		await uni.request({ //刷新token
			url: config.baseUrl + "app-api/member/auth/refresh-token",
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
				'tenant-id': 1
			},
			data: data
		}).then(res => {
			if (res.data.code == 401 || res.data.msg == "Error token") {
				//退出清除用户数据
				uni.removeStorageSync("token"); //"用户Token"
				uni.removeStorageSync("userInfo");
				uni.removeStorageSync("refreshToken");
				uni.removeStorageSync("teamId");
				globalData.isLogin = false
			} else {
				uni.setStorageSync("token", res.data.data.accessToken); //"用户Token"
				uni.setStorageSync("refreshToken", res.data.data.refreshToken); //"用户Token" 
				handle_user_info()
			}
		})
	}
	const handle_user_info = async () => {
		// console.log('调用了参数')
		await uni.$request({
			url: config.baseUrl + 'app-api/member/user/get',
		}).then((res) => {
			if (res.data.code == 0) {
				// console.log(res, '赋值了realNameAuthFlag');
				uni.setStorageSync("teamId", res.data.data.teamId);
				uni.setStorageSync("realNameAuthFlag", res.data.data.realNameAuthFlag)
			}
		})
	}

	const searchdestination = ref(null)
	const getStationName = async () => {
		let data = {
			stationName: search_stationName.value,
			pageNo: 1,
			pageSize: 10
		}
		await uni.$request({
			url: config.baseUrl + "app-api/cloud/station-info/page",
			method: 'GET',
			data: data,
		}).then(res => {
			if (res.data.code == 0) {
				if (res.data.data.list.length == 1) {
					let str = res.data.data.list[0]
					searchdestination.value.handle_open(str)
				}
				if (res.data.data.list.length == 0) {
					uni.showToast({
						title: '未查询到该站',
						duration: 2000,
						icon: 'error'
					});
				}
			} else {
				uni.showToast({
					title: res.data.msg,
					duration: 2000,
					icon: 'error'
				});
			}
		}).catch((err) => {

		})
	}
	const searchPeo = () => {
		if (!uni.getStorageSync("userInfo")) {
			uni.showToast({
				title: '请先完成登录',
				duration: 2000,
				icon: 'error'
			});
			return;
		} else if (uni.getStorageSync("realNameAuthFlag") != 1) {
			errornotify.value.show()
			return
		} else {
			uni.navigateTo({
				url: '/pages/order/swaporder/order'
			})
		}
	}

	const goRecharge = () => {
		if (!uni.getStorageSync("userInfo")) {
			uni.showToast({
				title: '请先完成登录',
				duration: 2000,
				icon: 'error'
			});
			return;
		} else if (uni.getStorageSync("realNameAuthFlag") != 1) {
			errornotify.value.show()
			return
		} else {
			uni.navigateTo({
				url: '/pages/order/chargorder/order'
			})
		}
	}
	const subscribe = () => {
		if (!uni.getStorageSync("userInfo")) {
			uni.showToast({
				title: '请先完成登录',
				duration: 2000,
				icon: 'error'
			});
			return;
		} else if (uni.getStorageSync("realNameAuthFlag") != 1) {
			errornotify.value.show()
			return
		} else {
			uni.navigateTo({
				url: '/pages/order/appointorder/order'
			})
		}
	}
	const swap_pay_stationNo = ref('')
	const handle_scan = () => {
		// startchargmodal.value.open()
		uni.scanCode({
			scanType: ['qrCode'],
			success: async function(res) {
				let res_result = JSON.parse(res.result)
				if (res_result.hasOwnProperty('stationNo')) {
					uni.showToast({
						title: '验证成功',
						duration: 1000,
						icon: 'success'
					})
					swap_pay_stationNo.value = res_result.stationNo
					setTimeout(() => {
						startswapmodal.value.open()
					}, 2000)
				} else {
					handle_charging_pay(res_result)
				}
			}
		})
	}
	const handle_charging_pay = async (res_result) => {
		check_chargeEqm.value = res_result.chargeEqm
		check_gunNo.value = res_result.gunNo
		await uni.$request({
			url: config.baseUrl +
				`app-api/cloud/outCharge/confirmGunCanCharging/${res_result.chargeEqm}/${res_result.gunNo}`,
			method: 'GET'
		}).then(response => {
			if (response.data.code == 0) {
				uni.showToast({
					title: '验证成功',
					duration: 1000,
					icon: 'success'
				})
				setTimeout(() => {
					startchargmodal.value.open()
				}, 2000)
			} else {
				uni.showModal({
					title: '错误',
					showCancel: false,
					content: response.data.msg,
					success: function(res) {}
				});
			}

		}).catch((err) => {
			uni.showToast({
				title: '错误,验证失败',
				duration: 2000,
				icon: 'error'
			});
		})
	}

	const handle_swaping_pay = async () => {
		// let stationNo = res_result.stationNo
		await uni.request({
			url: config.baseUrl +
				`app-api/cloud/swapOrder/sendSwap`,
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
				'tenant-id': 1
			},
			data: {
				stationNo: swap_pay_stationNo.value
			}

		}).then(response => {
			// console.log(response, '验证');
			if (response.data.code == 0) {
				uni.showLoading({
					title: '充电机启动中...请稍后'
				});
				setTimeout(() => {
					uni.hideLoading()
				}, 2000)
			} else {
				uni.showModal({
					title: '错误',
					showCancel: false,
					content: response.data.msg,
					success: function(res) {}
				});
			}

		}).catch((err) => {
			uni.showToast({
				title: '错误,验证失败',
				duration: 2000,
				icon: 'error'
			});
		})
	}

	const getLocation = () => {
		// 先调取用户授权请求询问用户是否授权
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				if (!uni.getStorageSync('location')) {
					// 未授权进入
					isGetLocation();
				}
			},
			fail: (err) => {
				noneShow.value = true
			}
		})
	}
	const isGetLocation = () => {
		uni.getLocation({
			type: 'gcj02',
			geocode: true,
			success: (res) => {
				// console.log(res,'res');
				uni.setStorageSync('location', res)
				longiNum.value = res.longitude
				latiNum.value = res.latitude
			},
			fail: (err) => {
				// console.log(err, 'uni.getLocation解析失败');
			},

		});
	}

	const isOpenAuth = () => {
		uni.showModal({
			content: '由于您还没有允许授权位置，无法定位，请点击确定允许授权',
			success: (res) => {
				if (res.confirm) {
					uni.openSetting({
						success: (result) => {
							if (result.authSetting['scope.userLocation']) {
								// 引导用户授权成功 调用获取位置接口
								getLocation()
								noneShow.value = false
							} else {
								noneShow.value = true
								cityRes.value = '全国';
								// console.log('失败')
							}
						}
					});
				} else {
					// console.log('失败2')

				}
			}
		});
	}

	const startchargmodal = ref(null)
	const startswapmodal = ref(null)
	const check_chargeEqm = ref('')
	const check_gunNo = ref('')
	const chargorder = ref('')
	const startconfirm = async () => {
		startchargmodal.value.close()

		let config_url = ''
		if (uni.getStorageSync("version") == '个人版') {
			config_url = `app-api/cloud/personal/startCharge/${check_chargeEqm.value}/${check_gunNo.value}`
		} else {
			config_url = `app-api/cloud/team/startCharge/${check_chargeEqm.value}/${check_gunNo.value}`
		}
		await uni.$request({
			url: config.baseUrl + config_url
		}).then(res => {
			if (res.data.code == 0) {
				uni.showLoading({
					title: '充电机启动中...请稍后'
				});
				setTimeout(() => {
					uni.hideLoading()
				}, 2000)
				chargorder.value = res.data.data
				setTimeout(() => {
					handle_chargorder()
				}, 6000)
				// uni.navigateTo({
				// 	url: '/pages/order/chargorder/order'
				// })
			} else {
				uni.showToast({
					title: res.data.msg,
					duration: 2000,
					icon: 'error'
				});
			}
			// console.log(res, 'res开始充电');
		}).catch((err) => {

		})
	}

	const handle_chargorder = async () => {
		let config_url = ''
		if (uni.getStorageSync("version") == '个人版') {
			config_url = `app-api/cloud/personal/queryRealTimeOrder/${chargorder.value}`
		} else {
			config_url = `app-api/cloud/team/queryRealTimeOrder/${chargorder.value}`
		}

		clearInterval(timer.value)
		timer.value = null
		await uni.$request({
			url: config.baseUrl + config_url
		}).then(res => {
			// console.log(res, '当前充电订单');
			if (res.data.code == 0) {
				let str = res.data.data
				uni.navigateTo({
					url: '/pages/order/chargorder/detailInf/detailInf?details=' + JSON.stringify(
						str)
				})
			} else {
				uni.showToast({
					title: res.data.msg,
					duration: 2000,
					icon: 'error'
				});
			}
		}).catch((err) => {

		})
	}
	const changepicker = ref(null)
	const subscribeChange = () => {
		changepicker.value.open()
	}
	const check_version = ref()
	const version_loading = ref(false)
	const confirm_picker = (e) => {
		let teamId = uni.getStorageSync("teamId")
		let str = uni.getStorageSync("version")
		if (teamId) {
			if (e.value[0] != str) {
				version_loading.value = true
				uni.setStorageSync('version', e.value[0])
				setTimeout(() => {
					version_loading.value = false
					check_version.value = e.value[0]
				}, 2000)
			} else {
				return
			}
		} else {
			uni.showModal({
				title: '提示',
				showCancel: false,
				content: "未绑定车队的用户,不允许切换版本,请绑定后重试...",
				success: function(res) {

				}
			});
		}


	}
</script>

<style lang="scss" scoped>
	.mainBg {
		width: 100vw;
		position: fixed;
		top: 0;
		height: 100vh;
		background: linear-gradient(180deg, #4C91FF 0%, #3698FD 11.35%, #73CBFD 21.65%, #94EBFF 37.35%, #EAF4F8 97.71%);
		z-index: -1;
	}

	.change_version {
		display: flex;
		align-items: center;
	}

	.tab_headers {
		line-height: 80rpx;
		width: 100%;
		text-align: center;
		color: #fff;
		font-size: 14px;
		font-weight: 600;
	}

	.topNav {
		position: relative;
	}

	.posi_imgs {
		position: absolute;
		// background: #fff;
		// padding: 5rpx;
		right: 30rpx;
		bottom: -10rpx;
		z-index: 999;
	}

	.cu-bar {
		padding-bottom: 16rpx;
		margin: 0 30rpx;
		color: #fff;
		justify-content: space-between;
		align-items: center;

		.search-form {
			width: 334rpx;
			background-color: #E2E2E2;
			flex: 0;
		}

		.searchPoint {
			width: 500rpx;
			height: 36rpx;
		}
	}

	.tabList {
		.stateStyle {
			padding: 8rpx 16rpx;
			color: #808A96;
			background-color: #E2E2E2;
			margin-left: 16rpx;
			font-size: 28rpx;
		}
	}




	.titleName {
		color: #333333;
		font-weight: 400;
		font-size: 36rpx;
		// letter-spacing: 1px;
	}

	.addressInf {
		width: 442rpx;
		color: #666666;
		font-size: 28rpx;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		// margin:16rpx 0 0rpx 0;
	}

	.listInf {
		width: 490rpx;
		flex-direction: column;
		justify-content: space-between;
		height: 178rpx;
	}

	.mapBtn {
		height: 178rpx;
		align-items: flex-end;
		// background-color: greenyellow;
	}

	.goMap {
		width: 24rpx;
		height: 24rpx;
		background: url('/static/home/goMap.svg') no-repeat;
		background-size: 100% 100%;
	}

	.moreLocal {
		margin-left: 10rpx;
	}

	.regionName {
		letter-spacing: 3rpx;
	}

	.stateImg {
		width: 164rpx;
		height: 164rpx;
		background-color: #eee;
		border-radius: 8rpx;

		.titleImg {
			border-radius: 8rpx;
		}
	}


	.searchImg {
		width: 72rpx;
		height: 72rpx;
		background: url('../../static/home/search.svg') no-repeat;
		background-size: 100% 100%;
	}

	.chargeImg {
		width: 72rpx;
		height: 72rpx;
		background: url('../../static/home/pay.svg') no-repeat;
		background-size: 100% 100%;
	}

	.subscribeImg {
		width: 72rpx;
		height: 72rpx;
		background: url('../../static/home/subscribe.svg') no-repeat;
		background-size: 100% 100%;
		position: relative;

		.cu-tag {
			background-color: #F2634F;
			font-size: 24rpx;
			font-weight: 400;
		}

		.cu-tag.badge {
			border: 1px solid #fff;
			right: -17rpx;
			height: 34rpx;
		}

	}

	.wrap {
		width: 100%;
	}


	.stateFlex {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		margin-left: 16rpx;
	}

	.cu-card>.cu-item {
		margin: 0 32rpx 16rpx 32rpx;
	}

	.stateImg .cu-tag.badge {
		width: 100rpx;
		height: 40rpx;
		top: 0rpx;
		left: 0rpx;
		right: 90rpx;
		padding: 8rpx 0rpx;
		background-image: linear-gradient(to right bottom, #A5C7FF, #2690FB);
		border-radius: 4px;
		font-size: 24rpx;
		text-align: center;
	}

	.bg-blue {
		background-image: linear-gradient(to right bottom, #A5C7FF, #2690FB);
	}

	.stateImg .cu-tag .bgPlane {
		padding: 0rpx 8rpx;
		background: rgba(255, 255, 255, 0);
	}

	.column {
		display: flex;
		flex-direction: column;
	}

	.card-nav {
		padding: 32rpx;

		.navStyle {
			border-radius: 16rpx;
		}
	}

	.swiperCard {
		margin: 16rpx 32rpx 0rpx 32rpx;
		position: relative;

		.notice_position {
			width: 100%;
			position: absolute;
			top: 0;
			z-index: 99;
		}
	}

	.cu-bar .search-form {
		background-color: #fff;
	}

	.cu-card .cu-item,
	.radius {
		border-radius: 16rpx;
	}

	.none-box {
		width: 100vw;
		display: flex;
		justify-content: center;

		.image-none {
			width: 320rpx;
			height: 452rpx;
		}
	}

	.battery-num {
		width: 20rpx;
		height: 32rpx;
	}

	.bat-use {
		font-size: 32rpx;
		font-weight: 400;
		letter-spacing: 1px;
		color: #333333;
		margin-left: 16rpx;
		line-height: 28rpx;
	}

	.bat-total {
		font-size: 28rpx;
		font-weight: 400;
		letter-spacing: 1px;
		color: #333333;
		line-height: 26rpx;
	}

	.card-box {
		padding: 32rpx;
		box-shadow: -2px 2px 8px 0px #7AA7D026;

	}

	.planeIcon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 12rpx;
	}

	.planeNum {
		font-size: 28rpx;
		line-height: 28rpx;
		font-weight: 400;
		color: #4C91FF;

	}

	.panel {
		padding: 32rpx;
	}

	.notification {
		margin-top: 16rpx;

		::v-deep .u-notice-bar {
			border-radius: 16rpx;
		}

		::v-deep .u-icon text {
			color: #808080 !important;
		}
	}

	.map_content {
		padding: 0 32rpx;
		box-sizing: border-box;
		position: relative;



		.marker_map {
			height: 660rpx;
			border-radius: 16rpx;
			overflow: hidden;
		}
	}
</style>