<template>
  <el-row class="box1">
    <el-col :span="20" class="box">
      <el-card class="box-card">
        <span style="font-size: 17px">已选题目</span>
        <el-divider></el-divider>
        <el-table ref="selectedQuestionsTable" :data="selectedQuestions" style="width: 100%" empty-text="空"
          :row-key="getRowKeys">
          <el-table-column label="分值" width="100">
            <template #default="scope">
              <span style="float: left; color: #71bbdb ">{{ scope.row.score }}</span>
              <span class="box2">
                <el-icon @click="increasePoints(scope.row)">
                  <CaretTop />
                </el-icon>
                <el-icon @click="decreasePoints(scope.row)">
                  <CaretBottom />
                </el-icon>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-icon @click="deleteItem(scope.$index, scope.row)" :size="20">
                <DeleteFilled />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="题干">
            <template #default="scope">
              <markdown-text :raw="scope.row.stem"></markdown-text>
            </template>
          </el-table-column>
        </el-table>
        <el-row justify="center">
          <el-button type="primary" @click="onSubmitManualPaper">确认调整</el-button>
          <el-button @click="onLeave">返回</el-button>
        </el-row>
      </el-card>
    </el-col>
    <el-col :span="20" class="box">
      <el-card class="box-card">
        <span style="font-size: 17px">试题列表</span>
        <el-divider></el-divider>
        <el-row style="justify-content:right;">
          <el-col :span="5">
            <el-input v-model="stem" class="w-50 m-2" size="small" placeholder="根据题目内容查找" @input="onSearch">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </el-col>
        </el-row>
        <el-table ref="questionsTable" :data="expanded" :row-key="getRowKeys" style="width: 100%" @select="handleSelect"
          @select-all="handleSelectAll">
          <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
          <el-table-column label="题目类型" prop="typeText" width="100" />
          <el-table-column label="标签" prop="tags" width="100" />
          <el-table-column label="关键词" prop="keyPoints" width="200" />
          <el-table-column label="题干" prop="stem">
            <template #default="scope">
              <markdown-text :raw="scope.row.stem"></markdown-text>
            </template>
          </el-table-column>
        </el-table>
        <el-row justify="center">
          <el-pagination v-model:current-page="pageNum" layout="total, prev, pager, next, jumper" background
            :total="totalNum" @current-change="changePage"></el-pagination>

        </el-row>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import markdownText from "@/views/EvalPage/MarkdownText.vue";
import { toRaw } from "vue";
import { ElMessage } from "element-plus";
import * as ELIcons from "@element-plus/icons-vue";

export default {
  name: "QuestionList",
  props: {
    sampleQuestions: {
      type: Array
    },
    questionAndScore: {},
    examId: null,
    fromEditPage: Boolean //是否从编辑页面跳过来
  },
  components: {
    markdownText
  },
  data() {
    return {
      questions: [],
      selectedQuestions: [],
      tags: "",
      knowledgeName: "",
      stem: "",
      pageNum: 1,
      pageSize: 10,
      totalNum: 0,
      loading: true,
      selectQuestionsSuccess: false,
      expanded: [],
    };
  },
  created() {
    this.fetchData();
  },
  mounted() {
    this.selectedQuestions = this.sampleQuestions.map((val) => {
      return {
        ...val,
        score: this.questionAndScore[val.id] ?? 3,
        typeText: this.questionTypeToText(val.type)
      };
    });
  },
  methods: {
    fetchData() {
      this.$apis.getQuestionList(
        { pageSize: this.pageSize, pageNum: this.pageNum },
        this.stem,
        this.tags,
        this.knowledgeName
      ).then(res => {
        this.questions = res.data.data.result.questionStemList.map((val) => {
          return { ...val, typeText: this.questionTypeToText(val.type), score: 5 };
        });
        this.totalNum = res.data.data.result.totalNum;
        this.expanded = [];
        this.$nextTick(() => {
          this.expanded = this.questions;
          this.loading = false;
        });
      });
    },
    deleteItem(index, item) {
      this.selectedQuestions.splice(index, 1);
      this.$refs.questionsTable.toggleRowSelection(item, false);
    },
    increasePoints(item) {
      let selectedIndex = this.selectedQuestions.indexOf(item);
      this.selectedQuestions[selectedIndex].score++;
    },
    decreasePoints(item) {
      let selectedIndex = this.selectedQuestions.indexOf(item);
      if (this.selectedQuestions[selectedIndex].score > 0)
        this.selectedQuestions[selectedIndex].score--;
    },

    questionTypeToText(type) {
      switch (type) {
        case "choice":
          return "单选题";
        case "multiple_choice":
          return "多选题";
        case "true_false":
          return "判断题";
        case "blank":
          return "填空题";
        case "code":
          return "编程题";
        case "short_answer":
          return "简答题";
      }
    },

    getRowKeys(row) {
      return row.id;
      //todo 列表的唯一id值
    },
    handleSelect(rows, row) {
      if (this.selectedQuestions.find((item) => item.id === row.id)) {
        this.selectedQuestions = this.selectedQuestions.filter(
          (item) => item.id !== row.id
        );
      } else {
        this.selectedQuestions.push(row);
      }
    },

    handleSelectAll(rows) {
      if (rows.length && rows.indexOf(this.expanded.at(0)) !== -1) {
        rows.forEach((row) => {
          if (!this.selectedQuestions.find((item) => item.id === row.id)) {
            this.selectedQuestions.push(row);
          }
        });
      } else {
        this.expanded.forEach((row) => {
          this.selectedQuestions = this.selectedQuestions.filter(
            (item) => item.id !== row.id
          );
        });
      }
    },

    onSubmitManualPaper() {
      let idAndScore = new Map();
      this.selectedQuestions.forEach((val) => {
        idAndScore.set(val.id, val.score);
      });
      this.$apis.setExamPaperQuestions(this.examId, Object.fromEntries(idAndScore)).then(() => {
        this.selectQuestionsSuccess = true;
        ElMessage({
          message: "修改试卷成功",
          type: "success",
        });
        if (this.fromEditPage) {
          setTimeout(() => {
            this.$router.push({
              name: "teacher-examDetails",
              params: {
                examId: this.examId,
              }
            });
          }, 1000);
        } else {
          this.$emit("updatePaper");
        }
      });
    },
    changePage() {
      this.loading = true;
      this.fetchData();
    },

    onSearch() {
      this.pageNum = 1;
      this.fetchData();
    },

    onLeave() {
      this.$emit("leave");
    }
  }
};
</script>

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

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

.box2 {
  display: flex;
  flex-direction: column;
  margin-top: -3px;
}


.el-card {
  margin-bottom: 20px;
}
</style>