<!--
 * @desc 创建试卷
 * @author linyuanjie
 * @date 2023/10/16
-->

<template>
  <basic-container>
    <el-button size="small" @click="backFn">
      返回
    </el-button>
    <el-form
      :model="formData"
      :rules="formRules"
      ref="formRef"
      label-width="80px"
      class="mt24"
    >
      <el-form-item label="标题:" prop="title">
        <el-input
          v-model="formData.title"
          maxlength="30"
          show-word-limit
          disabled
        />
      </el-form-item>
      <div class="mt24">题目设置</div>
      <el-divider />
      <div
        v-for="(item, index) in quizList"
        :key="item.widget"
        class="question-item"
      >
        <div>
          {{ index + 1 }}.{{ item.label }}（分值：<span class="color_blue">{{
            item.mark || "-"
          }}</span
          >分）
        </div>
        <el-radio-group v-model="quizList[index].answer" class="mt14">
          <div
            v-for="optionItem in item.options"
            :key="optionItem.no"
            class="mb14"
          >
            <el-radio :label="optionItem.no">
              <template v-if="optionItem.type === 'text'">
                {{ optionItem.text }}
              </template>
              <template v-if="optionItem.type === 'img'">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="baseUrl + optionItem.text"
                  :preview-src-list="[baseUrl + optionItem.text]"
                >
                </el-image> </template
            ></el-radio>
          </div>
        </el-radio-group>
        <div v-if="!item.mark" class="danger_text f12">请设置题目分数</div>
        <div class="mt8">
          <el-button size="mini" @click="editQuizItemFn(item, index)"
            >编辑</el-button
          >
          <el-button size="mini" @click="delQuizItemFn(item, index)"
            >删除</el-button
          >
          <el-button size="mini" @click="enterQuestionBank(item)"
            >录入到题库</el-button
          >
        </div>
        <el-divider />
      </div>
      <div class="df_sb">
        <div class="df_ac">
          <el-button type="primary" @click="showAddQuizItemFn"
            >添加题目</el-button
          >
          <i class="grey_line ml20 mr20"></i>
          <el-button type="text" @click="showSelectQuizItemFn"
            >从题库中选择</el-button
          >
        </div>
        <div class="df_ac">
          <div>
            总题数<span class="ml8 color_blue">{{ quizList.length }}</span>
          </div>
          <i class="grey_line ml20 mr20"></i>
          <div>
            总分<span class="ml8 color_blue">{{ totalMark }}</span>
          </div>
          <el-button class="ml20" type="primary" @click="saveQuizFn"
            >保存试卷</el-button
          >
        </div>
      </div>
    </el-form>
    <addQuizTitleDialog
      :showDialog.sync="showAddQuizTitleDialog"
      @setTitle="setTitle"
      @setUUID="setUUID"
    />
    <addQuestionDialog
      :showDialog.sync="showAddQuestionDialog"
      :dialogType="dialogType"
      :questionDetail="questionDetail"
      :pageType="'addQuiz'"
      @addQuizItemFn="addQuizItemFn"
      @updateQuizItemFn="updateQuizItemFn"
    />
    <selectQuizItemDialog
      v-if="showSelectQuestionDialog"
      :showDialog.sync="showSelectQuestionDialog"
      @setSelection="setSelection"
    />
    <saveQuizDialog
      :showDialog.sync="showSaveQuizDialog"
      :saveQuizParams="saveQuizParams"
      @backFn="backFn"
    />
  </basic-container>
</template>

<script>
import {
  addQuestion,
  addQuizItem,
  batchAddQuizItem,
  delQuizItem,
  updateQuizItem
} from "@/api/test";
import addQuizTitleDialog from "@/views/admin/quiz/components/addQuizTitleDialog";
import addQuestionDialog from "@/views/admin/quiz/components/addQuestionDialog";
import selectQuizItemDialog from "@/views/admin/quiz/components/selectQuizItemDialog";
import saveQuizDialog from "@/views/admin/quiz/components/saveQuizDialog";

export default {
  name: "add",
  components: {
    addQuizTitleDialog,
    addQuestionDialog,
    selectQuizItemDialog,
    saveQuizDialog
  },
  data() {
    return {
      formData: {},
      formRules: {},
      showAddQuizTitleDialog: true,
      quizSerialNum: null,
      showAddQuestionDialog: false,
      dialogType: "add",
      questionDetail: null,
      quizList: [], // 当前问卷的题目列表
      showSelectQuestionDialog: false,
      saveQuizParams: {},
      showSaveQuizDialog: false
    };
  },
  computed: {
    totalMark() {
      return this.quizList.reduce((pre, cur) => {
        return pre + (cur.mark ? parseInt(cur.mark) : 0);
      }, 0);
    }
  },
  methods: {
    // 保存问卷
    saveQuizFn() {
      const everyItemHasMark = this.quizList.every(ele => !!parseInt(ele.mark));
      if (!everyItemHasMark) {
        this.$message.warning("请设置所有题目的分数");
        return;
      }
      this.saveQuizParams = {
        sn: this.quizSerialNum,
        expand: {
          itemQty: this.quizList.length,
          totalMark: this.totalMark,
          passingMark: ""
        },
        title: this.formData.title,
        introduction: ""
      };
      this.showSaveQuizDialog = true;
    },
    backFn() {
      this.$router.back();
    },
    setTitle(title) {
      this.formData.title = title;
    },
    setUUID(uuid) {
      this.quizSerialNum = uuid;
    },
    // 编辑题目
    editQuizItemFn(item, index) {
      this.questionDetail = Object.assign({}, item, { index });
      this.dialogType = "edit";
      this.showAddQuestionDialog = true;
    },
    // 编辑题目
    async updateQuizItemFn(val, editIdx) {
      const params = {
        ...val
      };
      const res = await updateQuizItem(params);
      if (res.data.code === 0) {
        this.quizList.splice(editIdx, 1, params);
        this.$message.success("编辑题目成功");
      }
    },
    // 删除题目
    delQuizItemFn(item, idx) {
      this.$confirm("是否删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await delQuizItem({ itemId: item.itemId });
          if (res.data.code === 0) {
            this.$message.success("删除题目成功");
            this.quizList.splice(idx, 1);
          }
        })
        .catch(() => {});
    },
    // 录入到题库
    async enterQuestionBank(item) {
      const { label, options, answer } = item;
      const params = {
        label,
        options,
        answer
      };
      const res = await addQuestion(params);
      if (res.data.code === 0) {
        this.$message.success("录入题库成功");
      }
    },
    // 添加题目-弹窗
    showAddQuizItemFn() {
      this.questionDetail = null;
      this.dialogType = "add";
      this.showAddQuestionDialog = true;
    },
    // 添加题目
    async addQuizItemFn(val) {
      const params = {
        ...val,
        quizSerialNum: this.quizSerialNum,
        widget: this.quizList.length
          ? this.quizList[this.quizList.length - 1].widget + 1
          : 0
      };
      const res = await addQuizItem(params);
      if (res.data.code === 0) {
        this.quizList.push({
          ...params,
          itemId: res.data.data
        });
        this.$message.success("添加题目成功");
      }
    },
    // 显示题库
    showSelectQuizItemFn() {
      this.showSelectQuestionDialog = true;
    },
    // 从题库挑选题目
    async setSelection(list) {
      const params = list.map((ele, index) => {
        const { label } = ele;
        const { options, answer } = ele.details;
        return {
          label,
          quizSerialNum: this.quizSerialNum,
          options,
          answer,
          widget: this.quizList.length + index + 1
        };
      });
      const res = await batchAddQuizItem(params);
      if (res.data.code === 0) {
        const result = res.data.data || [];
        result.forEach(ele => {
          const {
            label,
            options,
            itemId,
            answer,
            mark,
            quizSerialNum,
            widget
          } = ele;
          this.quizList.push({
            label,
            options,
            itemId,
            answer,
            mark,
            quizSerialNum,
            widget
          });
        });
        this.$message.success("添加题目成功");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.grey_line {
  display: inline-block;
  width: 1px;
  height: 24px;
  background-color: #c3c3c3;
}
.color_blue {
  color: #1e90ff;
}
.danger_text {
  color: #f56c6c;
}
</style>
