feat:1. 调整项目结构,将API接口定义单独抽离 2. 将倒计时计算逻辑调整到后端进行处理计算 3. 增加铃声提示功能

This commit is contained in:
2025-07-26 12:53:33 +08:00
parent 07bf872149
commit 4faf2db730
6 changed files with 206 additions and 135 deletions
+81 -131
View File
@@ -1,38 +1,50 @@
<!-- src/views/StudyTimer.vue -->
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import {ElButton, ElMessage, ElMessageBox, ElProgress} from 'element-plus';
import { useRoute } from "vue-router";
import request from "@/utils/request";
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useTimer } from '@/components/composables/useTimer';
import { continueSession, pauseSession, endSession, startOrContinueStudySession } from '@/api/studySessions';
const route = useRoute();
const taskNum = route.params.taskNum;
const taskNum = route.params.taskNum as string;
const taskInfo = ref({
sessionNum: '',
sessionState: '--',
taskName: '',
taskNum: taskNum,
taskNum,
startTime: '',
endTime: '',
lastStartTime: '',
actualTime: 0,
effectiveTime: 0,
effectivenessRatio: '--',
pointerPosition: 0,
systemMessage: '',
});
const timerMinutes = ref(25);
const timerSeconds = ref(0);
const timerRunning = ref(false);
let timerInterval: number;
let timer : number;
const {
timerMinutes,
timerSeconds,
runCountdown,
clear,
timerRunning,
timerIsOver,
checkAudioPermission,
requestAudioPermission
} = useTimer();
const currentCycle = computed(() => Math.floor(taskInfo.value.effectiveTime/60 / 25) + 1);
const currentTime = ref(Date.now());
const globalTimer = ref(Date.now());
const currentCycle = computed(() =>
Math.floor(taskInfo.value.effectiveTime / 60 / 25) + 1
);
const elapsedTime = computed(() => {
if (!taskInfo.value.startTime) return { hours: 0, minutes: 0, seconds: 0 };
if (!taskInfo.value.startTime || !timerRunning.value) return { hours: 0, minutes: 0, seconds: 0 };
const start = new Date(taskInfo.value.startTime).getTime();
const now = currentTime.value;
const now = globalTimer.value;
const diff = Math.max(Math.floor((now - start) / 1000), 0);
return {
hours: Math.floor(diff / 3600),
@@ -41,134 +53,73 @@ const elapsedTime = computed(() => {
};
});
const formatTime = (time: { hours: number; minutes: number; seconds: number }) => {
return `${time.hours}${time.minutes}${time.seconds}`;
};
const formatTime = (t: { hours: number; minutes: number; seconds: number }) =>
`${t.hours}${t.minutes}${t.seconds}`;
const progress = computed(() => ((timerMinutes.value * 60 + timerSeconds.value) / (25 * 60)) * 100);
const audio = new Audio('/resource/notification.mp3');
const progress = computed(() =>
((timerMinutes.value * 60 + timerSeconds.value) / (25 * 60)) * 100
);
const startTimer = async () => {
if ("PAUSED" === taskInfo.value.sessionState) {
await request.post(`/study-sessions/${taskInfo.value.sessionNum}/study-sessions/continue`, null, {params: null}).then(req => {
if (req.code === 200) {
ElMessage.success('任务开始');
}
});
if (taskInfo.value.sessionState === "PAUSED") {
const res = await continueSession(taskInfo.value.sessionNum);
if (res.code === 200) ElMessage.success('任务继续');
await loadTaskSession();
}
timerRunning.value = true;
timerInterval = window.setInterval(() => {
if (timerRunning.value) {
if (timerSeconds.value === 0) {
if (timerMinutes.value === 0) {
endTimer();
// 弹窗 + 播放铃声
audio.loop = true; // 循环播放,避免弹窗没关闭铃声自动停
audio.play();
ElMessageBox.alert('本次番茄钟结束!', '提醒', {
confirmButtonText: '关闭铃声',
callback: () => {
audio.pause();
audio.currentTime = 0; // 重置音频进度
ElMessage.success('铃声已关闭');
}
});
} else {
timerMinutes.value--;
timerSeconds.value = 59;
}
} else {
timerSeconds.value--;
}
}else {
clearInterval(timerInterval);
}
}, 1000);
const duration = taskInfo.value.pointerPosition || 25 * 60 * 1000;
runCountdown(duration);
};
const stopTimer = async () => {
await request.post(`/study-sessions/${taskInfo.value.sessionNum}/study-sessions/pause`, null, {params:null}).then(req =>{
if (req.code === 200) {
ElMessage.success('任务暂停');
}
});
timerRunning.value = false;
const res = await pauseSession(taskInfo.value.sessionNum);
if (res.code === 200) ElMessage.success('任务暂停');
clear();
};
const endTimer = async () => {
await request.post(`/study-sessions/${taskInfo.value.sessionNum}/study-sessions/ended`, {content:"测试关闭"}, {params:null}).then(req =>{
if (req.code === 200) {
ElMessage.success('任务结束');
}
});
clearInterval(timerInterval);
timerRunning.value = false;
const res = await endSession(taskInfo.value.sessionNum, "用户手动结束");
if (res.code === 200) ElMessage.success('任务结束');
clear();
};
const handleTimerException = async (adjustedEnd: Date) => {
await request.post(`/study-sessions/${taskInfo.value.sessionNum}/study-sessions/pause`, null, {
params: {
endTime: adjustedEnd.toISOString(),
}
});
ElMessage.warning('上次学习任务开始时间过长,未及时结束,有效时间仅增加25分钟');
// 重新加载数据
startOrContinueStudySession()
const restTimer = async () => {
await stopTimer();
runCountdown(5 * 60 * 1000);
};
const initClocker = async () => {
const end = new Date(taskInfo.value.endTime).getTime();
const lastStart = new Date(taskInfo.value.lastStartTime).getTime();
const now = new Date().getTime();
let diff = Math.floor((now - lastStart) / 1000);
// 判断任务是否超时(状态为正在进行,且最后一次开始时间到现在超过25分钟)
console.log(new Date().toISOString())
if (taskInfo.value.sessionState === 'ONGOING' && now - lastStart > 25 * 60 * 1000) {
// 超时了,触发暂停
const adjustedEnd = new Date(lastStart + 25 * 60000);
await handleTimerException(adjustedEnd);
// 准备开始下一次倒计时
timerMinutes.value = 25;
timerSeconds.value = 0;
} else if (taskInfo.value.sessionState === 'ONGOING' ) {
// 没超时,恢复进度
timerMinutes.value = 25 - Math.floor(diff / 60);
timerSeconds.value = 60 - diff % 60;
startTimer();
} else {
// 准备开始下一次倒计时
timerMinutes.value = 25;
timerSeconds.value = 0;
const loadTaskSession = async () => {
try {
const res = await startOrContinueStudySession(taskNum);
Object.assign(taskInfo.value, res.data);
if (taskInfo.value.sessionState === 'ONGOING') {
startTimer();
}
if (taskInfo.value.systemMessage) {
ElMessage.warning(taskInfo.value.systemMessage);
}
} catch (err: any) {
ElMessage.error(err.message || '加载任务失败');
}
};
const startOrContinueStudySession = () => {
request.get(`/tasks/${taskNum}/study-sessions/start-or-continue`, {})
.then(res => {
Object.assign(taskInfo.value, res.data);
initClocker();
})
.catch(err => {
ElMessage.error(err.message);
});
const initPage = async () => {
const hasPermission = await checkAudioPermission();
if (!hasPermission) {
const activated = await requestAudioPermission();
if (!activated) {
console.warn('用户拒绝或未能激活权限');
return;
}
}
await loadTaskSession();
setInterval(() => {
globalTimer.value = Date.now();
}, 1000);
};
onMounted(() => {
startOrContinueStudySession();
timer = setInterval(() => {
currentTime.value = Date.now();
}, 1000);
});
onUnmounted(() => {
clearInterval(timerInterval)
clearInterval(timer);
initPage();
});
</script>
@@ -180,17 +131,19 @@ onUnmounted(() => {
<p>有效时间{{ taskInfo.effectiveTime / 60 }}分钟</p>
<p>本次运行时间{{ formatTime(elapsedTime) }}</p>
</div>
<div class="timer-section">
<el-progress type="circle" :percentage="progress" :width="200">
<div>{{ timerMinutes.toString().padStart(2, '0') }} : {{ timerSeconds.toString().padStart(2, '0') }}</div>
<div>
{{ timerMinutes.toString().padStart(2, '0') }} :
{{ timerSeconds.toString().padStart(2, '0') }}
</div>
</el-progress>
</div>
<div class="actions">
<el-button @click="startTimer" :disabled="timerRunning">开始</el-button>
<el-button @click="stopTimer" :disabled = "!timerRunning">暂停</el-button>
<el-button @click="endTimer" >结束</el-button>
<el-button @click="stopTimer" :disabled="!timerRunning" v-if="!timerIsOver">暂停</el-button>
<el-button @click="restTimer" v-if="timerIsOver">休息</el-button>
<el-button @click="endTimer">结束</el-button>
</div>
</div>
</template>
@@ -203,16 +156,13 @@ onUnmounted(() => {
justify-content: center;
margin: 20px;
}
.task-info {
font-size: 18px;
margin-bottom: 30px;
}
.timer-section {
margin: 20px;
}
.actions {
display: flex;
gap: 10px;