<!-- src/views/StudyTimer.vue -->
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import { useTimer } from '@/components/composables/useTimer';
import { continueSession, pauseSession, endSession, startOrContinueStudySession } from '@/api/studySessions';
import { useStudyFragment } from '@/components/composables/fragment';
import {routes} from "vue-router/auto-routes";
import router from "@/router";

const {
  fragmentsDialogVisible,
  fragmentContent,
  openFragmentDialog,
  closeFragmentDialog,
  confirmGenerateFragment
} = useStudyFragment();

const summaryDialogVisible = ref(false);
const summaryContent = ref('');

const route = useRoute();
const taskNum = route.params.taskNum as string;

const taskInfo = ref({
  sessionNum: '',
  sessionState: '--',
  taskName: '',
  taskNum,
  startTime: '',
  endTime: '',
  lastStartTime: '',
  actualTime: 0,
  effectiveTime: 0,
  effectivenessRatio: '--',
  pointerPosition: 0,
  systemMessage: '',
});

const {
  timerMinutes,
  timerSeconds,
  runCountdown,
  clear,
  timerRunning,
  timerIsOver,
  checkAudioPermission,
  requestAudioPermission
} = useTimer();

const globalTimer = ref(Date.now());

const currentCycle = computed(() =>
    Math.floor(taskInfo.value.effectiveTime / 60 / 25) + 1
);

const elapsedTime = computed(() => {
  if (!taskInfo.value.startTime || !timerRunning.value) return { hours: 0, minutes: 0, seconds: 0 };
  const start = new Date(taskInfo.value.startTime).getTime();
  const now = globalTimer.value;
  const diff = Math.max(Math.floor((now - start) / 1000), 0);
  return {
    hours: Math.floor(diff / 3600),
    minutes: Math.floor((diff % 3600) / 60),
    seconds: diff % 60,
  };
});

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 startTimer = async () => {
  if (taskInfo.value.sessionState === "PAUSED") {
    const res = await continueSession(taskInfo.value.sessionNum);
    if (res.code === 200) ElMessage.success('任务继续');
    await loadTaskSession();
  }
  const duration = taskInfo.value.pointerPosition || 25 * 60 * 1000;
  runCountdown(duration);
};

const stopTimer = async () => {
  const res = await pauseSession(taskInfo.value.sessionNum);
  if (res.code === 200) ElMessage.success('任务暂停');
  clear();
};

const endTimer = async (content: string) => {
  if (!content) {
    ElMessage.warning('请输入学习总结内容');
    return;
  }
  ElMessageBox.confirm('确定要结束吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  }).then(async () => {
    const res = await endSession(taskInfo.value.sessionNum, content);
    if (res.code === 200) ElMessage.success('任务结束');
    router.back();
    clear();
  })
};

const openSummaryDialog = async () => {
  summaryDialogVisible.value = true;
}

const closeSummaryDialog = async () => {
  ElMessageBox.alert('确定取消吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    summaryDialogVisible.value = false;
    ElMessage.info('已取消结束操作')
  })
}

const restTimer = async () => {
  await stopTimer();
  runCountdown(5 * 60 * 1000);
};

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 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(() => {
  initPage();
});
</script>

<template>
  <div class="task-container">
    <div class="task-info">
      <p>当前任务【{{ taskInfo.taskName }}】</p>
      <p>当前循环：{{ currentCycle }}</p>
      <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>
      </el-progress>
    </div>
    <div class="actions">
      <el-button @click="startTimer" :disabled="timerRunning">开始</el-button>
      <el-button @click="stopTimer" :disabled="!timerRunning" v-if="!timerIsOver">暂停</el-button>
      <el-button @click="openFragmentDialog" :disabled="!timerRunning">生成学习残片</el-button>
      <el-button @click="restTimer" v-if="timerIsOver">休息</el-button>
      <el-button @click="openSummaryDialog">结束</el-button>
    </div>
  </div>
  <el-dialog v-model="fragmentsDialogVisible" title="生成学习残片" width="500px">
    <el-input
        type="textarea"
        v-model="fragmentContent"
        placeholder="请输入本次学习的内容"
        rows="5"
    />
    <template #footer>
    <span>
      <el-button @click="closeFragmentDialog">取消生成</el-button>
      <el-button type="primary" @click="confirmGenerateFragment(taskInfo.sessionNum)">确定生成</el-button>
    </span>
    </template>
  </el-dialog>
  <el-dialog v-model="summaryDialogVisible" title="本次学习内容总结" width="500px">
    <el-input
        type="textarea"
        v-model="summaryContent"
        placeholder="请输入本次学习的内容总结"
        rows="5"
    />
    <template #footer>
    <span>
      <el-button @click="closeSummaryDialog">取消</el-button>
      <el-button type="primary" @click="endTimer(summaryContent)">确定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.task-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 20px;
}
.task-info {
  font-size: 18px;
  margin-bottom: 30px;
}
.timer-section {
  margin: 20px;
}
.actions {
  display: flex;
  gap: 10px;
}
</style>
