<!--
 * @desc 添加试题
 * @author linyuanjie
 * @date 2023/10/16
-->

<template>
  <el-dialog
    :title="
      dialogType === 'add'
        ? '添加题目'
        : dialogType === 'edit'
        ? '编辑题目'
        : '查看题目'
    "
    :visible.sync="showDialog"
    width="50%"
    center
    :append-to-body="true"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :disabled="dialogType === 'view'"
      :hide-required-asterisk="dialogType === 'view'"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题:" prop="label">
        <el-input type="textarea" v-model="formData.label"></el-input>
      </el-form-item>
      <el-form-item label="选项:" prop="options">
        <div
          v-for="(item, index) in formData.options"
          :key="index"
          class="df_center mb12"
        >
          <el-radio v-model="answer" :label="index" class="mr10"
            ><span></span
          ></el-radio>
          <div class="type">
            <el-select
              v-model="item.type"
              placeholder="请选择"
              @change="e => selectChange(index, e)"
            >
              <el-option label="文本" value="text" />
              <el-option label="图片" value="img" />
            </el-select>
          </div>
          <div class="content">
            <template v-if="item.type === 'text'">
              <el-input v-model="item.text" class="mr20" />
            </template>
            <template v-if="item.type === 'img'">
              <uploadCom
                :info="item.text"
                @updateInfo="list => updatesSuccess(list, index)"
              />
            </template>
          </div>

          <i
            v-if="dialogType !== 'view'"
            class="el-icon-circle-plus-outline mr10 f22 pointer"
            @click="addAnswer"
          ></i>
          <i
            v-if="dialogType !== 'view' && formData.options.length !== 1"
            class="el-icon-remove-outline f22 pointer"
            @click="delAnswer(index)"
          ></i>
        </div>
      </el-form-item>
      <p class="ml100 mt10">说明：选中选项，可将其设置为正确答案。</p>
      <el-form-item
        v-if="pageType === 'addQuiz'"
        label="分数:"
        prop="mark"
        class="mt10"
      >
        <el-input-number
          v-model="formData.mark"
          controls-position="right"
          :min="0"
          class="w100 input-num-box"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button
        v-if="dialogType !== 'view'"
        type="primary"
        :step="1"
        @click="submitFn"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { addQuestion, updateQuestion } from "@/api/test";

import uploadCom from "./uploadCom.vue";

export default {
  name: "addQuestionDialog",
  components: { uploadCom },
  props: {
    showDialog: {
      type: Boolean,
      required: true,
      default: false
    },
    dialogType: {
      type: String,
      default: "add"
    },
    questionDetail: {
      type: Object,
      default: null
    },
    pageType: {
      type: String,
      default: "" // 从哪个页面打开的当前弹窗, addQuiz: 从创建试卷打开弹窗  默认为'': 从题库管理-创建试题打开弹窗
    }
  },
  data() {
    const optionsValidator = (rule, value, callback) => {
      const everyAnswerHasValue = value.every(ele => !!ele.text);
      if (this.answer !== 0 && !this.answer) {
        return callback(new Error("请设置正确答案"));
      }
      if (!everyAnswerHasValue) {
        return callback(new Error("请完善选项内容"));
      } else {
        callback();
      }
    };
    return {
      formData: {
        label: "",
        options: [
          {
            timestamp: new Date().getTime(),
            text: "",
            type: "text"
          }
        ],
        mark: ""
      },
      formRules: {
        label: [{ required: true, message: "请输入标题", trigger: "blur" }],
        options: [
          { required: true, validator: optionsValidator, trigger: "blur" }
        ],
        mark: [{ required: true, message: "请设置题目分数", trigger: "blur" }]
      },
      answer: "",
      alphabet: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z"
      ]
    };
  },
  methods: {
    selectChange(index, e) {
      this.formData.options[index].text = "";
    },
    updatesSuccess(url, index) {
      this.formData.options[index].text = url;
    },
    submitFn() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          const options = this.formData.options.map((ele, index) => ({
            no: this.alphabet[index],
            type: ele.type,
            text: ele.text
          }));
          const params = {
            label: this.formData.label,
            options,
            answer: this.alphabet[this.answer]
          };
          if (this.pageType === "addQuiz") {
            params.mark = this.formData.mark;
            if (this.dialogType === "add") {
              this.$emit("addQuizItemFn", params);
            } else {
              const { widget, itemId } = this.questionDetail;
              this.$emit(
                "updateQuizItemFn",
                { ...params, widget, itemId },
                this.questionDetail.index
              );
            }
            this.handleClose();
          } else {
            if (this.dialogType === "add") {
              const res = await addQuestion(params);
              if (res.data.code === 0) {
                this.handleClose();
                this.$emit("openSuccessTip");
              }
            } else {
              params.questionId = this.questionDetail.questionId;
              const res = await updateQuestion(params);
              if (res.data.code === 0) {
                this.handleClose();
                this.$emit("openSuccessTip");
              }
            }
          }
        } else {
          return false;
        }
      });
    },
    handleClose() {
      this.$emit("update:showDialog", false);
      this.formData.label = "";
      this.formData.options = [
        {
          timestamp: new Date().getTime(),
          text: ""
        }
      ];
      this.answer = "";
      this.formData.mark = "";
    },
    addAnswer() {
      this.formData.options.push({
        timestamp: new Date().getTime(),
        text: "",
        type: "text"
      });
    },
    delAnswer(index) {
      this.formData.options.splice(index, 1);
    }
  },
  watch: {
    showDialog(newVal) {
      if (
        newVal &&
        (this.dialogType === "view" || this.dialogType === "edit")
      ) {
        if (this.questionDetail && Object.keys(this.questionDetail).length) {
          const { label, options, answer, mark } = this.questionDetail;
          this.formData.mark = mark;
          this.formData.label = label;
          this.formData.options = options
            ? options.map((ele, index) => ({
                ...ele,
                timestamp: new Date().getTime() + index
              }))
            : [{ timestamp: new Date().getTime(), text: "" }];
          this.answer = this.alphabet.findIndex(ele => ele === answer);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.input-num-box {
  ::v-deep .el-input__inner {
    text-align: left;
  }
}
.type {
  width: 100px;
}
.content {
  width: 400px;
  margin: 0 10px;
}
</style>
