<template>
	<view class="content">
		<view class="cu-bar topNav">
			<view class="circle" @click="handle_push_personnel" :style="{ 'background-image': `url( ${avatar} )`  }"
				v-if="globalData.isLogin">
			</view>
			<view class="circle" :style="{ 'background-image': `url( ${no_avatar} )`  }"
				v-else>
			</view>
			<view class="search-form round">
				<text class="cuIcon-search" style="font-size: 14px;"></text>
				<input class="searchPoint" type="text" v-model="search_stationName" placeholder="搜索地点,找充电站"
					@confirm="getStationName" confirm-type="search" />
			</view>

		</view>
		<view class="notice_position" v-if="ischarging_order">
			<uv-notice-bar :text="notice_text" mode="link" @click="handle_chargorder"></uv-notice-bar>
			<!-- <uv-notice-bar text="notice_text" mode="link" @click="handle_chargorder"></uv-notice-bar> -->
		</view>
		<view class="position_right_order">
			<view class="" @click="searchPeo" v-if="check_version == '车队版' ">
				<uv-icon name="coupon" size="20" color="#000"></uv-icon>
				换电
			</view>
			<view class="" @click="goRecharge">
				<uv-icon name="pushpin-fill" size="20" color="#000"></uv-icon>
				充电
			</view>
			<view class="" @click="subscribe" v-if="check_version == '车队版' ">
				<uv-icon name="empty-data" size="20" color="#000"></uv-icon>
				预约
			</view>
		</view>


		<view class="section">
			<view class="map_content">
				<view class="marker_map">
					<search-destination ref="searchdestination" style="width: 100%; height: 100%;"></search-destination>
				</view>
			</view>
		</view>
		<view class="scan_views">
			<!-- <view class="left_cicle .public_flex">
				<uv-icon name="map" size="25"></uv-icon>
			</view> -->
			<view class="scan_btns" @click="handle_scan" v-if="globalData.isLogin">
				扫码充电/换电
			</view>
			<view class="scan_btns" @click="handle_go_login" v-else>
				请登录
			</view>

			<!-- <view class="right_cicle .public_flex">
				<uv-icon name="reload" size="25"></uv-icon>
			</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>
</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,
		onUnload,
		onHide
	} from "@dcloudio/uni-app";


	const search_stationName = ref('')
	const noneShow = ref(false)

	let longiNum = ref()
	let latiNum = ref()
	const cityRes = ref()
	const realNameAuthFlag = ref()
	const errornotify = ref(null)

	const notice_text = ref('当前有正在充电的订单,请点击前往查看')
	const ischarging_order = ref(false)
	onLoad(async () => {})
	onUnload(() => {

	})
	onHide(() => {
		// if (timer.value) {
		console.log('清空了')
		clearInterval(timer.value)
		timer.value = null
		// }
	})
	onShow(() => {
		check_version.value = uni.getStorageSync("version") || "个人版"
		if (uni.getStorageSync("version") == "") {
			uni.setStorageSync("version", "个人版")
		}
		// realNameAuthFlag.value = uni.getStorageSync("realNameAuthFlag")
		// console.log(globalData.isLogin, 'globalData.isLogin')
		if (globalData.isLogin) {
			handle_user_info()
		}
	})
	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) => {
				// console.log(res, '');
				if (res.data.code == 0 && res.data.data != null) {
					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
					}
				}

			})
		}, 10000)
	}

	const handle_go_login = () => {
		uni.navigateTo({
			url: '/pagesCenter/login/enter'
		})
	}

	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" 
			}
		})
	}
	const avatar = ref(null)
	const no_avatar = ref(
		'https://zzpower.net//admin-api/infra/file/4/get/6e642a15c0bad98793f342a5ca83317cfcd62ed8b84fa5fd4c5d6f4176bd3a14.png'
	)
	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)
				realNameAuthFlag.value = res.data.data.realNameAuthFlag
				avatar.value = res.data.data.avatar
				if (realNameAuthFlag.value == 1) {
					clearInterval(timer.value)
					timer.value = null
					handle_loop()
				}
			}
		})
	}

	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
				if (str.orderStatus == 1) {
					uni.navigateTo({
						url: '/pages/order/chargorder/detailInf/detailInf?details=' + JSON
							.stringify(
								str)
					})
				} else if (str.orderStatus == 4) {
					uni.navigateTo({
						url: '/pages/order/chargorder/detailInf/detail?details=' + JSON
							.stringify(
								str)
					})
				}
				uni.hideLoading()
			} else {
				uni.hideLoading()
				uni.showToast({
					title: res.data.msg,
					duration: 2000,
					icon: 'error'
				});
			}
		}).catch((err) => {

		})
	}

	const check_version = ref()

	const handle_push_personnel = () => {
		uni.navigateTo({
			url: '/pages/userCenter/userCenter'
		});
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>