<template>
	<view class="content">
		<view class="page-body">
			

			<view class="content-show">
				<view v-if="is === null">
					<view class="module CAsh">
						<view class="text">定位失败</view>
						<view class="time">{{time}}</view>
					</view>
					<view class="colorRed" style="text-align: center;">
						<text>请检查手机定位服务状态</text>
						<text class="relocation" @click="relocation">刷新</text>
					</view>
				</view>
				<view v-else>
					<view :class="['module', moduleColor]" @click="clickSign">
						<view class="text">打卡</view>
						<view class="time">{{time}}</view>
					</view>
					
				</view>
			</view>
			<view>
				<view>打卡时间： {{amSign.time}}</view>
				<view>打卡地点：{{amSign.address}}</view>
			</view>
			
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		formateDate,
		pointInsideCircle,
		isSameDay
	} from "@/common/util.js";
	import {
		handleSignClick,
		setSignInfo,
		addSignInfo,
		getSignInfo,
		delSignInfo,
		getInfo,
		key
	} from "./clockIn.js";

	// 定义响应式数据
	const name = ref("Navy_c");
	const moduleColor = ref('CBlue');
	const moduleTitle = ref('上班打卡');
	const bzText = ref({
		time: "",
		address: "",
		img: "",
		remarks: ""
	});
	const type = ref("");
	const achievement = ref({
		money: "888.88",
		num: "1"
	});
	const r = ref(80);
	const Timer = ref([{
		time: "09:00"
	}, {
		time: "18:00"
	}]);
	const isAm = ref(false);
	const isPm = ref(false);
	const amSign = ref({
		time: "",
		address: "",
		remarks: "",
		img: ""
	});
	const clickNum = ref(0);
	const is = ref(null);
	const isSign = ref(false);
	const time = ref(formateDate(new Date(), 'h:min:s'));
	const date = ref(formateDate(new Date(), 'Y-M-D'));
	const week = ref("");
	const latitude = ref("");
	const longitude = ref("");
	const address = ref("我的位置");
	const wqInfo = ref(null);
	const allSign = ref([]);
	const organize = ref('R & D department');
	const signInfo = ref({
		mode: "",
		latitude: "",
		longitude: "",
		address: "",
		time: "",
		remarks: ""
	});
	const covers = ref([{
		id: 0,
		callout: {
			content: "南京xxx技术有限公司",
			color: "red",
			display: "ALWAYS"
		},
		latitude: 113224630.115,
		longitude: 1837131905.02,
		iconPath: '../../../static/img/location.png'
	}]);
	const circles = ref([{
		latitude: 113224630.115,
		longitude: 1837131905.02,
		radius: 80,
		strokeWidth: 1,
		fillColor: "#7fff0099"
	}]);

	// 初始化页面数据
	const initializePage = async () => {
		const sign = getSignInfo();
		if (sign && sign.main) {
			const signA = [...sign.main].reverse();
			allSign.value = signA;

			// 检查当天是否已经签到
			checkIfSigned(signA);
		}

		await getLocation();
		getTime();
		getWeekDate();
	};

	// 检查当天是否已经签到
	const checkIfSigned = (signA) => {
		if (signA.length === 1 && isSameDay(signA[0].nowT)) {
			isSign.value = true;
			isAm.value = true;
			amSign.value = signA[0];
		} else if (signA.length > 1) {
			
				isSign.value = true;
				isAm.value = true;
				amSign.value = signA[1];
			
		}
	};

	// 获取星期几
	const getWeekDate = () => {
		const now = new Date();
		const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
		week.value = weeks[now.getDay()];
	};



	// 获取地址信息
	const getAdd = async () => {
		if (isAm.value && isPm.value) return;

		if (is.value === true) {
			address.value = covers.value[0].callout.content;
			signInfo.value.address = address.value;
			return;
		}

		try {
			const res = await uni.request({
				url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude.value},${longitude.value}&key=${key}`,
			});

			const data = res.data;
			if (data.status !== 0) {
				throw new Error(data.message);
			}

			if (is.value === null) {
				address.value = "请检查位置信息！";
			} else if (is.value === false) {
				let addressStr = `${data.result.address} ${data.result.formatted_addresses.recommend}`;
				address.value = addressStr;
				signInfo.value.address = addressStr;
			}
		} catch (error) {
			uni.showToast({
				title: error.message || "获取地址失败",
				icon: "none"
			});
		}
	};
	// 实时时间
	const getTime = async () => {
		setInterval(function() {
			time.value = formateDate(new Date(), 'h:min:s')
		}, 1000)
	};
	// 获取位置信息
	const getLocation = async () => {
		try {
			uni.showLoading({
				title: "获取中...",
				mask: true
			});

			const res = await uni.getLocation({
				type: 'gcj02'
			});
			uni.hideLoading();

			latitude.value = res.latitude;
			longitude.value = res.longitude;
			updateLocation(res.latitude, res.longitude);
		} catch (error) {
			uni.hideLoading();
			address.value = "请检查位置信息";
			uni.showToast({
				title: "请检查位置信息状态！",
				icon: "none",
				mask: true,
				duration: 3000
			});
		}
	};

	// 更新位置信息
	const updateLocation = (lat, lng) => {
		covers.value.push({
			id: 1,
			latitude: lat,
			longitude: lng,
			iconPath: '../../static/location.png'
		});
		const s = pointInsideCircle([lat, lng], [circles.value[0].latitude, circles.value[0].longitude], r.value /
			100000);
		is.value = s;
		signInfo.value.latitude = lat;
		signInfo.value.longitude = lng;
		signInfo.value.mode = s ? "正常打卡" : "外勤打卡";
		getAdd();
	};

	// 打卡操作
	const clickSign = async () => {
		if (is.value === null) {
			uni.showToast({
				title: "请检查位置信息状态！",
				icon: "none",
				mask: true,
				duration: 3000
			});
			return;
		}

		try {
			await getLocation(); // 再次获取数据
			uni.showLoading({
				title: "打卡记录中...",
				mask: true
			});

			signInfo.value.time = formateDate(new Date(), 'Y-M-D h:min:s');
			const a = getSignInfo();
			if (a) {
				addSignInfo(getInfo(signInfo.value), a);
			} else {
				setSignInfo(getInfo(signInfo.value));
			}

			const updatedSign = getSignInfo().main.reverse();
			allSign.value = updatedSign;
			isSign.value = true;


			isAm.value = true;
			amSign.value = updatedSign[0];


			uni.showToast({
				title: "打卡成功！"
			});
		} catch (error) {
			uni.showToast({
				title: "打卡失败，请稍后再试！",
				icon: "none",
				mask: true
			});
		} finally {
			uni.hideLoading();
		}
	};

	// 初始化页面
	onMounted(() => {
		initializePage();
	});
</script>

<style>
	.module {
			overflow: hidden;
			margin: 20upx auto;
			width: 220upx;
			height: 220upx;
			border-radius: 50%;
			color: #fff;
			text-align: center;
		}
	
		.module .text {
			font-size: 20px;
			margin: 50upx auto 10upx;
		}
	
		.CBlue { background-color: #007aff; box-shadow: 0 3px 3px #007aff; }
		.CAsh { background-color: #C8C7CC; box-shadow: 0 3px 3px #C8C7CC; }
	
		.colorRed { color: red; text-align: center; }
</style>