<template>
	<map id="mapRef" ref="mapRef" style="width: 100%;height: 100vh;" show-location :longitude="location.longitude"
		:latitude="location.latitude" :markers="markers" :scale="scale" :polygons="polygons" :polyline="polylines"
		:circles="circles" @markertap="openBikeInfo" />
	<div v-if="!showBikeInfo" class="divMapTools" style="left: 10px;">
		<div>
			<image class="divImg" :src='imgPath+"static/userui/home/localtion.png"' @click="refresh" />
		</div>
		<div>
			<image class="divImg" :src='imgPath+"static/userui/home/fault.png"' @click="reportFault" />
		</div>
	</div>
	<div v-if="!showBikeInfo" class="divMapTools" style="right: 10px;">
		<div>
			<image class="divImg" :src='imgPath+"static/userui/home/packing.png"' @click="getSite" />
		</div>
		<div>
			<image class="divImg" :src='imgPath+"static/userui/home/mine.png"' @click="getMine" />
		</div>
	</div>
	<div v-if="hasOrder" class="divMapOrder" @click="showOrderInfo">
		<div>
			<image style="width: 15px;height: 15px;margin-left: 15px;margin-right: 10px;"
				:src='imgPath+"static/userui/home/speaker.png"' />
			<label>有骑行订单未支付，请查看</label>
		</div>
		<div style="margin-right: 15px;">
			<label>查看 <label>></label></label>
		</div>
	</div>
	<div class="divMapBottom">
		<div :class="(hasOrder?'divScanBtnDis ':'')+'divScanBtn'" @click="scanBike">
			<uni-icons type="scan" color="white" :size="25"></uni-icons>
			<label style="margin-left: 5px;">扫码用车</label>
		</div>
	</div>
	<div v-if="showOrder" class="divOrder">
		<div class="divOrderRow">
			<div class="divOrderCell">
				<image class="divOrderImg" :src='imgPath+"static/userui/home/money.png"' />
				<label>费用：</label>
				<label>{{order.money}}元</label>
			</div>
			<div class="divOrderCell2">
				<label>{{order.bikecode}}</label>
			</div>
		</div>
		<div class="divOrderRow" style="font-size: 12px;">
			<div class="divOrderCell">
				<image class="divOrderImg" :src='imgPath+"static/userui/home/timer.png"' />
				<label>计时：</label>
				<label style="color: #61D246;">{{order.time}}</label>
			</div>
			<div class="divOrderCell2">
				<image class="divOrderImg" :src='imgPath+"static/userui/home/bike.png"' />
				<label>骑行：</label>
				<label style="color: #61D246;">{{order.mileage}}</label>
			</div>
		</div>
		<div class="divOderBtn">
			<image v-if="orderState==0" style="width: 120px;height: 40px;" :src='imgPath+"static/userui/home/lock.png"'
				@click="lockRiding" />
			<image v-if="orderState==1" style="width: 120px;height: 40px;" :src=' imgPath+"static/userui/home/run.png"'
				@click="continueRiding" />
			<image style="width: 160px;height: 40px;" :src='imgPath+"static/userui/home/end.png"' @click="endRiding" />
		</div>
	</div>
	<div v-if="showMess!=1" class="divMess">
		<uni-card>
			<uni-list border>
				<uni-list-item :thumb='imgPath+"static/userui/home/map1.png"' thumb-size="lg">
					<template v-slot:body>
						<div class="divMessTitle1">服务区域</div>
						<div class="divMessTitle2">请在服务区域内骑行</div>
					</template>
				</uni-list-item>
				<uni-list-item :thumb='imgPath+"static/userui/home/map2.png"' thumb-size="lg">
					<template v-slot:body>
						<div class="divMessTitle1">换车区域</div>
						<div class="divMessTitle2">还车时确保车辆已经到达还车区域或者距你最近的停车网点</div>
					</template>
				</uni-list-item>
				<uni-list-item :thumb='imgPath+"static/userui/home/map3.png"' thumb-size="lg">
					<template v-slot:body>
						<div class="divMessTitle1">停车网点</div>
						<div class="divMessTitle2">还车至停车网点，时长费最多可半价优惠</div>
					</template>
				</uni-list-item>
			</uni-list>
			<div class="divMessWorn">
				<div class="divMessWornTitle">
					·注意事项
				</div>
				<div class="divMessWornContent">禁止私自加锁或破坏车辆</div>
				<div class="divMessWornContent">未满12岁禁止骑行</div>
				<div class="divMessWornContent">如车辆故障，及时通过app保修</div>
			</div>
			<div class="divMessBtn">
				<label
					style="color: #61D145;border: 1px solid #0000000f;padding: 5px 15px;border-radius: 5px;box-shadow: 2px 2px #0000000a;"
					@click="clickMess">已知晓</label>
			</div>
		</uni-card>
	</div>
	<div v-if="showBikeInfo" style="position: absolute;z-index: 2000;bottom: 0;width: 100vw;">
		<bike-info bikecode="123456" @close="closeBikeInfo"/>
	</div>

</template>

<script setup>
	import {
		ref,
		onMounted,
		getCurrentInstance
	} from 'vue';
	import {
		showModelMessage,
		getUrlParams
	} from "@/utils/tools.js";
	import {
		callOrdereApi,
		callOperateApi
	} from "@/utils/api.js";

	import {
		findIndex
	} from 'lodash';
	import config from '@/utils/config';

	const imgPath = config.imgPath;

	const location = ref({
		longitude: "",
		latitude: ""
	});
	const scale = ref(15);
	const markers = ref([]);
	const polygons = ref([]); //面
	const polylines = ref([]); //线
	const circles = ref([]); //圆

	let oMap = null;

	const oUser = uni.getStorageSync("wechat_user");
	const showMess = ref(uni.getStorageSync("kbike-mess"));
	const hasOrder = ref(false); //是否有订单
	const showOrder = ref(false);
	const order = ref({
		bikecode: "123456",
		money: "2.5",
		time: "22.58min",
		mileage: "5.6km"
	});
	//订单信息
	let orderData = {
		bikeCode: null,
		status: null,
		createdAt: null,
		orderId: null
	};
	let orderTimer = null;
	const orderState = ref(0);


	//车辆
	let arrBikeData = [];
	const showBikeInfo = ref(false);

	//加载数据
	function getLoalcationData() {
		uni.getLocation({
			type: 'gcj02',
			geocode: true,
			success(res) {
				const {
					latitude,
					longitude
				} = res;
				location.value = {
					longitude: 103.975457,
					latitude: 30.633199
				};
				const params = {
					longitude: 103.975457,
					latitude: 30.633199
				};
				callOrdereApi("userOrders/bikeList", params, "post").then(res => {
					console.log("11111111111111111", "userOrders/bikeList", res);
					const {
						code,
						data,
						message
					} = res;
					if (code != 200) {
						showModelMessage(message);
						return;
					}
					arrBikeData = data || [];
					const arrData = markers.value || [];
					arrBikeData.map((item) => {
						const {
							longitude,
							latitude
						} = item;
						let index = findIndex(arrData, {
							longitude,
							latitude
						});
						index = index == -1 ? arrData.length : index;
						arrData[index] = addMarker(index, longitude, latitude, "mapbike.png",
							true);
					})
					markers.value = arrData;

				})

			},
			fail(res) {

			}
		});
	}

	function clickMess() {
		uni.setStorageSync("kbike-mess", 1);
		showMess.value = 1;
	}

	//刷新
	function refresh() {
		getLoalcationData();
	}

	//故障上报
	function reportFault() {
		if (!oUser) {
			tologin();
			return;
		}
		uni.navigateTo({
			url: "/pages/user/login/TroubleReportUser"
		})
	}

	//站点
	function getSite() {
		showModelMessage("该功能暂未实现！");
	}

	//个人中心
	function getMine() {
		if (!oUser) {
			tologin();
			return;
		}
		uni.navigateTo({
			url: "/pages/user/mine/MePage"
		})
	}

	//扫描
	function scanBike() {
		if (!oUser) {
			tologin();
			return;
		}
		const {
			userId
		} = oUser;
		uni.navigateTo({
			url: "/pages/user/scan/scancode?type=ride"
		})

	}


	//添加点
	function addMarker(id, longitude, latitude, icon, joinCluster) {
		return {
			id: id,
			latitude,
			longitude,
			width: 30,
			height: 30,
			zIndex: "100",
			iconPath: imgPath+"static/userui/home/" + icon,
			joinCluster: joinCluster ? true : false
		};
	}

	//添加线
	function addLine(scolor, arrPoints) {
		return {
			points: arrPoints,
			color: scolor,
			width: 3
		}
	}
	//显示订单
	function showOrderInfo() {
		showOrder.value = true;
	}

	//获取订单
	function getOrder() {
		const {
			userId
		} = oUser;
		callOrdereApi("userOrders/checkHistoryOrder", {
			userId
		}, "get").then(res => {
			console.log("111111111111111", "getOrder", res);
			const {
				code,
				data,
				message
			} = res;
			if (code != 200) {
				showModelMessage(message);
				return;
			}
			if (!data) { //订单完成
				completeRiding();
				return;
			}
			const {
				bikeCode,
				status,
				createdAt,
				orderId,
				tempLock,
				ridePoint,
				returnPoint
			} = data;
			//0-进行中 1-已取消 2-待支付 3-已支付  4-退款中 5-已退款
			orderState.value = tempLock ? 1 : 0;
			orderData = data;
			if (status == 2) {
				completeRiding();
				hasOrder.value = true;
				return;
			} else if (status != 0) {
				completeRiding();
				return;
			}
			showOrder.value = true;
			if (!orderTimer) {
				console.log("5555555555555555555555555555555");
				orderTimer = setInterval(getTracking, 10000);
			}
		})
	}

	//轨迹
	function getTracking() {
		const {
			bikeCode,
			createdAt,
			ridePoint,
			returnPoint
		} = orderData;
		const params = {
			ebikeCode: bikeCode,
			//startTime: createdAt
			startTime: '2025-04-02 09:00:00'
		}
		callOperateApi("ebikeTracking/query", params, "post").then(res => {
			const {
				code,
				data,
				message
			} = res;
			if (code != 200) {
				return;
			}
			const arrPoints = !data ? [] : data.map(item => {
				const {
					lngGCJ02,
					latGCJ02
				} = item;
				return {
					longitude: lngGCJ02,
					latitude: latGCJ02
				}
			})
			const lng = startPoint[0];
			const lat = startPoint[1];
			const start = {
				longitude: lng,
				latitude: lat
			}
			// const end={
			// 		longitude: endPoint[0],
			// 		latitude: endPoint[1]
			// 	}
			arrPoints.splice(0, 0, start);
			// arrPoints.push(end);

			const arrMakers = markers.value || [];
			const id = 10000000;
			let index = findIndex(arrMakers, {
				id
			});
			index = index == -1 ? arrMakers.length : index;
			arrMakers[index] = addMarker(id, lng, lat, "mapstart.png");
			markers.value = arrMakers[index];
			polylines.value = [addLine("#168DED", arrPoints)];
		})
	}

	//完成骑行
	function completeRiding() {
		if (!orderTimer) return;
		clearInterval(orderTimer);
		orderTimer = null;
		showOrder.value = false;
		hasOrder.value = false;
		orderState.value = 0;
	}

	function tologin() {
		uni.navigateTo({
			url: "/pages/user/login/wx_login"
		})
	}

	//临时锁车
	function lockRiding() {
		showModelMessage("该功能暂未实现！");
		orderState.value = 1;
	}

	//结束用车 
	function endRiding() {
		showModelMessage("该功能暂未实现！");
		const {
			userId
		} = oUser;
		const {
			bikeCode
		} = orderData;
		const params = {
			userId,
			bikeCode
		}
		callOrdereApi("userOrders/doneRide", params, "post").then(res => {
			const {
				code,
				data,
				message
			} = res;
			console.log("111111111111111111111111", "endRiding", res);
			if (code != 200) {
				showModelMessage(message);
				return;
			}
			completeRiding();
		})

	}

	//继续骑行  需要开锁
	function continueRiding() {
		showModelMessage("该功能暂未实现！");
		orderState.value = 0;
		//getOrder();
	}

	//查看车辆信息
	function openBikeInfo() {
		showModelMessage("该功能暂未实现！");
		showBikeInfo.value = true;
	}

	//关闭车辆信息
	function closeBikeInfo(){
		showBikeInfo.value =false;
	}

	getLoalcationData();

	onMounted(() => {
		const instance = getCurrentInstance();
		oMap = uni.createMapContext("mapRef", {
			this: instance.proxy
		});
		const {
			userId
		} = oUser;
		if (userId) {
			getOrder();
		}

	});
</script>

<style scoped>
	@import url("home.css");
</style>