<template>
  <div>
    <!-- 整卷 -->
    <div v-if="paperStyle == 0">
      <div v-for="(item, ind) in questionList?.classify" :key="ind">
        <p
        class="ele-item answer-item"
        style="padding: 10px 0 20px 0; font-weight: bold; font-size: 14px"
        >
          第{{
            ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"][ind]
            }}部分：
          {{ item.title }}
          <span
            style="
              font-size: 12px;
              font-weight: normal;
              display: inline-block;
              margin-left: 10px;
              color: #999;
            "
          >
          (共{{ questionList.questions[item.title].length }}题<span
              v-if="(typeof item.score !== 'undefined')"
              >，每题{{ item.score }}分</span>
           )
          </span>
          <span
            v-if="isPrint && mode !== 4"
            style="
              margin-left: 10px;
              height: 25px;
              display: inline-block;
              border: 1px solid black;
              text-align: center;
              line-height: 23px;
            "
          >
            <span
              style="
                width: 50px;
                height: 100%;
                display: inline-block;
                border-right: 1px solid black;
              "
              >得分</span
            >
            <span style="width: 60px; display: inline-block">
              {{ item.userScore }}
            </span>
          </span>
        </p>
        <div
          :style="{ 'margin-bottom': '10px' }"
          class="ele-item"
          v-for="(questionItem, ind) in questionList.questions[item.title]"
          :key="questionItem.id"
        >
          <QuestionItem
            :random="random"
            :questionInfo="questionItem"
            :serial="ind + 1"
            @answerChanged="userAnswerOnChange($event, questionItem)"
            @flag="toggleFlagList"
            :isFlag="flagList.includes(questionItem.id)"
            :mode="mode"
            @eval="questionItemHasEval"
          ></QuestionItem>
        </div>
      </div>
    </div>
    <!-- 逐题模式 -->
    <div v-if="paperStyle == 1">
      <div>
        <p style="padding: 10px 0 20px 0; font-weight: bold; font-size: 14px">
          {{ questions[currentQuestionInd].type }}
          <span
            style="
              font-size: 12px;
              font-weight: normal;
              display: inline-block;
              margin-left: 10px;
              color: #999;
            "
          >
            (共{{
              questionList.questions[questions[currentQuestionInd].type].length
            }}题，<span v-if="questions[currentQuestionInd].score"
              >每题{{ questions[currentQuestionInd].score }}分</span
            >)
          </span>
        </p>
        <QuestionItem
          :questionInfo="questions[currentQuestionInd]"
          :key="questions[currentQuestionInd].id"
          :serial="currentQuestionInd + 1"
          @answerChanged="
          userAnswerOnChange($event, questions[currentQuestionInd])
          "
          @flag="toggleFlagList"
          :isFlag="flagList.includes(questions[currentQuestionInd].id)"
          :mode="mode"
          :answer="getAnswer(questions[currentQuestionInd].id)"
        ></QuestionItem>
      </div>
      <div class="changer-btns">
        <div>
          <el-button
            size="medium"
            icon="el-icon-arrow-left"
            type="primary"
            circle
            :disabled="currentQuestionInd == 0"
            @click="changeQuestion(-1)"
          ></el-button>
          <p>上一题</p>
        </div>
        <div>
          <el-button
            size="medium"
            :icon="
              !flagList.includes(questions[currentQuestionInd].id)
                ? 'el-icon-star-off'
                : 'el-icon-star-on'
            "
            :style="{
              color: flagList.includes(questions[currentQuestionInd].id)
                ? '#ee0000'
                : '#333333',
            }"
            circle
            @click="
              toggleFlagList({
                isFlag: !flagList.includes(questions[currentQuestionInd].id),
                question: questions[currentQuestionInd],
              })
            "
          ></el-button>
          <p>标记</p>
        </div>
        <div>
          <el-button
            size="medium"
            icon="el-icon-arrow-right"
            type="primary"
            circle
            :disabled="currentQuestionInd == questions.length - 1"
            @click="changeQuestion(1)"
          ></el-button>
          <p>下一题</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import QuestionItem from '@/views/assessment-evaluation/question-bank-manage/components/QuestionItem.vue'
export default {
  components: { QuestionItem },
  props: {
    questions: {},
    // 模式：0答题 1预览 2模拟考试 3判卷 4错题巩固-背题模式 5-错题巩固-答题模式
    mode: { default: 0, type: Number },
    // 试卷模式，0整卷，1逐题
    paperStyle: {
      default: 0,
      type: Number
    },
    random: {
      default: () => [0, 0],
      type: Array
    }

    // onlyMistake: {
    //   default: false
    // },
    // onlyTextarea: {
    //   default: false
    // }
  },
  data: () => ({
    flagList: [],
    answerList: [],
    questionList: null,
    currentQuestionInd: 0,
    evalList: [],
    isPrint: false
  }),
  watch: {
    questions: {
      deep: true,
      immediate: true,
      handler (nv) {
        if (nv) {
          this.questionList = this.formatQuestions(nv)
        }
      }
    }
  },
  activated () {
    this.flagList = []
    this.answerList = []
    this.evalList = []
    this.currentQuestionInd = 0
    if (this.$route.meta?.key === 'printPaper') {
      this.isPrint = true
    }
  },
  created () {
    if (this.$route.meta?.key === 'printPaper') {
      this.isPrint = true
    }
  },
  methods: {
    // 当子组件发出事件时调用的方法。
    questionItemHasEval (nv) {
      const oldInd = this.evalList.findIndex((item) => item.id === nv.id)
      if (oldInd !== -1) this.evalList.splice(oldInd, 1)
      if (Object.keys(nv).includes('score')) {
        this.evalList.push(nv)
      }
      this.$emit('evalChanged', this.evalList)
    },
    // 使用questionID切换当前试题ind
    changeIndById (id) {
      const ind = this.questions.findIndex((item) => item.id === id)
      this.currentQuestionInd = ind
    },
    // 一种更改当前问题索引的方法。
    changeQuestion (offset) {
      this.currentQuestionInd += offset
    },
    getAnswer (questionId) {
      const ind = this.answerList.findIndex(
        (item) => item.questionId === questionId
      )
      if (ind === -1) return null

      return this.answerList[ind].answer
    },
    // 当子组件发出事件时调用的方法。
    userAnswerOnChange (answer, question) {
      const ind = this.answerList.findIndex(
        (item) => item.questionId === question.id
      )
      if (ind !== -1) {
        this.answerList.splice(ind, 1)
      }
      if (answer.length > 0) {
        const item = { questionId: question.id, answer }
        if (this.mode === 5) {
          item.resultId = question.resultId
        }
        this.answerList.push(item)

        this.$emit('answers', this.answerList)
      }
    },
    // 当用户单击星形图标时调用的方法。
    toggleFlagList ({ isFlag, question }) {
      if (isFlag === true) {
        this.flagList.push(question.id)
      } else {
        const itemInd = this.flagList.indexOf(question.id)
        this.flagList.splice(itemInd, 1)
      }
      this.$emit('flag', this.flagList)
    },
    // 获取一组问题并返回一个具有两个属性的对象：`classify` 和 `questions`。
    formatQuestions (questionList) {
      // const questionsClassify = {}
      const resQ = questionList.reduce(
        (prev, item) => {
          const index = prev.classify.findIndex((j) => j.title === item.type)
          if (index === -1) {
            prev.classify.push({
              title: item.type,
              score: item.itemScore || item.score || 0,
              userScore:
                typeof item.userScore !== 'undefined'
                  ? item.userScore
                  : undefined
            })
          } else {
            if (typeof item.userScore !== 'undefined') {
              prev.classify[index].userScore += item.userScore
            }
          }
          if (Object.keys(prev.questions).includes(item.type)) {
            prev.questions[item.type].push(item)
          } else prev.questions[item.type] = [item]
          return prev
        },
        { classify: [], questions: {} }
      )
      return resQ
    }
  }
}
</script>

<style lang="scss" scoped>
.changer-btns {
  margin-top: 20px;
  padding-top: 16px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #efefef;

  & > div {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 20px;
    & > p {
      padding: 5px 0;
      color: $--color-primary;
    }
  }
}
</style>
