<template>
	<view class="page flex-col">
		<view style="width: 100%;background: #f4f5f6;box-sizing: border-box;padding-top: 88px;">
			<headers titles="驾校">
				<uni-icons type="left" color="#000000" size="22px"></uni-icons>
			</headers>
		</view>
		<view class="group_4 flex-col">
			<image style="width: 100%; height: 100%;" referrerpolicy="no-referrer"
				:src="imagesUrl + '/' + schoolInfo.photo" v-if="schoolInfo.photo" />
			<!-- src="/static/lanhu_jiaxiaoxiangqing/FigmaDDSSlicePNGcd54efcc9a8c89af0ef99c8275464828.png" -->
		</view>
		<view class="group_5 flex-col">
			<text class="text_3">{{ schoolInfo.corpName }}</text>
			<view class="text-wrapper_1 flex-row justify-between">
				<text class="text_4">营业时间</text>
				<text class="text_5" v-if=" schoolInfo.businessStartTime && schoolInfo.businessEndTime ">
					{{ schoolInfo.businessStartTime }} - {{ schoolInfo.businessEndTime }}</text>
				<text class="text_5" v-else>08:00-18:00</text>
			</view>

		</view>
		<!-- 地图 -->
		<view class="map_whole flex-row">
			<!-- <view class="map_body flex-col" @click="bookingInfoClick(schoolInfo.lat, schoolInfo.lgt)"> -->
			<view class="map_body flex-col">
				<view class="map_container"
					@click="bookingInfoClick(schoolInfo.lat, schoolInfo.lgt, schoolInfo.corpName, schoolInfo.address)">
					<image class="bg-img" src="/static/imgs/mapBackground-1.png" mode="scaleToFill" />
					<view class="map-text-1">{{ schoolInfo.address }}</view>
					<!-- <view class="map-text-2">距离 {{ distance }}</view> -->
					<view class="map-text-2" v-if="showDistance">距离 {{ distance }} </view>
					<view class="get-distance-btn" v-else @click.stop="requestLocationPermission">
						<text>获取距离</text>
					</view>

				</view>
			</view>

		</view>


		<view class="group_6 flex-col">
			<view class="box_4 flex-row justify-between">
				<view class="box_5 flex-col"></view>
				<text class="text_8">报名类型</text>
			</view>
			<view v-if="schoolClassList.length > 0">
				<view class="box_6 flex-row" v-for="(item, index) in schoolClassList" :key="index"
					@click="goToDetail(item.id)">
					<view class="image-text_1 flex-row">
						<image class="image_2" referrerpolicy="no-referrer" :src="imagesUrl + '/' + item.photo" />
						<view class="text-group_2 flex-col justify-between">
							<text class="text_9">{{ item.name }}</text>
							<view class="text-wrapper_2 flex-row justify-between">
								<text class="text_10">￥{{ item.price }}</text>
							</view>
						</view>
						<view class="text-wrapper_4 flex-col">
							<view style="display: flex">
								<text class="text_13"
									style="background-color: rgba(223, 235, 255, 1);padding: 5rpx 15rpx"
									v-if="item.tittle">{{ item.tittle }}
								</text>
								<text class="text-wrapper_3  text_13" v-if="item.type"
									style="color: black;padding: 5rpx 10rpx">{{ item.type }}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="box_12 flex-row">
					<view class="image-text_2 flex-row justify-between" @click="goClassList()">
						<text class="text-group_3">查看全部班型({{ schoolAllClassList.length }})</text>
						<image class="thumbnail_2" referrerpolicy="no-referrer"
							src="/static/lanhu_jiaxiaoxiangqing/FigmaDDSSlicePNGb5045194768d2baa618848ea60e5a9e4.png" />
					</view>
				</view>
			</view>
			<view v-else>
				<u-empty mode="data" text="该驾校没有课程...">
				</u-empty>
			</view>
		</view>

		<view class="group_8 flex-col">
			<view class="group_9 flex-row justify-between">
				<view class="block_3 flex-col"></view>
				<text class="text_24">团队教练</text>
			</view>
			<view v-if="schoolCoachList.length > 0">
				<view class="group_10 flex-row justify-between" v-for="(item, index) in schoolCoachList" :key="index">
					<view class="image-text_3 flex-row justify-between">
						<image class="label_3" referrerpolicy="no-referrer" :src="imagesUrl + '/' + item.image" />
						<view class="text-group_4 flex-col justify-between">
							<text class="text_25">{{ item.name }}</text>
							<text class="text_27" v-if="item.seniority">教龄&nbsp;{{ item.seniority }}年</text>
						</view>
					</view>
				</view>
			</view>
			<view v-else>
				<u-empty mode="list" text="该驾校没有团队教练...">
				</u-empty>
			</view>

		</view>

	</view>
</template>
<script>
	import request from "@/utils/request";
	import config from "@/config.js"
	import headers from "@/components/header/headers.vue";
	import * as auth from '@/utils/auth';

	export default {
		components: {
			headers
		},
		data() {
			return {
				imagesUrl: config.imagesUrl,
				constants: {},
				schoolId: undefined,
				tenantId: undefined,
				schoolName: undefined,
				schoolDetails: {},
				schoolInfo: [],
				schoolClassList: [],
				schoolAllClassList: [],
				schoolCoachList: [],

				latitude: 0, // 地图中心纬度
				longitude: 0, // 地图中心经度
				scale: 16, // 地图缩放级别
				markers: [], // 地图标记点

				distance: '0.0', // 初始距离

				showDistance: true, // 控制是否显示距离
				locationPermissionDenied: false // 记录用户是否拒绝了位置权限


			};
		},
		async onShow() {
			// const res = await this.getLocation();
			// console.log('位置信息',res)

		},
		onLoad(options) {
			this.schoolId = options.id;
			this.tenantId = options.tenantId;
			this.schoolName = options.schoolName;
			// this.getSchoolDetails();
			this.getSchoolInfo()
			this.getSchoolClass();
			this.getSchoolAllClass()
			this.getSchoolCoach()
		},
		methods: {

			bookingInfoClick(lat, lgt, name, address) {
				// 进行导航
				uni.openLocation({
					latitude: lat,
					longitude: lgt,
					name: name,
					address: address,
					success: function() {
						console.log('success');
					}
				});
			},
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			getSchoolDetails() {
				request({
					url: '/userClient/base/companySmallProgram/noTenantIdGet',
					method: 'GET',
					params: {
						id: this.schoolId
					},
					tenantIdFlag: false
				}).then(res => {
					this.schoolDetails = res.data;
					this.tenantId = res.data.tenantId
				}).catch(err => {
					console.error('获取驾校详情失败', err);
				});
			},
			/* async getSchoolInfo() {
				try {
					const res = await request({
						url: '/userClient/base/companySmallProgram/getCompanyByTenantId',
						method: 'GET',
						params: {
							tenantId: this.tenantId,
							systemCode: 'jiaxiao',
						}
					});

					this.schoolInfo = res.data;

					// 获取用户位置并计算距离
					const userLocation = await this.getLocation();
					if (userLocation.lat && userLocation.lng && this.schoolInfo.lat && this.schoolInfo.lgt) {
						const distance = this.calculateDistance({
							latitude: userLocation.lat,
							longitude: userLocation.lng
						}, {
							latitude: parseFloat(this.schoolInfo.lat),
							longitude: parseFloat(this.schoolInfo.lgt)
						});
						this.distance = distance; // 保存距离到data中
					}
				} catch (error) {
					console.error('获取驾校信息失败', error);
				}
			}, */

			async getSchoolInfo() {
				try {
					const res = await request({
						url: '/userClient/base/companySmallProgram/getCompanyByTenantId',
						method: 'GET',
						params: {
							tenantId: this.tenantId,
							systemCode: 'jiaxiao',
						}
					});

					this.schoolInfo = res.data;

					// 获取用户位置并计算距离
					try {
						const userLocation = await this.getLocation();
						if (userLocation.lat && userLocation.lng && this.schoolInfo.lat && this.schoolInfo.lgt) {
							const distance = this.calculateDistance({
								latitude: userLocation.lat,
								longitude: userLocation.lng
							}, {
								latitude: parseFloat(this.schoolInfo.lat),
								longitude: parseFloat(this.schoolInfo.lgt)
							});
							this.distance = distance;
							this.showDistance = true;
							this.locationPermissionDenied = false;
						}
					} catch (error) {
						console.error('获取位置失败', error);
						this.showDistance = false;
						this.locationPermissionDenied = true;
					}
				} catch (error) {
					console.error('获取驾校信息失败', error);
				}
			},

			getSchoolClass() {
				request({
					url: '/app-api/dl-drive-school-course-small/noTenantIdPage',
					method: 'GET',
					params: {
						pageNo: 1,
						pageSize: 4,
						tenantId: this.tenantId,
					},
					tenantIdFlag: false
				}).then(res => {
					this.schoolClassList = res.data.records;
					this.total = res.data.total;
				})
			},
			//获取当前位置
			getLocation() {
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {
							resolve({
								lat: res.latitude,
								lng: res.longitude
							});
						},
						fail: (err) => {
							console.error('获取位置失败', err);
							// 用户拒绝了位置授权
							if (err.errMsg.includes('auth deny') || err.errMsg.includes(
									'fail auth deny')) {
								this.showDistance = false;
								this.locationPermissionDenied = true;
							}
							reject(err);
						}
					});
				});
			},

			// 计算两点间距离（单位：米）
			calculateDistance(loc1, loc2) {
				const {
					latitude: lat1,
					longitude: lng1
				} = loc1;
				const {
					latitude: lat2,
					longitude: lng2
				} = loc2;

				// 将经纬度转换为弧度
				const rad = (d) => d * Math.PI / 180.0;
				const radLat1 = rad(lat1);
				const radLat2 = rad(lat2);
				const a = radLat1 - radLat2;
				const b = rad(lng1) - rad(lng2);

				// 使用Haversine公式计算距离
				const s = 2 * Math.asin(Math.sqrt(
					Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) *
					Math.cos(radLat2) *
					Math.pow(Math.sin(b / 2), 2)
				));

				const EARTH_RADIUS = 6378.137; // 地球半径（千米）
				const distance = s * EARTH_RADIUS;

				// 小于1公里显示米，大于等于1公里显示千米
				if (distance < 1) {
					return (distance * 1000).toFixed(0) + '米';
				} else {
					return distance.toFixed(2) + '公里';
				}
			},

			wxGeocoder(address) {
				return new Promise((resolve, reject) => {
					// 需要先通过chooseLocation获取坐标（用户交互触发）
					uni.chooseLocation({
						success: (res) => {
							resolve({
								latitude: res.latitude,
								longitude: res.longitude
							});
						},
						fail: (err) => reject(err)
					});
				});
			},


			getSchoolAllClass() {
				request({
					url: '/app-api/dl-drive-school-course-small/list',
					method: 'GET',
					params: {
						tenantId: this.tenantId,
					},
					tenantIdFlag: false
				}).then(res => {
					this.schoolAllClassList = res.data;
					this.total = res.data.total;
				})
			},

			getSchoolCoach() {
				console.log('执行');
				request({
					url: '/app-api/dl-drive-school-coach-small/page',
					method: 'GET',
					params: {
						tenantId: this.tenantId,
						pageNo: 1,
						pageSize: 100000,
						type: 'jl'
					},
					tenantIdFlag: false
				}).then(res => {
					// 对数据进行排序
					const sortedList = res.data.records.sort((a, b) => b.seniority - a.seniority);
					const coachId = auth.getCoachId()
					const staffType = auth.getStaffType()
					console.log(coachId, 'coachId');
					if (coachId && staffType === '02') {
						const coach = res.data.records.find(item => item.userId == coachId)
						console.log(coach, 'coach');
						if (coach) {
							this.schoolCoachList.push(coach)
						} else {
							// 取排序后的前三条数据
							this.schoolCoachList = sortedList.slice(0, 3);
							this.total = res.data.total;
						}
					} else {
						// 取排序后的前三条数据
						this.schoolCoachList = sortedList.slice(0, 3);
						this.total = res.data.total;
					}
				}).catch(e => {
					console.log(e);
				})
			},

			goClassList() {
				uni.navigateTo({
					url: '/newPages/courseList/index?tenantId=' + this.tenantId,
				});
			},
			// 跳转到详情页
			goToDetail(courseId) {
				uni.navigateTo({
					url: `/pagesA/courseDetail/index?courseId=${courseId}&tenantId=${this.tenantId}`,
				});
			},

			// 请求位置权限
			requestLocationPermission() {
				uni.showModal({
					title: '提示',
					content: '需要获取您的位置信息才能计算距离，是否前往设置开启权限？',
					success: (res) => {
						if (res.confirm) {
							// 打开设置页面
							uni.openSetting({
								success: (res) => {
									if (res.authSetting['scope.userLocation']) {
										// 用户授权了位置权限，重新获取位置
										this.getSchoolInfo();
									}
								}
							});
						}
					}
				});
			},

			// 初始化地图
			/* initMap() {
				// 假设驾校地址的经纬度已经获取或通过接口返回
				if (this.schoolInfo.lat && this.schoolInfo.lgt) {
					this.latitude = parseFloat(this.schoolInfo.lat);
					this.longitude = parseFloat(this.schoolInfo.lgt);

					this.markers = [{
						id: 1,
						latitude: this.latitude,
						longitude: this.longitude,
						title: this.schoolInfo.corpName,
						iconPath: '/static/location.png', // 自定义标记图标
						width: 30,
						height: 30
					}];
				}
			}, */




			// 点击地图事件
			/* handleMapTap() {
				// 打开地图APP或导航
				uni.openLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					name: this.schoolInfo.corpName,
					address: this.schoolInfo.address
				});
			}, */

		}
	};
</script>
<style lang='scss'>
	@import '../common/common.scss';
	@import './assets/style/index.rpx.scss';

	.map_whole {
		width: 100%;
		height: 180rpx;
		/* background-color: #000000; */
		margin: 0 0 10rpx 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.map_body {
		width: 92%;
		height: 95%;
		/* background-color: #00aaff; */
		border-radius: 16rpx;
	}

	.map_container {
		position: relative;
		width: 100%;
		height: 300rpx;
		overflow: hidden;
	}

	.bg-img {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: 0;
	}

	.map-text-1 {
		width: 70%;
		position: absolute;
		top: 30rpx;
		left: 20rpx;
		z-index: 1;
		color: #000;
		font-size: 26rpx;
		right: 20rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		word-break: break-word;

	}

	.map-text-2 {
		margin-top: 30rpx;
		position: absolute;
		top: 80rpx;
		left: 20rpx;
		z-index: 1;
		color: #5f5f5f;
		font-size: 26rpx;
	}

	.get-distance-btn {
		margin-top: 30rpx;
		position: absolute;
		top: 80rpx;
		left: 20rpx;
		z-index: 1;
		color: #007AFF;
		font-size: 26rpx;
		padding: 5rpx 15rpx;
		background-color: rgba(223, 235, 255, 1);
		border-radius: 8rpx;
	}

	.get-distance-btn text {
		color: #007AFF;
	}
</style>