<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { useMessage, useToast } from 'wot-design-uni'

import { examDetail } from '@/api/exam'
import { startExam } from '@/api/exam/participant'

import { useAuthStore } from '@/store/auth'
import { useTokenStore } from '@/store/token'

const tokenStore: any = useTokenStore()
const toast = useToast()
const wotMessage = useMessage()
const authStore = useAuthStore()

const route = useRoute()
// const id = ref(Number(route.query.id))
const examId = ref(Number(route.query.id || '0'))
console.log(tokenStore.tokenInfo, 'tokenStore.tokenInfo')
const token = ref(tokenStore.tokenInfo?.token || '')

const examInfo: any = ref({
  examName: '',
  totalScore: 100,
  passScore: 60,
  examDuration: '30分钟',
  examDescription: '',
})

const loginUser: any = ref({
  username: '',
  password: '',
})

onMounted(async () => {
  const res: any = await examDetail(examId.value)
  if (res.code === 200) {
    examInfo.value = res.data || {}
  }
})

function startExamEvent() {
  // 判断开始是否在进行中
  if (examInfo.value.examStatus !== 'ongoing') {
    toast.error('当前考试状态不是进行中，不能开始考试')
    return
  }

  if (
    examInfo.value.examStartTime
    && new Date(examInfo.value.examStartTime).getTime() > Date.now()
  ) {
    toast.error('考试还未开始')
    return
  }

  if (
    examInfo.value.examEndTime
    && new Date(examInfo.value.examEndTime).getTime() < Date.now()
  ) {
    toast.error('考试已结束')
    return
  }

  // 增加一个二次确认提醒，提醒开始之后必须完成
  wotMessage.confirm({
    msg: `考试过程中不可以退出，完成之后需要点击提交试卷按钮`,
    title: '考试提醒',
  }).then(async () => {
    try {
      const res: any = await startExam(+(examId.value || '0'))
      if (res.code !== 200) {
        toast.error(`操作失败${res.msg}`)
        return
      }
      const userType = res?.userType || ''
      localStorage.setItem('exam:usertype', userType)
      if (userType === 'exam') {
        // router.replace({
        //   name: 'Startexamin',
        //   params: {
        //     id: route.params.id,
        //   },
        //   query: {
        //     pid: res.id,
        //   },
        // })
        uni.navigateTo({
          url: `/pages/knowledge/exam/answer?id=${examId.value}&pid=${res?.id}`,
        })
      }
      else {
        uni.navigateTo({
          url: `/pages/knowledge/exam/answer?id=${examId.value}&pid=${res?.id}`,
        })
        // router.replace({
        //   name: 'StartExamin',
        //   params: {
        //     id: route.params.id,
        //   },
        //   query: {
        //     pid: res.id,
        //   },
        // })
      }
    }
    catch (error) {
      toast.error(`操作失败${error}`)
    }
  })
}

async function start() {
  if (token.value) {
    startExamEvent()
  }
  else {
    if (!loginUser.value.username && !loginUser.value.password) {
      toast.error('请输入姓名或手机号')
      return
    }

    try {
      await authStore.authExamLogin(loginUser.value)

      token.value = tokenStore.tokenInfo?.token || ''
      startExamEvent()
    }
    catch (error) {
      toast.error(`操作失败${error}`)
    }
  }
}
</script>

<template>
  <view class="knowledgebase_exam_explanation">
    <view class="knowledgebase_exam_explanation_title">
      {{ examInfo.examName }}
    </view>
    <view class="knowledgebase_exam_explanation_content">
      <view class="knowledgebase_exam_explanation_content_title">
        考试说明
      </view>
      <view class="knowledgebase_exam_explanation_content_text">
        {{ examInfo.examDescription }}
      </view>
    </view>
    <view class="knowledgebase_exam_explanation_float">
      <view class="knowledgebase_exam_explanation_float_title">
        考试总分
        <span class="knowledgebase_exam_explanation_float_title_score">
          {{ examInfo.totalScore }}分
        </span>
      </view>
      <view class="knowledgebase_exam_explanation_float_title">
        及格分数
        <span class="knowledgebase_exam_explanation_float_title_score">
          {{ examInfo.passScore }}分
        </span>
      </view>
      <view class="knowledgebase_exam_explanation_float_title">
        考试时长
        <span class="knowledgebase_exam_explanation_float_title_score">
          {{ examInfo.examDuration }} 分钟
        </span>
      </view>
    </view>
    <view v-if="!token" class="knowledgebase_exam_explanation_form">
      <view class="knowledgebase_exam_explanation_form_item">
        <view class="knowledgebase_exam_explanation_form_item_label">
          姓名
        </view>
        <input
          v-model="loginUser.password"
          type="text"
          class="knowledgebase_exam_explanation_form_item_input"
          placeholder="请输入姓名"
        >
      </view>
      <view class="knowledgebase_exam_explanation_form_item">
        <view class="knowledgebase_exam_explanation_form_item_label">
          手机号
        </view>
        <input
          v-model="loginUser.username"
          type="number"
          class="knowledgebase_exam_explanation_form_item_input"
          placeholder="请输入手机号"
        >
      </view>
    </view>
    <wd-button class="knowledgebase_exam_explanation_float_button" @click="start">
      开始考试
    </wd-button>
    <!-- <wd-button disabled class="knowledgebase_exam_explanation_float_button"
      >考试将于2026-2-1 19:00开始</wd-button
    > -->
    <wd-toast />
    <wd-message-box />
  </view>
</template>

<style scoped lang="scss">
html,
body {
  overflow: hidden;
}
.knowledgebase_exam_explanation {
  height: calc(100vh - 88rpx);
  display: flex;
  flex-direction: column;
  // justify-content: space-between;
  padding: 24rpx;
  box-sizing: border-box;
}
.knowledgebase_exam_explanation_title {
  font-family: Alibaba PuHuiTi 2;
  font-weight: 500;
  font-style: 65 Medium;
  font-size: 48rpx;
  leading-trim: NONE;
  line-height: 48rpx;
  letter-spacing: 0px;
  color: #31373d;
}
.knowledgebase_exam_explanation_content {
  margin-top: 80rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  .knowledgebase_exam_explanation_content_title {
    font-weight: 500;
    font-style: 65 Medium;
    font-size: 36rpx;
    leading-trim: NONE;
    letter-spacing: 0px;
    color: #31373d;
  }
  .knowledgebase_exam_explanation_content_text {
    font-weight: 400;
    font-style: 55 Regular;
    font-size: 28rpx;
    line-height: 48rpx;
    letter-spacing: 0px;
    color: #4e5969;
  }
}
.knowledgebase_exam_explanation_float {
  margin-top: 48rpx;
  border-top: 1rpx solid #eeeeee;
  padding-top: 48rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  .knowledgebase_exam_explanation_float_title {
    font-weight: 400;
    font-style: 55 Regular;
    font-size: 28rpx;
    letter-spacing: 0px;
    color: #4e5969;
    .knowledgebase_exam_explanation_float_title_score {
      margin-left: 48rpx;
      color: #31373d;
    }
  }
}
.knowledgebase_exam_explanation_float_button {
  margin-top: auto;
  width: 100%;
  background-color: #215acd !important;
  height: 80rpx !important;
  border-radius: 8rpx !important;
}

.knowledgebase_exam_explanation_form {
  margin-top: 48rpx;
  border-top: 1rpx solid #eeeeee;
  padding-top: 48rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.knowledgebase_exam_explanation_form_item {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.knowledgebase_exam_explanation_form_item_label {
  font-weight: 400;
  font-style: 55 Regular;
  font-size: 28rpx;
  letter-spacing: 0px;
  color: #4e5969;
}

.knowledgebase_exam_explanation_form_item_input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  padding: 0 24rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  color: #31373d;
  background-color: #ffffff;
}

.knowledgebase_exam_explanation_form_item_input::placeholder {
  color: #c0c4cc;
}
</style>
