<script setup lang="ts">
import { getExperimentQuestionList, getExperimentQuestion } from '../api'
import { Document } from '@element-plus/icons-vue'
import { filesize } from 'filesize'

interface Props {
  experiment_id: string,
  exam_status?: number
}
interface QuestionListItem {
  experiment_id: string
  id: string
  type: string
}
type QuestionGroupListItem = QuestionListItem & { index: number }
interface QuestionGroupList {
  type: string
  type_name: string
  list: Array<QuestionGroupListItem>
}

const props = defineProps<Props>()

const questionIndex = ref<number>(1)
const questionId = computed(() => {
  return questionList.value[questionIndex.value - 1]?.id
})
const questionList = ref<QuestionListItem[]>([])
const questionGroupList = computed<QuestionGroupList[]>(() => {
  return questionList.value.reduce((result, item, index) => {
    let currentGroup = result.find(({ type }) => customFloor(parseInt(type)) === customFloor(parseInt(item.type)))
    if (!currentGroup) {
      result.push({ type: item.type, type_name: getQuestionTypeName(item.type), list: [] })
      currentGroup = result[result.length - 1]
    }
    currentGroup.list.push({ ...item, index: index + 1 })
    return result
  }, [] as QuestionGroupList[])
})
const hasPrev = computed(() => questionIndex.value > 1)
const hasNext = computed(() => questionIndex.value < questionList.value.length)

// 试题列表
async function fetchList() {
  if (!props.experiment_id) return
  const res = await getExperimentQuestionList({ experiment_id: props.experiment_id })
  questionList.value = res.data.items
}
watchEffect(() => {
  if (props.experiment_id) fetchList()
})

// 试题详情
const questionDetail = ref()
async function fetchDetail() {
  if (!questionId.value) return
  const res = await getExperimentQuestion({ experiment_id: props.experiment_id, id: questionId.value })
  const detail = res.data.detail
  let files = []
  try {
    files = JSON.parse(detail.files)
  } catch (error) {
    console.log(error)
  }
  questionDetail.value = { ...detail, files, score: parseFloat(detail.score) }
}
watch(questionId, id => {
  if (id) fetchDetail()
})

function handleClick(question: QuestionGroupListItem) {
  questionIndex.value = question.index
}
function handlePrev() {
  questionIndex.value--
}
function handleNext() {
  questionIndex.value++
}

function getQuestionTypeName(type: string) {
  if (['101', '102'].includes(type)) return '用户/事件管理'
  if (['201', '202'].includes(type)) return '标签管理'
  if (['301', '302'].includes(type)) return '群组管理'
  if (['401', '402', '403', '404', '405', '406', '407'].includes(type)) return '营销资料管理'
  if (['501'].includes(type)) return '用户旅程'
  if (['601'].includes(type)) return '营销报告'
  return type
}
function customFloor(num: number) {
  return num - (num % 100)
}
</script>

<template>
  <div v-if="questionList.length">
    <el-card shadow="never" class="question-number">
      <dl v-for="group in questionGroupList" :key="group.type">
        <dt>{{ group.type_name }}</dt>
        <dd>
          <span
            :class="{ 'is-active': question.id === questionId }"
            v-for="question in group.list"
            :key="question.index"
            @click="handleClick(question)"
            >{{ question.index }}</span
          >
        </dd>
      </dl>
    </el-card>
    <el-card shadow="never" class="question-item" v-if="questionDetail">
      <h3 class="question-item__title">{{ getQuestionTypeName(questionDetail.type) }}</h3>
      <p class="question-item__stem">
        {{ questionIndex }}、{{ questionDetail.title }} <span v-if="props?.exam_status !== 1">（{{ questionDetail.score }}分）</span>
      </p>
      <p class="question-item__content">{{ questionDetail.content }}</p>
      <ul class="question-item__files">
        <li class="question-item__files-item" v-for="(file, index) in questionDetail.files" :key="index">
          <el-icon><Document /></el-icon>
          <div class="question-item__files-item__title">
            <p>{{ file.name }}</p>
            <p>{{ filesize(file.size) }}</p>
          </div>
          <a :href="file.url" target="_blank" download v-if="file.is_download">下载</a>
          <a :href="file.url" target="_blank">查看</a>
        </li>
      </ul>
    </el-card>
    <el-row justify="center">
      <el-button type="primary" :disabled="!hasPrev" @click="handlePrev">上一题</el-button>
      <el-button type="primary" :disabled="!hasNext" @click="handleNext">下一题</el-button>
    </el-row>
  </div>
  <el-empty description="暂无数据" v-else />
</template>

<style lang="scss" scoped>
.question-number {
  dt {
    font-size: 14px;
    margin-bottom: 10px;
  }
  dd {
    span {
      margin-right: 10px;
      margin-bottom: 10px;
      display: inline-block;
      width: 28px;
      height: 28px;
      text-align: center;
      font-size: 14px;
      line-height: 28px;
      border: 1px solid #bbb;
      border-radius: 50%;
      cursor: pointer;
      &.is-active {
        color: #fff;
        background-color: var(--main-color);
        border-color: var(--main-color);
      }
    }
  }
}
.question-item {
  margin-top: 10px;
  margin-bottom: 20px;
}
.question-item__title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
}
.question-item__stem {
  font-size: 14px;
  color: #101010;
}
.question-item__content {
  margin-top: 10px;
  font-size: 13px;
  color: #75797b;
}
.question-item__files-item {
  margin-top: 10px;
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f2f2f2;
  border-radius: 6px;
  a {
    margin-left: 10px;
    font-size: 14px;
    color: var(--main-color);
  }
  .el-icon {
    font-size: 20px;
    color: var(--main-color);
  }
}
.question-item__files-item__title {
  flex: 1;
  font-size: 12px;
  color: #75797b;
  margin: 0 10px;
}
</style>
