<template>
	<van-sticky>
		<van-nav-bar title="每日答题" />
	</van-sticky>

	<van-overlay :show="overlayloading">
		<div class="wrapper">
			<van-loading color="#0094ff"> 加载中... </van-loading>
		</div>
	</van-overlay>

	<van-grid :column-num="3">
		<van-grid-item>
			<div class="numStyle">{{ totaltimes }}/{{ 3 }}</div>
			<div class="descStyle">今日答题次数</div>
		</van-grid-item>

		<van-grid-item>
			<div class="numStyle">{{ score }}</div>
			<div class="descStyle">今日得分</div>
		</van-grid-item>

		<van-grid-item>
			<div class="numStyle">{{ total }}</div>
			<div class="descStyle">总分</div>
		</van-grid-item>
	</van-grid>
	<!-- </van-sticky> -->
	<!-- </div> -->
	<van-row justify="center" class="cont">
		<van-col span="4"></van-col>
		<van-col span="16" class="cont-circle">
      <van-circle
        v-if="times < 3"
        @click="answerable ? goToQuiz() : showCompleteMessage()"
        v-model:current-rate="currentRate"
        :rate="rate"
        :speed="speed"
        :text="text"
        :color="gradientColor"
        layer-color="#ebedf0"
        size="120px"
      />
      <div v-else class="limit-message">今日答题次数已达上限，明天再来吧</div>

    </van-col>
		<van-col span="4"></van-col>
	</van-row>
	<!-- 底部按钮 -->
	<div class="footer">
		<div class="buttons">
			<van-button type="primary" class="custom-button" size="large" @click="goJieguo">
				考试结果
			</van-button>
			<van-button class="custom-button" size="large" @click="goPaiming">
				公司总排名
			</van-button>
		</div>
	</div>
</template>

<script setup>
	import {
		onMounted,
		ref,
		computed,
		getCurrentInstance
	} from "vue";
	import {
		showConfirmDialog,
		showSuccessToast,
		showFailToast,
		showDialog
	} from 'vant';

	import {
		useRouter
	} from "vue-router";
	const {
		proxy
	} = getCurrentInstance()
	const router = useRouter();
	const times = ref(0);
	const totaltimes = ref(0);
	const score = ref(0);
	const total = ref(0);
	const overlayloading = ref(false);
	const currentRate = ref(0);
	const rate = ref(0);
	const answerable = ref(false);

	var userId = localStorage.getItem('userId')
	console.log('index的userId：' + userId)
	if (userId == '1' || userId == '' || userId == 'undefined') userId = '267633C4380511B2B37DE5E6DC503AC7'
	const today = new Date();
	const year = today.getFullYear();
	const month = String(today.getMonth() + 1).padStart(2, '0');
	const day = String(today.getDate()).padStart(2, '0');
	const todayStr = `${year}-${month}-${day}`;

	const speed = ref(100);
	const text = "开始答题";
	const gradientColor = {
		"0%": "#3fecff",
		"100%": "#6149f6",
	};
  const   showCompleteMessage
    = () => {
    showDialog({
      message: '本日答题次数已用完',
    })
  }
	const courseId = ref(0);
  const queryOneInTimeNoPageH5 =async () => {

    var url = '/sgsafe/ExamHead/queryOneInTimeNoPageH5'
    var param = {}
    const res = await proxy.$axios.post(url, param);

    return res.data.data
  }
	const goToQuiz = async () => {
    //-----
    //如果status为新建那么查出这条数据
		//先生成试卷

   const res1 = await queryOneInTimeNoPageH5()

    if (res1!=null){
      console.log(res1);
      courseId.value = res1.headId;
    }else {
      var url = '/sgsafe/Package/doProc'
      var param = {
        procName: 'safeplat.sxsp_create_exam_p',
        param: JSON.stringify(['', userId, 'Y'])
      }
      const res = await proxy.$axios.post(url, param);
      if (res.data.code === 0) {
        courseId.value = res.data.data;
      } else {
        console.log('操作失败!' + res.data.msg);
      }
    }

		//再跳转答题页
		router.push({
			path: "/datistart",
			query: {
				courseId: courseId.value,
				userId: userId,
				todayStr: todayStr,
			},
		});
	};

	//////////////////////////////////////////////////////////我的答题分数
	const tableData = ref([]);
	const getMyDefaultCourse = async () => {
		try {
			overlayloading.value = true;
			var url = '/sgsafe/DailyExam/appQueryMyScore'
			const query = ref({
				userId: userId,
				examDate: todayStr,
			})
			var param = {
				params: JSON.stringify(query.value)
			}
			try {
				const res = await proxy.$axios.post(url, param);
				console.log('index的query', query)
				if (res.data.code === 0) {
					console.log(res.data.data.dailyExamList)
					tableData.value = res.data.data.dailyExamList.length > 0 ?
						res.data.data.dailyExamList : [{
							examCounts: '0',
							totalScore: '0'
						}];
				} else {
					console.log('操作失败!' + res.data.msg);
				}
			} catch (error) {
				console.log('请求出错:', tableData);
			}
			const data = tableData.value[0] || {
				examCounts: '0',
				totalScore: '0'
			};
			//不管是否做完3次，都显示当日答题结果
			totaltimes.value = data.examCounts; //今日次数
			score.value = data.totalScore; // 今日得分
			total.value = data.totalScore; // 总分
			const counts = parseInt(data.examCounts) || 0;
			currentRate.value = (counts * 100) / 3;
			rate.value = (counts * 100) / 3;

			if (data.examCounts == '3') {
				answerable.value = false;

			} else {
				answerable.value = true;
			}
			overlayloading.value = false;
		} catch (error) {
			console.error("出错：", error);
			overlayloading.value = false;
			alert("获取失败，请稍后重试");
		}
	};

	const goJieguo = () => {
		router.push({
			path: "/jieguo",
			query: {
				userId: userId
			},
		});
	};

	const goPaiming = () => {
		router.push({
			path: "/paiming",
			query: {
				userId: userId
			},
		});
	};

	// 如果为无权限用户，进入unauth界面
	// 已登录且无toPath，进入首页
	// 已登录，有需要跳转的详情，进入详情页

	onMounted(() => {
		getMyDefaultCourse();
	});
</script>

<style scoped>
	.descStyle {
		font-size: 12px;
		color: #323232;
	}

	.numStyle {
		font-size: 20px;
		font-weight: bold;
		color: #007aff;
	}

	.cont {
		margin-top: 100px;
	}

	.cont-circle {
		display: flex;
		justify-content: center;
	}

	.limit-message {
		color: #ff0000;
		font-size: 15px;
		text-align: left;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		/* padding: 0 8px; */
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: white;
		padding-bottom: 10px;
	}

	.buttons {
		display: flex;
		flex-direction: row;
		width: 95%;
		justify-content: space-between;
		/* 使按钮在水平方向上两端对齐 */
		align-items: center;
		/* 垂直居中对齐 */
	}

	.custom-button {
		font-size: 14px;
		/* 设置按钮字体大小为14px */
	}

	.buttons .van-button {
		flex: 1;
		/* 使按钮可以收缩或扩展以填充可用空间 */
		margin: 0 10px;
		/* 按钮之间的间距 */
		width: auto;
		/* 让按钮宽度自适应内容 */
		/* max-width: 140px; 设置按钮的最大宽度 */
		height: 38px;
	}

	/* 遮罩 */
	.wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.van-overlay {
		z-index: 2;
		background-color: rgba(0, 0, 0, 0.5);
	}
</style>