<template>
  <main class="create">
    <div class="create-operate">
      <div class="left-operate">
        <a
          :class="['pre', { disabled: curIndex === 0 }]"
          :disabled="curIndex === 0"
          @click="selectExerciseItem(curIndex - 1)"
        >
          <i class="el-icon-back"></i><span>上一题</span>
        </a>
        <a
          :class="['next', { disabled: curIndex === indexList.length - 1 || indexList.length === 0 }]"
          @click="selectExerciseItem(curIndex + 1)"
        >
          <span>下一题</span><i class="el-icon-right"></i>
        </a>
      </div>
      <div class="save-tip">
        <span>{{ curSaveDate }} </span><span>已自动保存</span>
        <span class="now-save" @click="saveQuestion">立即保存</span>
      </div>
      <div class="right-operate">
        <span class="current-score">当前卷面分：{{ totalScore }}</span>
        <span class="line"></span>
        <a class="preview" @click="setPreview"><SvgIcon icon-class="eye" /><span>预览</span></a>
        <a class="delete" @click="deleteQuestion"><SvgIcon icon-class="delete" /><span>删除</span></a>
      </div>
    </div>
    <div class="create-content">
      <QuestionHeader v-if="indexList.length > 0" :type="exerciseTypeList[indexList[curIndex].type]" />
      <template v-for="{ id } in indexList">
        <component
          :is="curExercisePage"
          v-if="id === indexList[curIndex].id"
          :key="id"
          ref="exercise"
          :question-id="id"
        />
      </template>
    </div>
  </main>
</template>

<script>
import { SaveQuestion } from '@/api/exercise';
import { timeFormatConversion } from '@/utils/transform';
import { exerciseTypeList } from '@/views/exercise_questions/data/questionType';

import QuestionHeader from './common/QuestionHeader.vue';
import SelectQuestion from './exercises/SelectQuestion.vue';
import JudgeQuestion from './exercises/JudgeQuestion.vue';
import MatchingQuestion from './exercises/MatchingQuestion.vue';
import FillQuestion from './exercises/FillQuestion.vue';
import ReadAloudQuestion from './exercises/ReadAloudQuestion.vue';
import ChineseQuestion from './exercises/ChineseQuestion.vue';
import WriteQuestion from './exercises/WriteQuestion.vue';
import DialogueQuestion from './exercises/DialogueQuestion.vue';
import TalkPictureQuestion from './exercises/TalkPictureQuestion.vue';
import ChooseToneQuestion from './exercises/ChooseToneQuestion.vue';
import RepeatQuestion from './exercises/RepeatQuestion.vue';
import ReadQuestion from './exercises/ReadQuestion.vue';
import SortQuestion from './exercises/SortQuestion.vue';
import ListenSelectQuestion from './exercises/ListenSelectQuestion.vue';
import ListenJudgeQuestion from './exercises/ListenJudgeQuestion.vue';
import ListenFillQuestion from './exercises/ListenFillQuestion.vue';
import WordCardQuestion from './exercises/WordCardQuestion.vue';
import AnswerQuestion from './exercises/AnswerQuestion.vue';
import WritePictureQuestion from './exercises/WritePictureQuestion.vue';
import ReplaceAnswerQuestion from './exercises/ReplaceAnswerQuestion.vue';
import EssayQuestion from './exercises/EssayQuestion.vue';
import TableFillQuestion from './exercises/TableFillQuestion.vue';
import WordDictationQuestion from './exercises/WordDictationQuestion.vue';
import ActivityQuestion from './exercises/ActivityQuestion.vue';

export default {
  name: 'CreateMain',
  components: {
    QuestionHeader,
  },
  provide() {
    return {
      curSaveDate: () => this.curSaveDate,
      recognition: this.recognition,
    };
  },
  props: {
    curIndex: {
      type: Number,
      required: true,
    },
    indexList: {
      type: Array,
      required: true,
    },
    loading: {
      type: Boolean,
      required: true,
    },
    totalScore: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      exerciseTypeList,
      timer: null,
      curSaveDate: '',
      exerciseComponents: {
        select: SelectQuestion,
        judge: JudgeQuestion,
        matching: MatchingQuestion,
        fill: FillQuestion,
        read_aloud: ReadAloudQuestion,
        chinese: ChineseQuestion,
        write: WriteQuestion,
        dialogue: DialogueQuestion,
        talk_picture: TalkPictureQuestion,
        choose_tone: ChooseToneQuestion,
        repeat: RepeatQuestion,
        read: ReadQuestion,
        sort: SortQuestion,
        listen_select: ListenSelectQuestion,
        listen_judge: ListenJudgeQuestion,
        listen_fill: ListenFillQuestion,
        word_card: WordCardQuestion,
        answer_question: AnswerQuestion,
        write_picture: WritePictureQuestion,
        replace_answer: ReplaceAnswerQuestion,
        essay_question: EssayQuestion,
        table_fill: TableFillQuestion,
        word_dictation: WordDictationQuestion,
        activity: ActivityQuestion,
      },
    };
  },
  computed: {
    curExercisePage() {
      if (this.indexList.length === 0) return '';
      return this.exerciseComponents[this.indexList[this.curIndex].type];
    },
  },
  mounted() {
    this.resetSaveDate();
  },
  beforeDestroy() {
    this.saveQuestion();
    clearInterval(this.timer);
  },
  methods: {
    // 重置保存时间
    resetSaveDate() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        this.saveQuestion();
      }, 30000);
    },
    // 清除保存时间
    clearSaveDate() {
      clearInterval(this.timer);
    },
    /**
     * 选择练习
     * @param {number} i 练习索引
     */
    selectExerciseItem(i) {
      if (this.indexList.length <= 0) return;
      this.$emit('selectExerciseItem', i);
    },
    /**
     * 预览
     */
    setPreview() {
      this.$emit('setPreview');
    },
    /**
     * 删除
     */
    deleteQuestion() {
      this.$confirm('是否删除当前题目', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$emit('deleteQuestion');
        })
        .catch(() => {});
    },
    /**
     * 数据格式转换
     */
    dataConversion() {
      const data = this.$refs.exercise[0].data;
      const { select_type } = data.property;

      return {
        question_id: this.indexList[this.curIndex].id,
        type: data.type,
        additional_type: select_type || '',
        content: JSON.stringify(data),
      };
    },
    /**
     * 保存题目
     */
    async saveQuestion() {
      if (this.indexList.length <= 0) return;
      if (this.loading) return;
      try {
        let childrenExercise = this.$refs.exercise[0].$refs.exercise;
        if (childrenExercise) {
          childrenExercise.forEach((item) => {
            item?.saveChildQuestion();
          });
        }
        await SaveQuestion(this.dataConversion());
        const curDate = timeFormatConversion(new Date());
        if (this.curSaveDate !== curDate) {
          this.curSaveDate = curDate;
        }
      } catch (err) {
        console.log(err);
      }
    },
    /**
     * 智能识别
     * @param {String} text
     */
    recognition(text) {
      this.$refs.exercise[0]?.recognition(text);
    },
  },
};
</script>

<style lang="scss" scoped>
.create {
  padding: 16px 24px;
  overflow: hidden;
  background-color: $main-background-color;

  &-operate {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left-operate {
      .pre,
      .next {
        display: inline-flex;
        column-gap: 8px;
        align-items: center;
        height: 32px;
        padding: 5px 8px;
        margin-left: 8px;
        font-size: 14px;
        color: #2f3742;
        cursor: pointer;

        &:hover {
          color: $main-color;
          background-color: #f4f8ff;
        }

        &.disabled {
          color: #999;
          cursor: not-allowed;

          &:hover {
            color: #999;
            background-color: $main-background-color;
          }
        }
      }
    }

    .save-tip {
      font-size: 12px;
      color: #858585;

      .now-save {
        margin-left: 8px;
        color: $main-color;
        cursor: pointer;
      }
    }

    .right-operate {
      display: flex;
      column-gap: 8px;
      align-items: center;

      %setting,
      .setting {
        display: flex;
        column-gap: 8px;
        align-items: center;
        padding: 4px 8px;
        color: #2f3742;
        cursor: pointer;
        border-radius: 2px;

        &:hover {
          background-color: $border-color;
        }
      }

      .current-score {
        font-size: 14px;
        color: #2f3742;
      }

      .preview {
        @extend %setting;

        color: #175dff;
      }

      .delete {
        @extend %setting;

        color: $danger-color;

        &:hover {
          background-color: $main-background-color;
        }
      }

      > span {
        color: #999;
        cursor: pointer;
      }
    }
  }

  &-content {
    width: 100%;
    height: calc(100% - 32px);
    margin-top: 16px;
    overflow: auto;
  }
}
</style>
