<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { myEndExamList, myPendingExamList } from '@/api/exam'

const examList = ref([
  {
    id: 1,
    status: '待考试',
  },
  {
    id: 2,
    status: '已考试',
  },
])
const activeId = ref(1)
const waitingForTheExam = ref([])
const endExamList = ref([])

// 滚动加载状态管理
const isLoading = ref(false)
const pendingTotal = ref(0)
const endTotal = ref(0)

const examStatusColorMap: any = {
  pending: {
    text: '待考试',
    color: '#215ACD',
  },
  ongoing: {
    text: '进行中',
    color: '#EB5E12',
  },
  absent: {
    text: '缺考',
    color: '#A4AAB2',
  },
}

function getStatus(row: any) {
  let status = ''
  if (new Date(row.examStartTime) > new Date()) {
    status = 'pending'
  }
  else if (new Date(row.examEndTime) > new Date()) {
    status = 'ongoing'
  }
  else {
    status = 'absent'
  }
  return status
}

// const reviewStatusOptions = [
//   { label: '待批改', value: 'unreviewed', color: '#EB5E12' },
//   { label: '批改中', value: 'reviewing', color: '#FFC107' },
//   { label: '已批改', value: 'reviewed', color: '#38B865' },
// ]

const endStatusColorMap = {
  0: {
    text: '已出分',
    color: '#38B865',
  },
  1: {
    text: '待出分',
    color: '#215ACD',
  },
}

function getEndStatus(row: any) {
  if (row.reviewStatus === 'unreviewed') {
    return endStatusColorMap[1]
  }
  return endStatusColorMap[0]
}

function toExamDetail(data) {
  if (data.Status === '未开始') {
    uni.navigateTo({
      url: '/pages/knowledge/exam/explanation/index',
    })
  }
  else if (data.Status === '进行中') {
    uni.navigateTo({
      url: '/pages/knowledge/exam/examcontent/index',
    })
  }
}
function ExamtakenDetail(data) {
  if (data.Status === '待出分') {
    uni.navigateTo({
      url: '/pages/knowledge/exam/examresults/scoresnotreleased',
    })
  }
  else if (data.Status === '已出分') {
    uni.navigateTo({
      url: '/pages/knowledge/exam/examresults/index',
    })
  }
}

const page = ref({
  currentPage: 1,
  pageSize: 10,
})

async function getExamList(loadMore = false) {
  try {
    isLoading.value = true
    if (activeId.value === 1) {
      const res: any = await myPendingExamList({
        pageNum: page.value.currentPage,
        pageSize: page.value.pageSize,
      })
      if (res.code === 200) {
        if (loadMore) {
          waitingForTheExam.value = [...waitingForTheExam.value, ...(res?.rows || [])]
        }
        else {
          waitingForTheExam.value = res?.rows
        }
        pendingTotal.value = res?.total
      }
    }
    else if (activeId.value === 2) {
      const res: any = await myEndExamList({
        pageNum: page.value.currentPage,
        pageSize: page.value.pageSize,
      })
      if (res.code === 200) {
        if (loadMore) {
          endExamList.value = [...endExamList.value, ...(res?.rows || [])]
        }
        else {
          endExamList.value = res?.rows
        }
        endTotal.value = res?.total
      }
    }
  }
  catch (err) {
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    })
  }
  finally {
    isLoading.value = false
  }
}

function changeTab(id) {
  if (id === activeId.value) {
    return
  }
  activeId.value = id
  page.value.currentPage = 1
  getExamList()
}

// 滚动加载更多
async function handleLoadMore() {
  if (isLoading.value)
    return

  const currentList = activeId.value === 1 ? waitingForTheExam.value : endExamList.value
  const currentTotal = activeId.value === 1 ? pendingTotal.value : endTotal.value

  if (currentList.length >= currentTotal) {
    uni.showToast({
      title: '没有更多数据了',
      icon: 'none',
    })
    return
  }

  page.value.currentPage++
  await getExamList(true)
}

function goDetail(item) {
  if (activeId.value === 1) {
    uni.navigateTo({
      url: `/pages/knowledge/exam/start?id=${item.id}`,
    })
  }
  else {
    if (item.reviewStatus === 'unreviewed') {
      uni.navigateTo({
        url: `/pages/knowledge/exam/correct?id=${item.id}&pid=${item.participantId}`,
      })
    }
    else {
      uni.navigateTo({
        url: `/pages/knowledge/exam/result?id=${item.id}&pid=${item.participantId}`,
      })
    }
  }
}

onMounted(async () => {
  await getExamList()
})
</script>

<template>
  <view class="knowledgebase_exam">
    <view class="header_nav">
      <view
        v-for="(item, index) in examList"
        :key="index"
        class="header_nav_item" :class="[{ active: item.id === activeId }]"
        @click="changeTab(item.id)"
      >
        {{ item.status }}
        <view v-if="item.id === activeId" class="active_line" />
      </view>
    </view>
    <scroll-view
      class="content"
      :scroll-y="true"
      @scrolltolower="handleLoadMore"
    >
      <view v-if="activeId === 1">
        <view
          v-for="(item, index) in waitingForTheExam"
          :key="index"
          class="content_item"
          @click="goDetail(item)"
        >
          <view class="content_item_title">
            <span class="content_item_title_name">{{ item.examName || '' }}</span>
            <span
              class="content_item_title_status"
              :style="{ 'background-color': examStatusColorMap[getStatus(item)].color }"
            >{{ examStatusColorMap[getStatus(item)].text }}</span>
          </view>
          <view class="content_item_time">
            {{ item.examStartTime }}
          </view>
        </view>
      </view>
      <view v-else>
        <view
          v-for="(item, index) in endExamList"
          :key="`else-${index}`"
          class="content_item"
          @click="goDetail(item)"
        >
          <view class="content_item_title">
            <span class="content_item_title_name">{{ item.examName || '' }}</span>
            <span
              class="content_item_title_status"
              :style="{ 'background-color': getEndStatus(item)?.color }"
            >{{ getEndStatus(item)?.text }}</span>
          </view>
          <view v-if="getEndStatus(item)?.text === '已出分'" class="content_item_result_score">
            <view class="content_item_result">
              考试结果：<text
                :style="{ color: item.examScore >= item.totalScore ? '#38B865' : '#EB5E12' }"
              >
                {{ item.examScore >= item.totalScore ? '及格' : '不及格' }}
              </text>
            </view>
            <view class="content_item_score">
              分数：<text>{{ item.examScore }}</text>
            </view>
          </view>
          <view class="content_item_time">
            {{ item.examStartTime }}
          </view>
        </view>
      </view>
      <!-- 加载中状态 -->
      <view v-if="isLoading" class="load-more">
        <text style="font-size: 24rpx; color: #86909c">加载中...</text>
      </view>
      <!-- 无更多数据提示 -->
      <view
        v-if="!isLoading && (activeId === 1 ? waitingForTheExam.length : endExamList.length) > 0 && (activeId === 1 ? waitingForTheExam.length >= pendingTotal : endExamList.length >= endTotal)"
        class="load-more"
      >
        <text style="font-size: 24rpx; color: #86909c">- 暂无更多数据 -</text>
      </view>
    </scroll-view>
  </view>
</template>

<style scoped lang="scss">
html,
body {
  overflow: hidden;
}
.knowledgebase_exam {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx;
  box-sizing: border-box;
  min-height: 0;
}
.header_nav {
  width: 100%;
  display: flex;
  gap: 24rpx;
  .header_nav_item {
    font-size: 32rpx;
    font-weight: 400;
    color: #4e5969;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
  }
  .active {
    font-weight: 500;
    color: #31373d;
  }
  .active_line {
    width: 40%;
    height: 4rpx;
    border-radius: 8rpx;
    background-color: #215acd;
  }
}
.content {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin-top: 46rpx;
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  padding-bottom: 150rpx;
  .content_item {
    // height: 150rpx;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    flex-direction: column;
    gap: 30rpx;
    padding-bottom: 24rpx;
    box-sizing: border-box;
    // justify-content: center;
    // gap: 12rpx;
    .content_item_title {
      display: flex;
      gap: 16rpx;
      align-items: flex-start;
      .content_item_title_name {
        font-weight: 500;
        font-style: 65 Medium;
        font-size: 32rpx;
        color: #31373d;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        max-width: calc(100% - 120rpx);
      }
      .content_item_title_status {
        padding: 10rpx;
        border-radius: 8rpx;
        font-size: 24rpx;
        font-weight: 400;
        font-style: 55 Regular;
        color: #ffffff;
        white-space: nowrap;
      }
    }
    .content_item_result_score {
      display: flex;
      gap: 24rpx;
      color: #31373d;
      font-size: 28rpx;
    }
    .content_item_time {
      font-size: 28rpx;
      font-weight: 400;
      font-style: 55 Regular;
      color: #86909c;
    }
  }
  :last-child {
    border-bottom: none;
  }
}
.load-more {
  width: 100%;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}
</style>
