<template>
  <main class="create">
    <div class="create-operate">
      <div class="left-operate">
        <el-button type="primary" @click="$emit('createNewQuestion')">创建新题</el-button>
        <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">{{ curSaveDate }} 已自动保存</div>
      <div class="right-operate">
        <a class="setting" @click="setUp"><SvgIcon icon-class="setting" /><span>设置</span></a>
        <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">
      <SelectQuestionType v-if="indexList.length > 0" :type="exerciseTypeList[indexList[curIndex].type]" />
      <template v-for="({ id }, i) in indexList">
        <KeepAlive :key="id">
          <component :is="curExercisePage" v-if="i === curIndex" ref="exercise" :question-id="id" />
        </KeepAlive>
      </template>
    </div>
  </main>
</template>

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

import SelectQuestionType from './common/SelectQuestionType.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';

export default {
  name: 'CreateMain',
  components: {
    SelectQuestion,
    JudgeQuestion,
    SelectQuestionType,
    MatchingQuestion,
    FillQuestion,
    ReadAloudQuestion,
    ChineseQuestion,
    WriteQuestion,
    DialogueQuestion,
    TalkPictureQuestion,
    ChooseToneQuestion,
    RepeatQuestion,
    ReadQuestion,
    SortQuestion,
    ListenSelectQuestion,
    ListenJudgeQuestion,
    ListenFillQuestion,
  },
  provide() {
    return {
      curSaveDate: () => this.curSaveDate,
      recognition: this.recognition,
    };
  },
  props: {
    curIndex: {
      type: Number,
      required: true,
    },
    indexList: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      timer: null,
      curSaveDate: '',
      exerciseTypeList,
      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,
      },
    };
  },
  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);
    },
    /**
     * 选择练习
     * @param {Number} i 练习索引
     */
    selectExerciseItem(i) {
      if (this.indexList.length <= 0) return;
      this.$emit('selectExerciseItem', i, this.dataConversion());
    },
    /**
     * 设置
     */
    setUp() {
      this.$emit('setUp');
    },
    /**
     * 预览
     */
    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;
      try {
        this.$bus.$emit('saveQuestion');
        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;
    }

    .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;
        }
      }

      .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>
