<template>
  <el-row v-if="!showQuestionList" class="box1">
    <el-col :span="20" class="box">
      <el-card class="box-card" v-if="examInfo">
        <template #header>
          <div class="card-header" v-if="paperQuestionsSet" style="font-size: 17px">
            评测「{{ examInfo.examName }}」
          </div>
          <div class="card-header" v-else style="font-size: 17px">
            评测「{{ examInfo.examName }}」创建成功 请设置试卷内容
          </div>
        </template>
        <el-row class="text">评测ID: {{ examInfo.examId }}</el-row>
        <el-row class="text">
          <el-col :span="12">
            评测邀请码：{{
              examInfo.inviteCode ? examInfo.inviteCode : '无'
            }}
          </el-col>
          <el-col :span="12">
            当前难度值：{{ examInfo.difficulty }}
          </el-col>
        </el-row>
        <el-row class="text">
          <el-col :span="12">
            开始时间：{{ examInfo.startTime }}
          </el-col>
          <el-col :span="12">
            结束时间：{{ examInfo.endTime }}
          </el-col>
        </el-row>
      </el-card>
    </el-col>
    <el-col v-if="!paperQuestionsSet" :span="20" class="box">
      <el-card class="box-card">
        <span style="font-size: 17px">样卷选择</span>
        <el-divider></el-divider>
        <el-tabs v-model="tab" v-if="examSamples[0]" class="demo-tabs">
          <el-tab-pane v-for="sample in examSamples" :key="sample.id" :name="sample.id" :label="'样卷' + sample.id">
            <div v-if="!fetching">
              <exam-questions-info :exam-questions="sampleQuestions[tab - 1]"
                :examId="this.examInfo.examId"></exam-questions-info>
            </div>
            <el-row justify="center">
              <el-button type="primary" style="float:right" @click="onSelectSample(sample.id)">
                选择此试卷
              </el-button>
              <el-button style="float: left" @click="showQuestionList = true">
                基于样卷调整试题
              </el-button>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
    <el-col v-else :span="20" class="box">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span style="font-size: 17px">试卷内容</span>
            <el-button v-if="fetching & hide" @click="onClickHideButton()" round style="float: right">
              <el-icon class="el-icon--right">
                <ArrowUp />
              </el-icon>
            </el-button>
            <el-button v-if="fetching & !hide" @click="onClickShowButton()" round style="float: right">
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <!--          响应事件是？-->
            <el-button v-if="!fetching" type="primary" style="float: right" @click="showQuestionList = true">
              调整试题
            </el-button>
          </div>
        </template>

        <exam-questions-info v-show="showQuestionInfo" :exam-questions="examQuestions"
          :examId="this.examInfo.examId"></exam-questions-info>
      </el-card>
    </el-col>
  </el-row>
  <question-list v-if="showQuestionList" :sample-questions="curQuestions" :question-and-score="curQuestionAndScore"
    :exam-id="this.examInfo.examId" :from-edit-page="true" @leave="showQuestionList = false"></question-list>
</template>

<script>

import ExamQuestionsInfo from "@/views/EvalPage/ExamQuestionsInfo.vue";
import QuestionList from "@/views/EvalPage/QuestionList.vue";
import { ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

export default {
  name: "EditExam",
  components: {
    ArrowDown,
    ArrowUp,
    ExamQuestionsInfo,
    QuestionList
  },
  data() {
    return {
      tab: 1,
      showQuestionList: false,
      paperQuestionsSet: false,
      examSamples: [],
      examQuestionAndScore: {},
      fetching: false,
      examQuestions: [],
      examInfo: [],
      sampleQuestions: [],
      showQuestionInfo: true,
      hide: true
    };
  },

  computed: {
    curQuestionAndScore() {
      if (this.paperQuestionsSet) {
        return this.examQuestionAndScore;
      }
      return this.examSamples[this.tab - 1].questionAndScore;
    },

    curQuestions() {
      if (this.paperQuestionsSet) {
        return this.examQuestions;
      }
      return this.sampleQuestions[this.tab - 1];
    },

  },

  created() {
    this.getExamInfo();
    this.$apis.getExamQuestions(this.examInfo.examId ?? "").then(
      _res => {
        if (_res.data.data.result) {
          this.paperQuestionsSet = true;
        }
        this.examQuestionAndScore = _res.data.data.result.questionAndScore;
        const questionsIds = Object.keys(_res.data.data.result.questionAndScore);
        const questionsPromises = [];
        this.fetching = true;
        questionsIds.forEach((value, index) => {
          questionsPromises[index] = this.$apis.getQuestionInfo(value);
        });
        Promise.all(questionsPromises)
          .then(reps => {
            this.examQuestions = reps.map((value) => {
              return value.data.data.result;
            });
          })
          .catch((error) => {
            console.log("题目获取失败");
          })
          .finally(() => {
            this.fetching = false;
          });
      }
    ).catch(() => {
      this.$apis.getSamplePaper().then(
        _res => {
          this.examSamples = _res.data.data.result;
          this.fetchQuestionInfo(0);
        });
    });
  },

  watch: {
    tab(val) {
      val = val - 1;
      this.fetchQuestionInfo(val);
    }
  },
  methods: {

    getExamInfo() {
      this.examId = this.$route.params.examId;
      this.$apis.getExamById(this.examId).then(_res => {
        this.examInfo = _res.data.data.result;
        this.examInfo.skills = this.examInfo.skills.toString();
      });
    },

    fetchQuestionInfo(val) {
      if (this.sampleQuestions[val]) {
        return this.sampleQuestions[val];
      } else {
        this.fetching = true;
        let questionsPromises = [];
        let questionsIds = Object.entries(
          this.examSamples[val].questionAndScore
        );
        questionsPromises = questionsIds.map((val) => {
          return this.$apis.getQuestionInfo(val[0]);
        });
        Promise.all(questionsPromises).then((reps) => {
          this.sampleQuestions[val] = reps.map((value) => {
            return value.data.data.result;
          });
          this.fetching = false;
        });
      }
    },

    onSelectSample(sampleId) {
      this.$apis.setExamPaperFromSample(this.examInfo.examId ?? "", sampleId).then(
        () => {
          ElMessage({
            message: "设置样卷成功",
            type: "success",
          });
          setTimeout(() => {
            this.$router.push({
              name: "teacher-examDetails",
              params: {
                examId: this.examInfo.examId,
              }
            });
          }, 1000);
        }
      ).catch(() => {
        ElMessage.error("设置样卷失败");
      });

    },

    onClickHideButton() {
      this.showQuestionInfo = false;
      this.hide = false;
    },

    onClickShowButton() {
      this.showQuestionInfo = true;
      this.hide = true;
    }


  }

};
</script>

<style scoped>
.el-alert {
  margin: 20px 0 0;
}

.el-alert:first-child {
  margin: 0;
}

.box {
  height: 100%;
  /*overflow-y: auto;*/
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.box1 {
  display: flex;
  justify-content: center;
}

.el-card {
  margin-bottom: 20px;
}

.text {
  font-family: Roboto, sans-serif;
  font-size: 14px;
}
</style>