<template>
	<view>
		<view v-if="canUse">
			<view class="form-item" v-if="[1, 2, 10].includes(Number(formData.leaveStatus))">
				<view class="status-flex">
					<label>审核状态：</label>
					<!-- <view style="color: red;border-bottom: 1px solid black;"> {{formData.status == 1 ? "已提交"
				: formData.status == 2 ? "通过"
				:formData.status == 10 ? "打回" :""}}
				</view> -->
					<view>
						<u-tag :text="leaveStatusText"></u-tag>
					</view>
				</view>
			</view>

			<view class="form-item">
				<label>家长姓名</label>
				<input :disabled="formData.status == 2" placeholder="请输入" v-model="formData.parentName" />
			</view>
			<view class="form-item">
				<label>家长电话</label>
				<input :disabled="formData.status == 2" placeholder="请输入" v-model="formData.parentPhone" />
			</view>
			<view v-if="formData.status != 2" class="form-item">
				<label>家长是否知晓</label>
				<radio-group @change="radioChange1">
					<label class="uni-list-cell uni-list-cell-pd">
						<view class="radio-flex">
							<radio :checked="formData.know=='是'" :value="'是'" />是
						</view>
					</label>
					<label style="margin-left: 80rpx;" class="uni-list-cell uni-list-cell-pd">
						<view class="radio-flex">
							<radio :checked="formData.know=='否'" :value="'否'" />否
						</view>
					</label>
				</radio-group>
			</view>
			<view v-if="formData.status == 2" class="form-item">
				<label>家长是否知晓：{{formData.know}}</label>
			</view>

			<view>
				<view v-if="formData.status != 2" class="form-item">
					<label>是否到校 <text style="color: red;">*请在到校后填写</text></label>
					<radio-group @change="radioChange2">
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="radio-flex">
								<radio :checked="formData.reachSchoolStatus=='是'" :value="'是'" />是
							</view>
						</label>
						<label style="margin-left: 80rpx;" class="uni-list-cell uni-list-cell-pd">
							<view class="radio-flex">
								<radio :checked="formData.reachSchoolStatus=='否'" :value="'否'" />否
							</view>
						</label>
					</radio-group>
				</view>
				<view v-if="formData.status == 2" class="form-item">
					<label>是否到校：<text style="color: red;">{{formData.reachSchoolStatus}}</text></label>
				</view>

				<view v-if="formData.reachSchoolStatus=='是'">
					<view class="form-item">
						<label>到校时间 <text style="color: red;">*请在到校后填写</text></label>
						<DateTimePicker :disabled="formData.status == 2" v-model="formData.attendSchoolTime" />
					</view>

					<view class="form-item">
						<label>到校定位 <text style="color: red;">*请在到校后填写</text> </label>
						<view>
							<button style="display: inline-block;" @click="getLocation">获取定位</button>
							<button v-if="formData.status!=2" type="primary"
								style="display: inline-block;margin-left: 30rpx;" @click="stuSchoolUpdate">点我提交</button>
							<map style="width:100%;height:300px;" :latitude="latitude" :longitude="longitude"
								:markers="covers" show-location></map>
						</view>
					</view>
				</view>
				<view v-if="formData.reachSchoolStatus=='否'">
					<view class="form-item">
						<label>未返校原因</label>
						<uni-data-select :disabled="formData.status == 2" placeholder="请选择"
							v-model="formData.absentSchoolType" :localdata="absentSchoolTypeList">
						</uni-data-select>
					</view>
					<view class="form-item">
						<label>未返校详细原因</label>
						<textarea :disabled="formData.status == 2" placeholder="请输入"
							v-model="formData.absentSchoolRemark" />
					</view>
					<button v-if="formData.status!=2" type="primary" @click="stuSchoolUpdate">点我提交</button>
				</view>

			</view>


		</view>

	</view>
</template>

<script>
	import DateTimePicker from "@/components/DateTimePicker.vue";
	import {
		getWxConfig
	} from "@/api/common/wechat";
	import wx from "weixin-js-sdk"; // 引入微信 JS-SDK
	import * as ww from '@wecom/jssdk'
	import {
		isEmpty,
		isValidPhone
	} from "@/api/helpFunc/index.js";

	import {
		boolStuOwnReturn,
		stuWillReturnUpdate,
		stuSchoolUpdate,
		getStuCampus
	} from '@/api/sur';
	import {
		getOwnInfo,
		getOwnFamily
	} from "@/api/person/person.js";
	export default {
		components: {
			DateTimePicker
		},
		data() {
			return {
				absentSchoolTypeList: [{
						text: '路上',
						value: '路上'
					},
					{
						text: '病假',
						value: '病假'
					},
					{
						text: '无票',
						value: '无票'
					},
					{
						text: '无课请事假延长',
						value: '无课请事假延长'
					},
					{
						text: '事假',
						value: '事假'
					},
					{
						text: '红白事',
						value: '红白事'
					},
					{
						text: '考试',
						value: '考试'
					},
					{
						text: '参赛',
						value: '参赛'
					},
					{
						text: '兵检或役前训练',
						value: '兵检或役前训练'
					},
					{
						text: '退学或休学',
						value: '退学或休学'
					}
				],
				latitude: 108.31019592285156, // 纬度
				longitude: 22.90125274658203, // 经度
				covers: [{
					latitude: 108.31019592285156,
					longitude: 22.90125274658203,
					iconPath: '../../static/images/applyrelieve/location.png'
				}],
				canUse: false,

				formData: {
					scheduledReturnTime: '',
					attendSchoolTime: ''
				},
				returnSchoolId: null,
				distanceThreshold: 1000,
				circlePolyline: [],

				ownPhone: null,
				ownParentName: null,
				ownParentPhone: null
			}
		},
		computed: {
			leaveStatusText() {
				const statusMap = {
					1: "已提交",
					2: "通过",
					10: "打回"
				};
				return statusMap[this.formData.leaveStatus] || "";
			}
		},
		onLoad(options) {
			if (isEmpty(options.id)) {
				uni.redirectTo({
					url: "/pages/sub/StuApply"
				})
			} else {
				this.returnSchoolId = options.id;
				this.boolStuOwnReturn();
			}
		},
		async onShow() {
			await this.initWxConfig(); // 初始化微信配置
			this.getLocation();
		},
		methods: {
			async getOwnFamily() {
				uni.showLoading();
				let res = await getOwnFamily();
				uni.hideLoading();
				if (res.code == 200) {
					let data = [...res.data];
					if (!isEmpty(data)) {
						this.ownParentName = data[0].familyName;
						this.ownParentPhone = data[0].phone;
					}
				}
			},
			async getOwnInfo() {
				uni.showLoading();
				let res = await getOwnInfo();
				uni.hideLoading();
				if (res.code == 200) {
					this.ownPhone = res.data.stuPhone;
				}
			},
			async stuSchoolUpdate() {
				let sdata = {
					...this.formData
				};
				if (isEmpty(sdata.reachSchoolStatus)) {
					uni.showToast({
						title: "请选择是否到校",
						icon: "none",
						mask: true
					});
					return;
				}

				if (isEmpty(sdata.parentName)) {
					uni.showToast({
						title: "请输入家长姓名",
						icon: "none",
						mask: true
					});
					return;
				}
				if (isEmpty(sdata.parentPhone)) {
					uni.showToast({
						title: "请输入家长电话",
						icon: "none",
						mask: true
					});
					return;
				}

				if (!isValidPhone(sdata.parentPhone)) {
					uni.showToast({
						title: "家长电话格式不正确",
						icon: "none",
						mask: true
					});
					return;
				}

				if (sdata.reachSchoolStatus == "是" && isEmpty(sdata.attendSchoolTime)) {
					uni.showToast({
						title: "请选择到校时间",
						icon: "none",
						mask: true
					});
					return;
				}

				if (sdata.reachSchoolStatus == "是" && isEmpty(this.latitude)) {
					uni.showToast({
						title: "请定位",
						icon: "none",
						mask: true
					});
					return;
				}
				if (sdata.reachSchoolStatus == "是") {
					if (await this.checkIfNearCampus()) {
						sdata.attendSchoolGps = this.latitude + "," + this.longitude;
					} else {
						uni.showToast({
							title: "您不在学校附近",
							icon: "error"
						});
						return;
					}
				}

				if (sdata.reachSchoolStatus == "否" && isEmpty(sdata.absentSchoolType)) {
					uni.showToast({
						title: "请选择未返校原因",
						icon: "none",
						mask: true
					});
					return;
				}

				if (sdata.reachSchoolStatus == "否" && isEmpty(sdata.absentSchoolRemark)) {
					uni.showToast({
						title: "请输入详细原因",
						icon: "none",
						mask: true
					});
					return;
				}

				uni.showLoading();
				let res = await stuSchoolUpdate(sdata).then(res => {
					uni.hideLoading();
					if (res.code == 200) {
						uni.showToast({
							title: res.msg,
							mask: true,
							icon: "success"
						});
						//返回
						uni.navigateBack();
					}
				});


			},
			async checkIfNearCampus() {
				const campuses = [{
						name: "长堽校区",
						latitude: 22.835938,
						longitude: 108.351728
					},
					{
						name: "里建校区",
						latitude: 23.206284,
						longitude: 108.18664
					}
				];
				let isNearby = false;
				let res = false;

				let campus = campuses[0];
				let p1 = {
					latitude: this.latitude,
					longitude: this.longitude
				}
				let distance = this.getDistance(
					p1.latitude, p1.longitude,
					campus.latitude, campus.longitude
				);
				isNearby = distance < this.distanceThreshold;
				if (isNearby) {
					res = true;
				}

				campus = campuses[1];
				distance = this.getDistance(
					p1.latitude, p1.longitude,
					campus.latitude, campus.longitude
				);
				isNearby = distance < this.distanceThreshold;

				if (isNearby) {
					res = true;
				}

				if (res) {
					return true;
				} else {
					uni.showToast({
						icon: "error",
						title: "您不在校区范围内"
					});
					return false;
				}
			},
			distanceToLngLatOffset(distance) {
				const earthRadius = 6371000; // 地球半径，单位：米
				const radLat = this.centerLat * (Math.PI / 180);
				const dLat = (distance / earthRadius) * (180 / Math.PI);
				const dLng = (distance / (earthRadius * Math.cos(radLat))) * (180 / Math.PI);
				return {
					dLat,
					dLng
				};
			},
			toRadians(degree) {
				return degree * (Math.PI / 180);
			},

			// 计算两个经纬度之间的距离（近似计算，适用于小范围）
			getDistance(lat1, lng1, lat2, lng2) {
				const EARTH_RADIUS = 6378137; // 地球半径，单位：米
				const dLat = this.toRadians(lat2 - lat1);
				const dLng = this.toRadians(lng2 - lng1);
				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.toRadians(lat1)) *
					Math.cos(this.toRadians(lat2)) *
					Math.sin(dLng / 2) *
					Math.sin(dLng / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return EARTH_RADIUS * c;
			},
			drawCircle() {
				const points = [];
				const distance = 1000; // 1000米的半径
				const offset = this.distanceToLngLatOffset(distance);
				const numPoints = 30; // 圆圈由多少个点组成，越多越接近圆形
				for (let i = 0; i < numPoints; i++) {
					const angle = (i / numPoints) * 2 * Math.PI;
					const newLat = this.latitude + offset.dLat * Math.sin(angle);
					const newLng = this.longitude + offset.dLng * Math.cos(angle);
					points.push({
						latitude: newLat,
						longitude: newLng
					});
				}
				// 确保最后一个点和第一个点重合，形成封闭图形
				points.push({
					latitude: points[0].latitude,
					longitude: points[0].longitude
				});
				this.circlePolyline = [{
					points: points,
					color: "#FF0000", // 圆圈颜色
					width: 2, // 线条宽度
					dottedLine: false // 是否为虚线
				}];
			},
			async initWxConfig() {
				let that = this;
				let res = await that.getConfigSignature();
				that.info += JSON.stringify(res)
				ww.register({
					corpId: 'wx129e6bf0f36b8b3d', // 必填，当前用户企业所属企业ID
					agentId: 1000093, // 必填，当前应用的AgentID
					jsApiList: ["getLocation", "openLocation"], // 必填，需要使用的JSAPI列表
					// getAgentConfigSignature: that.getAgentConfigSignature, // 必填，根据url生成应用签名的回调函数
					getConfigSignature() {
						console.log(res)
						return res
					}
				})
			},
			// 初始化微信 JS-SDK
			async getConfigSignature() {
				return new Promise((resolve, reject) => {
					// 调用后端接口获取签名信息（需要后端支持）
					getWxConfig("corpId").then(res => {
						const {
							timestamp,
							nonceStr,
							signature
						} = res;
						resolve({
							timestamp,
							nonceStr,
							signature
						});
					}).catch(err => {
						reject(err);
					});
				});
			},
			async getAgentConfigSignature() {
				return new Promise((resolve, reject) => {
					// 调用后端接口获取签名信息（需要后端支持）
					getWxConfig("agentId").then(res => {
						const {
							timestamp,
							nonceStr,
							signature
						} = res;
						resolve({
							timestamp,
							nonceStr,
							signature
						});
					}).catch(err => {
						reject(err);
					});
				});
			},
			getLocation() {
				let that = this;
				ww.getLocation({
					type: 'gcj02', // GPS坐标  gcj02  wgs84
					success(res) {
						that.latitude = res.latitude
						that.longitude = res.longitude
						that.covers[0].latitude = res.latitude
						that.covers[0].longitude = res.longitude
						// this.drawCircle();

					},
					fail(err) {
						that.info += JSON.stringify(err) + "定位失败fail";
						uni.showToast({
							title: '定位失败' + JSON.stringify(err),
							icon: 'none'
						})
					},
					complete(err) {
						that.info += JSON.stringify(err) + "定位失败complete";
					}
				})
			},
			radioChange2(evt) {
				this.formData.reachSchoolStatus = evt.detail.value;
			},
			radioChange1(evt) {
				this.formData.know = evt.detail.value;
			},
			async stuWillReturnUpdate() {
				let sdata = {
					...this.formData
				};
				uni.showLoading();
				let res = await stuWillReturnUpdate(sdata);
				uni.hideLoading();
				if (res.code == 200) {
					uni.showToast({
						icon: "success",
						title: res.msg
					});
					this.boolStuOwnReturn();
				}
			},
			async boolStuOwnReturn() {
				uni.showLoading();
				let res = await boolStuOwnReturn(this.returnSchoolId);
				uni.hideLoading();
				if (res.code != 200) {
					uni.redirectTo({
						url: "/pages/sub/StuApply"
					})
				} else {
					this.canUse = true;
					this.formData = {
						...res.data
					};
					await this.getOwnInfo();
					await this.getOwnFamily();
					if (this.formData.status != 2 && this.formData.status != 11) {
						this.formData.parentName = this.ownParentName;
						this.formData.parentPhone = this.ownParentPhone;
					}
					console.log(this.formData);
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.form-item {
		display: flex;
		flex-direction: column;
		padding: 22rpx 40rpx;
		background-color: white;
		margin-bottom: 20rpx;
		border-radius: 16rpx;

		&.tip {
			justify-content: center;

			text:first-child {
				color: red;
			}

			text:last-child {
				margin-top: 10rpx;
				color: #FFBA00;
			}
		}

		.tip {
			color: red;
			font-size: 24rpx;
		}

		label {
			margin-bottom: 20rpx;
			display: inline-block;
			font-weight: bold;

			text {
				color: red;
			}
		}

		textarea {
			height: 200rpx;
			border: 1px solid #E1E1E1;
			padding: 20rpx;
			width: 100%;
		}

		input {
			border: 1px solid #E1E1E1;
			border-radius: 10rpx;
			height: 70rpx;
			padding-left: 30rpx;
		}

		picker {
			border: 1px solid #E1E1E1;
			height: 70rpx;
			line-height: 70rpx;
			padding: 0 30rpx;

			.uni-input {
				display: flex;
				color: #797979;

				.val {
					flex: 1;
				}
			}
		}
	}

	.status-flex {
		display: flex;
	}

	.radio-flex {
		display: flex;
		gap: 20rpx;
		align-items: center;
	}
</style>