<template>
    <view class="content">
		<view class="sign-box">
			<view class="content-show">
				<view :class="['module', moduleColor]" @click="clickSign">
					<view class="text">打卡</view>
					<view class="time">{{ time }}</view>
				</view>
			</view>
			<view class="sign-info" v-if="amSign.address">
				<view>打卡时间： {{ amSign.time }}</view>
				<view>打卡地点：{{ amSign.address }}</view>
			</view>
		</view>
		<view class="picture-box">
			<button class="picture-btn">拍照</button>
			<view class="picture-show">
				<image src="../../static/tp.png"></image>
			</view>
		</view>
		<view class="button-container">
			<view class="button-pad">
				<button class="clockBtn">核验通过</button>
				<button class="clockBtn">核验不通过</button>
			</view>
		</view>
    </view>
</template>

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

// 定义响应式数据
const moduleColor = ref('CBlue');


const amSign = ref({
    time: "",
    address: "",
    remarks: "",
    img: ""
});

const time = ref(formateDate(new Date(), 'h:min:s'));
const week = ref("");
const latitude = ref("");
const longitude = ref("");
const address = ref("我的位置");
const allSign = ref([]);
const signInfo = ref({
    mode: "",
    latitude: "",
    longitude: "",
    address: "",
    time: "",
    remarks: ""
});
// 初始化页面数据
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)) {
        amSign.value = signA[0];
    } else if (signA.length > 1) {
        amSign.value = signA[1];
    }
};

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



// 获取地址信息
const getAdd = async () => {
    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);
        }

		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) => {
    signInfo.value.latitude = lat;
    signInfo.value.longitude = lng;
    getAdd();
};

// 打卡操作
const clickSign = async () => {
    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;



        amSign.value = updatedSign[0];


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

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

<style lang="scss" scoped>
.module {
    overflow: hidden;
    margin: 20upx auto;
    width: 320upx;
    height: 320upx;
    border-radius: 50%;
    color: #fff;
    text-align: center;
}
.sign-box{
	margin-top: 40rpx;
}
.module .text {
    font-size: 20px;
    margin: 100upx auto 10upx;
}

.CBlue {
    background-color: #3E7CF7;
    box-shadow: 0 3px 3px #3E7CF7;
}

.CAsh {
    background-color: #C8C7CC;
    box-shadow: 0 3px 3px #C8C7CC;
}

.colorRed {
    color: red;
    text-align: center;
}
.sign-info{
	text-align: center;
	color: #747474;
	line-height: 60rpx;
}

.picture-box{
	margin-top: 40rpx;
	.picture-btn {
		width: 44%;
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 10rpx;
		background-color: #1E5FDF;
		color: #fff;
		font-size: 28rpx;
		text-align: center;
	  }
	  .picture-show{
		  margin: 40rpx 0 20rpx;
		  text-align: center;
	  }
}
.button-container {
	position: fixed;
	bottom: 0;
	background-color: #ffffff;
	width: 100vw;
	padding: 40rpx 0;
	.button-pad{
		padding: 0 40rpx;
		display: flex;
		justify-content: space-between;
	}
  

  .clockBtn{
    width: 44%;
    height: 70rpx;
	line-height: 70rpx;
    border-radius: 10rpx;
    background-color: #1E5FDF;
    color: #fff;
    font-size: 28rpx;
    text-align: center;
  }
}
</style>