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

// @ts-ignore
import { Page } from '@vben/common-ui';
// @ts-ignore
import { useAccessStore } from '@vben/stores';

import { ElForm, ElMessage, ElMessageBox } from 'element-plus';

// @ts-ignore
import { examDetail } from '#/api/exam/exam/exam';
// @ts-ignore
import { startExam } from '#/api/exam/exam/participant';
// @ts-ignore
import { useAuthStore } from '#/store';

const accessStore = useAccessStore();

const authStore = useAuthStore();

const route = useRoute();
const router = useRouter();

const token = ref(accessStore.accessToken);
// if (userinfo) {
//   token.value = JSON.parse(userinfo).accessToken || '';
// }

onMounted(async () => {
  const res: any = await examDetail(+(route.params.id || '0'));
  examInfo.value = res;
});

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

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

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

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

  // 增加一个二次确认提醒，提醒开始之后必须完成
  ElMessageBox.confirm(
    '考试过程中不可以退出，完成之后需要点击提交试卷按钮',
    '考试提醒',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(async () => {
    try {
      const res: any = await startExam(+(route.params.id || '0'));
      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,
          },
        });
      } else {
        router.replace({
          name: 'StartExamin',
          params: {
            id: route.params.id,
          },
          query: {
            pid: res.id,
          },
        });
      }
    } catch (error) {
      ElMessage.error(`操作失败${error}`);
    }
  });
};

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

    try {
      await authStore.authExamLogin(loginUser.value, () => {
        token.value = accessStore.accessToken || '';
        startExamEvent();
      });
    } catch (error) {
      ElMessage.error(`操作失败${error}`);
    }
  }
};

const loginUser = ref({
  username: '',
  password: '',
});
</script>
<template>
  <Page
    style="height: 100%"
    title="考试信息"
    :auto-content-height="true"
    class="h-screen"
  >
    <div class="w-full rounded-md bg-white p-4">
      <div
        class="mb-[48px] mt-[87px] text-center text-[22px] font-semibold text-gray-800"
      >
        欢迎进入联合汇能考试中心
      </div>
      <ElDescriptions class="task-info" :column="1" border :label-width="240">
        <ElDescriptionsItem label="考试名称">
          {{ examInfo.examName }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="考试总分">
          {{ examInfo.totalScore }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="及格分数">
          {{ examInfo.passScore }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="考试时长">
          {{ examInfo.examDuration || 0 }} 分钟
        </ElDescriptionsItem>
        <ElDescriptionsItem label="考试说明">
          {{ examInfo.examDescription }}
        </ElDescriptionsItem>
      </ElDescriptions>
      <!-- 分割线-->
      <div class="mt-[48px] border-t border-gray-200" v-if="!token"></div>
      <!-- 输入姓名和手机号-->
      <div class="mt-[48px] flex justify-center" v-if="!token">
        <ElForm style="width: 400px" label-position="right" label-width="80px">
          <ElFormItem label="姓名" prop="username">
            <ElInput v-model="loginUser.password" autocomplete="off" />
          </ElFormItem>
          <ElFormItem label="手机号" prop="phone">
            <ElInput v-model="loginUser.username" autocomplete="off" />
          </ElFormItem>
        </ElForm>
      </div>
      <!-- 开始考试按钮-->
      <div class="mt-[48px] flex justify-center">
        <el-button
          type="primary"
          size="large"
          style="width: 160px"
          @click="start"
        >
          开始考试
        </el-button>
      </div>
    </div>
  </Page>
</template>
<style lang="scss" scoped></style>
