<template>
  <div class="grid full check-exam-view">
    <div class="check-exam-modal">
      <div class="p-l-large modal-header">请选择考试</div>
      <div class="login-modal-content">
        <base-select
          v-if="examList.length"
          v-model="examId"
          class="full-w"
          :options="examList"
          placeholder="选择考试批次"
          size="large"
        ></base-select>
        <div :class="{ 'm-t-super-large': !isCreate }">
          <confirm-button
            :loading="loading"
            :ok-text="isCreate ? '创建考试' : '确定'"
            cancel-text="退出"
            @confirm="joinOrCreateExam(isCreate)"
            @cancel="logout()"
          ></confirm-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="CheckExam">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { logout } from '@/utils/shared'
import { sessionStorage } from '@/plugins/storage'
import useFetch from '@/hooks/useFetch'
import useMainStore from '@/store/main'
import BaseSelect from '@/components/element/BaseSelect.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'

const { push, replace } = useRouter()
const mainStore = useMainStore()

const examId = ref<number>()

const { result, loading, fetch } = useFetch('getExamList')
// const { fetch: checkExam, loading: checkLoading } = useFetch('checkExam')

const examList = computed(() => {
  return result.value?.result?.map((exam) => ({ ...exam, value: exam.id, label: exam.name })) || []
})

const isCreate = computed(() => {
  return !loading.value && !examList?.value?.length
})

fetch({ pageNumber: 1, pageSize: 9999, enable: true }).then((result) => {
  if (result?.result?.length && !examId.value) {
    examId.value = result.result[0].id
  }
})

async function joinOrCreateExam(isCreate: boolean) {
  if (loading.value) {
    return
  }
  if (isCreate) {
    push({ name: 'InitCreateExam' })
  } else {
    if (examId.value) {
      // await checkExam({ examId: examId.value })
      sessionStorage.set('EXAM_ID', examId.value)
    } else {
      ElMessage.error(`请选择一个考试批次`)
    }
    mainStore.getMyUserInfo()
    replace({ name: 'UserManage' })
  }
}
</script>

<style scoped lang="scss">
.check-exam-view {
  place-items: center;
  .check-exam-modal {
    width: 640px;
    background: $LoginModalBg;
    border-radius: $LoginModalRadius;
    overflow: hidden;
    .modal-header {
      height: $LoginModalHeaderHeight;
      line-height: $LoginModalHeaderHeight;
      background: $LoginModalHeaderBg;
      font-size: $LoginModalHeaderFontSize;
      font-weight: normal;
      color: $LoginModalHeaderFontColor;
    }
    .login-modal-content {
      padding: 52px 80px;
    }
    :deep(button.el-button) {
      width: 120px;
      height: 48px;
    }
  }
}
</style>
