<template>
  <div class="exercise">
    <div class="list">
      <el-button icon="el-icon-back" @click="back">返回练习管理</el-button>
      <div class="list-title">
        <el-input v-if="isEditExercise" v-model="exercise.name" @keyup.enter.native="UpdateExerciseName" />
        <span v-else class="nowrap-ellipsis">{{ exercise.name }}</span>
        <SvgIcon icon-class="edit" class-name="edit" @click="editExercise" />
      </div>
      <div class="exercise-list">
        <ul>
          <li v-for="(item, i) in index_list" :key="i" :class="['exercise-item', { active: i === curIndex }]">
            <SvgIcon icon-class="child" :size="20" />
            <span class="item-name nowrap-ellipsis" @click="selectExerciseItem(i)">
              {{ i + 1 }}. {{ exerciseNames[item.type] }}
            </span>
            <SvgIcon icon-class="copy" class="pointer" :size="10" @click="copy(i)" />
          </li>
        </ul>
      </div>
      <div class="list-operate">
        <!-- <el-button type="primary">批量导入</el-button> -->
        <el-button type="primary" @click="addQuestionToExercise('select', 'single')">新建</el-button>
      </div>
    </div>

    <CreateMain
      ref="createMain"
      :cur-index="curIndex"
      :index-list="index_list"
      @selectExerciseItem="selectExerciseItem"
      @setUp="setUp"
      @setPreview="setPreview"
      @deleteQuestion="deleteQuestion"
      @createNewQuestion="createNewQuestion"
    />

    <div class="preview" :style="{ minHeight: preview ? '300px' : 'auto' }">
      <div class="preview-header">
        <span class="quick-preview">快捷预览：</span>
        <div class="preview-right">
          <template v-if="preview">
            <span class="preview-button plain" @click="refreshPreviewData">
              <SvgIcon icon-class="loop" size="14" /><span>刷新</span>
            </span>
            <span class="preview-button"><SvgIcon icon-class="eye" /><span>完整预览</span></span>
            <span class="preview-button plain" @click="setPreview"><SvgIcon icon-class="close" />关闭预览</span>
          </template>
          <template v-else>
            <span class="preview-button" @click="setPreview"><SvgIcon icon-class="eye" />预览</span>
          </template>
        </div>
      </div>
      <div class="preview-content">
        <component :is="curPreviewPage" v-if="preview" :data="previewData" :child-preview-data="childPreviewData" />
      </div>
    </div>
  </div>
</template>

<script>
import { exerciseNames } from '../data/common';
import {
  AddQuestionToExercise,
  DeleteQuestion,
  GetExerciseQuestionIndexList,
  GetQuestionInfo,
  GetExerciseInfo,
  UpdateExercise,
} from '@/api/exercise';

import CreateMain from './components/create.vue';
import SelectPreview from '@/views/exercise_questions/preview/SelectPreview.vue';
import JudgePreview from '@/views/exercise_questions/preview/JudgePreview.vue';
import MatchingPreview from '@/views/exercise_questions/preview/MatchingPreview.vue';
import ChinesePreview from '@/views/exercise_questions/preview/ChinesePreview.vue';
import WritePreview from '../preview/WritePreview.vue';
import FillPreview from '../preview/FillPreview.vue';
import ReadAloudPreview from '../preview/ReadAloudPreview.vue';
import DialoguePreview from '../preview/DialoguePreview.vue';
import TalkPictruePreview from '../preview/TalkPictruePreview.vue';
import ChooseTonePreview from '../preview/ChooseTonePreview.vue';
import RepeatPreview from '../preview/RepeatPreview.vue';
import ReadPreview from '../preview/ReadPreview.vue';
import SortPreview from '../preview/SortPreview.vue';
import ListenSelectPreview from '../preview/ListenSelectPreview.vue';
import ListenFillPreview from '../preview/ListenFillPreview.vue';
import ListenJudgePreview from '../preview/ListenJudgePreview.vue';
import WordCardPreview from '../preview/WordCardPreview.vue';
import AnswerQuestionPreview from '../preview/AnswerQuestionPreview.vue';
import WritePictruePreview from '../preview/WritePictruePreview.vue';
import ReplaceAnswerPreview from '../preview/ReplaceAnswerPreview.vue';

export default {
  name: 'CreateExercise',
  components: {
    CreateMain,
    SelectPreview,
    JudgePreview,
    MatchingPreview,
    ChinesePreview,
    WritePreview,
    FillPreview,
    ReadAloudPreview,
    DialoguePreview,
    TalkPictruePreview,
    ChooseTonePreview,
    RepeatPreview,
    ReadPreview,
    SortPreview,
    ListenSelectPreview,
    ListenFillPreview,
    ListenJudgePreview,
    WordCardPreview,
    AnswerQuestionPreview,
    WritePictruePreview,
    ReplaceAnswerPreview,
  },
  provide() {
    return {
      isSetUp: () => this.isSetUp,
      updateCurQuestionType: this.updateCurQuestionType,
      exercise_id: this.id,
      refreshPreviewData: this.refreshPreviewData,
    };
  },
  data() {
    const { id } = this.$route.query;

    return {
      id, // 练习id
      exercise: { name: '' }, // 练习信息
      isEditExercise: false, // 是否编辑练习
      curIndex: 0, // 当前练习索引
      index_list: [], // 练习列表
      exerciseNames, // 练习名称
      isSetUp: false, // 设置
      preview: false, // 预览显示
      previewData: {}, // 预览数据
      previewComponents: {
        select: SelectPreview,
        judge: JudgePreview,
        matching: MatchingPreview,
        chinese: ChinesePreview,
        write: WritePreview,
        fill: FillPreview,
        read_aloud: ReadAloudPreview,
        dialogue: DialoguePreview,
        talk_picture: TalkPictruePreview,
        choose_tone: ChooseTonePreview,
        repeat: RepeatPreview,
        read: ReadPreview,
        sort: SortPreview,
        listen_select: ListenSelectPreview,
        listen_fill: ListenFillPreview,
        listen_judge: ListenJudgePreview,
        word_card: WordCardPreview,
        answer_question: AnswerQuestionPreview,
        write_picture: WritePictruePreview,
        replace_answer: ReplaceAnswerPreview,
      },
    };
  },
  computed: {
    curPreviewPage() {
      if (this.index_list.length === 0) return '';
      return this.previewComponents[this.index_list[this.curIndex].type];
    },
  },
  watch: {
    curIndex() {
      if (this.index_list.length === 0) return;
      this.getQuestionInfo();
    },
  },
  created() {
    this.getExerciseQuestionIndexList(true);
    this.getExerciseInfo();
  },
  methods: {
    // 返回练习管理
    back() {
      this.$router.push('/personal_question');
    },
    /**
     * 添加题目到练习
     * @param {string} type 题目类型
     * @param {string} additional_type 附加类型
     * @param {string} content 题目内容
     */
    addQuestionToExercise(type, additional_type, content = '') {
      AddQuestionToExercise({
        exercise_id: this.id,
        type,
        additional_type,
        content,
      })
        .then(() => {
          this.getExerciseQuestionIndexList();
        })
        .catch(() => {
          this.$message.error('添加失败');
        });
    },
    // 创建新题
    createNewQuestion() {
      if (this.index_list.length === 0) {
        this.addQuestionToExercise('select', 'single');
        return;
      }
      let { type, additional_type } = this.index_list[this.curIndex];
      this.addQuestionToExercise(type, additional_type);
    },
    /**
     * 获取练习题目索引列表
     */
    getExerciseQuestionIndexList(init) {
      GetExerciseQuestionIndexList({ exercise_id: this.id })
        .then(({ index_list }) => {
          this.index_list = index_list;

          if (!init) return;
          this.getQuestionInfo();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getExerciseInfo() {
      GetExerciseInfo({ exercise_id: this.id }).then(({ exercise }) => {
        this.exercise = exercise;
      });
    },
    editExercise() {
      if (this.isEditExercise) {
        return this.UpdateExerciseName();
      }
      this.isEditExercise = !this.isEditExercise;
    },
    UpdateExerciseName() {
      UpdateExercise(this.exercise)
        .then(() => {
          this.isEditExercise = false;
        })
        .catch(() => {
          this.$message.error('修改失败');
        });
    },
    /**
     * 获取题目信息
     */
    getQuestionInfo() {
      if (this.index_list.length === 0) return;
      GetQuestionInfo({ question_id: this.index_list[this.curIndex].id })
        .then(({ question }) => {
          if (!question.content) return;

          this.$nextTick(() => {
            this.$refs.createMain.$refs.exercise?.[0].setQuestion(question);
            this.refreshPreviewData();
          });
        })
        .catch(() => {});
    },
    /**
     * 复制练习
     * @param {Number} index 练习索引
     */
    copy(index) {
      this.$confirm('是否复制当前题目', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          GetQuestionInfo({ question_id: this.index_list[index].id }).then(
            ({ question: { type, additional_type, content } }) => {
              this.addQuestionToExercise(type, additional_type, content);
            },
          );
        })
        .catch(() => {});
    },
    /**
     * 选择练习
     * @param {Number} index 练习索引
     * @param {object} data 练习数据
     */
    selectExerciseItem(index, data) {
      if (index < 0 || index > this.index_list.length - 1) return;
      this.curIndex = index;
      this.$refs.createMain.resetSaveDate();
      this.$refs.createMain.saveQuestion(data);
    },
    // 设置
    setUp() {
      this.isSetUp = !this.isSetUp;
    },
    // 刷新预览数据
    refreshPreviewData() {
      this.previewData = this.$refs.createMain.$refs.exercise?.[0].data || {};
      this.childPreviewData = this.$refs.createMain.$refs.exercise?.[0].childPreviewData || [];
    },
    // 预览
    setPreview() {
      this.preview = !this.preview;
      this.refreshPreviewData();
    },
    // 删除练习
    deleteQuestion() {
      DeleteQuestion({ question_id: this.index_list[this.curIndex].id })
        .then(() => {
          this.curIndex = Math.max(0, this.curIndex - 1);
          this.getExerciseQuestionIndexList();
          this.$message.success('删除成功');
        })
        .catch(() => {
          this.$message.error('删除失败');
        });
    },
    /**
     * 修改当前题目类型
     * @param {Array} arr
     */
    updateCurQuestionType(arr) {
      let type = arr[arr.length - 1];
      this.index_list[this.curIndex].type = type;
    },
  },
};
</script>

<style lang="scss" scoped>
.exercise {
  display: grid;
  grid-template: 1fr auto / 224px 1fr;
  height: 100%;

  .list {
    display: flex;
    flex-direction: column;
    grid-area: 1 / 1 / -1;
    row-gap: 16px;
    padding: 16px 8px;
    background-color: #fff;
    border-right: 1px solid $border-color;

    &-title {
      display: flex;
      column-gap: 8px;
      align-items: center;
      font-weight: bold;

      :first-child {
        flex: 1;
      }

      .edit {
        cursor: pointer;
      }
    }

    .exercise-list {
      max-height: calc(100% - 130px);
      overflow-y: auto;

      .exercise-item {
        display: flex;
        column-gap: 8px;
        align-items: center;
        padding: 4px 8px;
        color: #333;
        cursor: pointer;
        border-radius: 2px;

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

        .item-name {
          flex: 1;
        }
      }
    }

    &-operate {
      display: flex;

      > .el-button {
        flex: 1;
      }
    }
  }

  .preview {
    position: relative;
    max-height: 450px;
    padding: 16px 24px;
    overflow: auto;
    background-color: #eff1f5;
    border-top: 1px solid $border-color;

    .preview-header {
      display: flex;
      justify-content: space-between;
      width: 100%;

      .quick-preview {
        font-weight: bold;
      }

      .preview-right {
        display: flex;
        column-gap: 18px;
        align-items: center;

        .preview-button {
          display: flex;
          column-gap: 8px;
          align-items: center;
          color: #175dff;
          cursor: pointer;

          &.plain {
            color: #2f3742;
          }
        }
      }
    }

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

<style>
.el-cascader-menu__wrap {
  height: 235px;
}
</style>
