<template>
	<view class="con-body">
		<view class="con-bg">
			<!-- 头部 -->
			<customHeader ref="customHeaderRef" :title="'签到打卡'" :leftFlag="true" :rightFlag="false"></customHeader>

			<!-- 高度来避免头部遮挡 -->
			<view class="top-height" :style="{ paddingTop: navBarPaddingTop + 'px' }"></view>

			<view class="inner-box">
				<view class="cu-form-group" style="height: 200px;padding:10px;">
					<uni-forms ref="formRef" :model="form" label-width="100px">
						<uni-forms-item label="签到备注内容" name="understandTheWay"
							class="uni-forms-item is-direction-top is-top">
							<uni-easyinput type="textarea" autoHeight v-model="form.remark" placeholder="请输入签到备注内容"
								class="form-texarea" />
						</uni-forms-item>
					</uni-forms>

					<view class="btn-box" style="padding-top: 50px;">
					<button type="primary" @click="addInsertMapClockIn">签到</button>
				</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import customHeader from '@/components/customHeader.vue'
import { onMounted, reactive, ref } from 'vue';
import { addStartMap } from '@/api/crm/activity/map';
import { parseTime } from '@/utils/datetime.js';
import { onLoad } from '@dcloudio/uni-app';
import { getNavBarPaddingTop } from '@/utils/system.js'
let form = reactive({
	addressForStart: null,
	addressForEnd: null,
	createId: null,
	staffName: null,
	visistCode: null,
	visistId: null,
	mapId: null,
	remark: null
})

// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(() => {
	navBarPaddingTop.value = getNavBarPaddingTop() * 2;
})

onLoad(option => {
	form.visistId = option.visistId
	let date = new Date();
	form.craeteTime = parseTime(date, '{y}-{m}-{d}');
})

function addInsertMapClockIn() {
	uni.getLocation({
		type: 'wgs84',
		success: (res) => {
			const latiude = res.latitude; //纬度
			const longitude = res.longitude; //经度
			//进行解析
			inverseGeocoding(latiude, longitude);
		},
		fail: function (err) {
			console.log("获取地址失败" + err)
		}
	})
}
function isWithinRange(lat, lon, centerLat, centerLon, rangeKm) {
	const distance = haversineDistance(centerLat, centerLon, lat, lon);
	return distance <= rangeKm;
}
function haversineDistance(lat1, lon1, lat2, lon2, radius = 6371) {
	const dLat = degToRad(lat2 - lat1);
	const dLon = degToRad(lon2 - lon1);
	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	return radius * c; // 距离，单位：公里
}
function degToRad(deg) {
	return deg * (Math.PI / 180);
}
function inverseGeocoding(latiude, longitude) {
	let points = longitude + ',' + latiude
	//URL
	const apiURL = 'https://tiles.geovisearth.com/geo/v1/geocode/regeo';
	const params = {
		lat: latiude,
		lng: longitude,
		radius: 1000,
		pageSize: 1,
		currentPage: 1,
	};
	const token = '66c87c897f0251295afdc794e4fbf73046a070338a726fe04f06cece6cb1ffdf';
	uni.request({
		url: apiURL,
		method: 'GET',
		data: params,
		header: {
			'Authorization': 'Bearer ' + token
		},
		success: (res) => {
			if (res.statusCode == 200 && res.data.status == 200) {
				let resdata = res.data.data.rows[0].address
				if (resdata == null) {
					const latiude1 = ref(34.1360);
					const longitude1 = ref(108.9126);
					if (isWithinRange(latiude1.value, longitude1.value, latiude, longitude, 1)) {
						form.addressForStart = "西安办事处位置签到"
						uni.showModal({
							title: '确定要在此处签到吗',
							content: form.addressForStart,
							success: function (res) {
								if (res.confirm) {
									var data = {
										mapId: form.mapId,
										addressForStart: form.addressForStart,
										cusName: form.cusName,
										cusId: form.cusId,
										remark: form.remark,
										path: longitude1 + "," + latiude1
									}
									addStartMap(data).then(res => {
										if (res.code == 200) {
											uni.showToast({
												icon: 'success',
												title: res.msg,
												duration: 1500,
											});
											setTimeout(() => {
												uni.navigateBack(1)
											}, 500)
										} else {
											uni.showToast({
												icon: 'none',
												title: res.msg,
											});
										}
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				} else {
					form.addressForStart = resdata;
					uni.showModal({
						title: '确定要在此处签到吗',
						content: form.addressForStart,
						success: function (res) {
							if (res.confirm) {
								var data = {
									mapId: form.mapId,
									addressForStart: form
										.addressForStart,
									cusName: form.cusName,
									cusId: form.cusId,
									remark: form.remark,
									path: points
								}
								addStartMap(data).then(res => {
									if (res.code == 200) {
										uni.showToast({
											icon: 'success',
											title: res.msg,
											duration: 1500,
										});
										setTimeout(() => {
											uni.navigateBack(1)
										}, 500)
									} else {
										uni.showToast({
											icon: 'none',
											title: res.msg,
										});
									}
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			} else {
				form.addressForStart = "第三方维护签到"
				uni.showModal({
					title: '确定要在此处签到吗',
					content: form.addressForStart,
					success: function (res) {
						if (res.confirm) {
							var data = {
								mapId: form.mapId,
								addressForStart: form.addressForStart,
								cusName: form.cusName,
								cusId: form.cusId,
								path: points
							}
							addStartMap(data).then(res => {
								if (res.code == 200) {
									uni.showToast({
										icon: 'success',
										title: '第三方维护签到',
										duration: 1500,
									});
								} else {
									uni.showToast({
										icon: 'none',
										title: res.msg,
									});
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		},
		fail(e) {
			console.log("获取位置失败", e)
		}
	})

}

</script>

<style lang="scss" scoped>
.con-bg {
	background: white;
}

/* Container for the checkbox group */
.checkbox-group.block {
	width: 100%;
}

/* Each item row */
.itemClass {
	display: flex;
	align-items: center;
	padding: 10rpx 0;
	margin-left: 15rpx;
	border-bottom: 1px solid #eee;
	/* optional divider */
}

/* Checkbox styling */
.checkBoxClass {
	margin-right: 12rpx;
}

/* Content container */
.clientClass {
	flex: 1;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	font-size: 36rpx;
	color: #333;
	/* default text color */
}

/* Blue username text */
.blue-text {
	/* or any blue you prefer */
	margin-right: 5rpx;
}
</style>
