<template>
  <div ref="myBody" class="add-question flex">
    <div class="text flex">
      <div class="left">
        目前录入题目是第<span>{{ questionNextNum }}</span
        >道题
      </div>
      <div>
        <el-radio-group
          v-model="form.topicType"
          size="mini"
          @input="topicTypeChange"
        >
          <el-radio-button :disabled="checkLock" :label="1"
            >单选</el-radio-button
          >
          <el-radio-button :disabled="checkLock" :label="2"
            >多选</el-radio-button
          >
          <el-radio-button :disabled="checkLock" :label="3"
            >判断</el-radio-button
          >
        </el-radio-group>
      </div>
      <div class="right">{{ courseName }}</div>
    </div>

    <el-form class="form flex" ref="form" :model="form" label-width="auto">
      <!-- <div class="top flex"> -->
      <div>
        <el-form-item
          label="题目内容"
          prop="topicTitle"
          :rules="{
            required: true,
            message: '必须输入题目内容',
            trigger: ['blur', 'change'],
          }"
        >
          <el-input
            type="textarea"
            placeholder="多行输入"
            resize="none"
            rows="4"
            v-model="form.topicTitle"
            :disabled="checkLock"
          >
          </el-input>
        </el-form-item>
      </div>

      <div class="bottom">
        <!-- <el-form-item label="选项1" prop="title">
          <el-input v-model="form.title" placeholder="请输入"></el-input>
        </el-form-item> -->
        <el-form-item
          v-for="(question, index) in form.questions"
          :label="'选项' + (index + 1)"
          :key="question.key"
          :prop="'questions.' + index + '.value'"
          :rules="{
            required: true,
            message: '第一项不能为空不能为空',
            trigger: ['blur', 'change'],
          }"
        >
          <div class="add-select flex">
            <el-input
              type="textarea"
              placeholder="多行输入"
              style="flex: 1; margin-right: 10px"
              rows="2"
              v-model="question.value"
              :disabled="checkLock"
            ></el-input>
            <div class="flex algin-items">
              <div
                @click="rightAnswerClick(index)"
                class="right"
                :class="{ active: answerNum.indexOf(index) >= 0 }"
              >
                设为正确答案
              </div>
              <el-button
                size="mini"
                type="danger"
                v-if="index > 0 && form.topicType != 3"
                @click.prevent="removeDomain(question)"
                :disabled="checkLock"
                >删除</el-button
              >
            </div>
          </div>
        </el-form-item>

        <!-- <el-form-item
          class="noAttr"
          :label="`选项${form.questions.length + 1}`"
          prop=""
        >
          <div class="add-select flex">
            <el-input
              type="textarea"
              placeholder="多行输入"
              resize="none"
              rows="2"
              v-model="addValue"
              style="flex: 1; margin-right: 10px"
            >
            </el-input>
            <div class="flex algin-items">
              <div
                @click="rightAnswerClick(form.questions.length)"
                class="right"
                :class="{ active: answerNum === form.questions.length }"
              >
                设为正确答案
              </div> -->
        <div style="padding-left: 30px">
          <el-button
            size="mini"
            type="primary"
            @click.prevent="add(addValue)"
            :disabled="checkLock"
            >新增选项</el-button
          >
        </div>

        <!-- </div>
          </div>
        </el-form-item> -->
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  addQuestion,
  checkQuestion,
  changeQuestion,
  getQuestion,
  getLessonById,
} from "@/api/educationPlanExam/lessonsProgram.js";

export default {
  name: "AnswerLesson",
  props: {
    // visible: {
    //   type: Boolean,
    //   default: false,
    // },
    courseId: {
      type: Number,
    },
    topicId: {
      type: Number,
    },
    checkLock: {
      type: Boolean,
    },
  },
  components: {},
  data() {
    return {
      form: {
        topicType: 1,
        topicTitle: "",
        questions: [{ value: "" }, { value: "" }],
      },
      answerNum: [],
      addValue: "",
      // 录入的是第几道题
      questionNextNum: 1,
      courseName: "",
    };
  },

  created() {
    // 如果存在就是修改
    if (this.topicId) {
      checkQuestion(this.topicId).then((res) => {
        console.log(res.data);
        const data = res.data;
        this.form = {
          topicType: data.topicType,
          topicTitle: data.topicTitle,
          questions: JSON.parse(data.topicOption),
        };
        // this.answerNum = data.answer;
        this.answerNum = JSON.parse(data.answer);
      });
    }

    // 查询是第几道题
    this.getQuestion();
    // 获取课程标题
    this.getLessonById(this.courseId);
  },
  methods: {
    // 题目类型变化
    topicTypeChange(num) {
      if (num == 1) {
        this.answerNum = [];
      } else if (num == 2) {
        this.answerNum = [];
        // this.form.questions=[{ value: "" }, { value: "" }];
      } else {
        this.answerNum = [];
        const form = {
          topicType: 3,
          topicTitle: this.form.topicTitle,
          questions: [{ value: "对" }, { value: "错" }],
        };
        this.form = form;
      }
    },
    getQuestion() {
      getQuestion({ courseId: this.courseId }).then((res) => {
        // 如果是修改 就是原来的值,如果不是,就是总数+1
        console.log(res);
        if (this.topicId) {
          res.rows.forEach((item, index) => {
            if (item.topicId == this.topicId) {
              this.questionNextNum = index + 1;
            }
          });
        } else {
          this.questionNextNum = res.total + 1;
        }
      });
    },
    getLessonById(courseId) {
      getLessonById(courseId).then((res) => {
        console.log(res);
        this.courseName = res.data.courseName;
      });
    },
    addQuestion(data) {
      // 如果是修改,就用修改的方法,如果是新增,就用新增的方法
      if (this.topicId) {
        return changeQuestion({ topicId: this.topicId, ...data });
      } else {
        return addQuestion({ courseId: this.courseId, ...data });
      }
    },
    rightAnswerClick(index) {
      if (this.checkLock) return;
      if (this.form.topicType === 2) {
        const ind = this.answerNum.indexOf(index);
        if (ind < 0) {
          this.answerNum.push(index);
        } else {
          this.answerNum.splice(ind, 1);
        }
        this.answerNum = this.answerNum.sort((a, b) => {
          return a - b;
        });
        console.log(this.answerNum);
      } else {
        // 判断跟单选模式差不多
        this.answerNum = [index];
      }
    },
    // 删除选项
    removeDomain(question) {
      if (this.checkLock) return;
      const index = this.form.questions.indexOf(question);
      console.log(index);
      // 如果是正确答案,就让正确答案清空
      const ind = this.answerNum.indexOf(index);
      if (ind >= 0) {
        this.answerNum.splice(ind, 1);
      }
      // 如果是最后一位呗删除,那不用管,如果不是最后一位置,这一位删除之后,则这一位后面的所有数字都要-1;
      if (index != this.form.questions.length - 1) {
        this.answerNum = this.answerNum.map((item, i) => {
          if (item >= index) {
            return item - 1;
          } else {
            return item;
          }
        });
      }
      if (index >= 0) {
        this.form.questions.splice(index, 1);
      }
      console.log(this.answerNum);
      // console.log(this.form.questions)
    },
    // 删除选项
    // removeDomain(question) {
    //   const index = this.form.questions.indexOf(question);
    //   // 如果是正确答案,就让正确答案清空
    //   if (this.answerNum === index) {
    //     this.answerNum = null;
    //   }
    //   if (index >= 0) {
    //     this.form.questions.splice(index, 1);
    //   }
    // },
    // 新增选项
    add(addValue) {
      this.form.questions.push({ value: addValue });
      console.log();
    },
    save(num = 2) {
      return new Promise((resove) => {
        if (!this.answerNum && this.answerNum !== 0) {
          this.$message({
            message: "警告,请设置一个正确答案",
            type: "warning",
          });
          return resove(false);
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            const data = {};
            data.topicTitle = this.form.topicTitle;
            data.topicOption = JSON.stringify(this.form.questions);
            // data.answer = this.answerNum;
            data.answer = JSON.stringify(this.answerNum);
            data.topicType = this.form.topicType;
            this.addQuestion(data).then((res) => {
              if (res.code == 200) {
                // 把修改的这个归位,变成正常添加
                this.$emit("update:topicId", null);
                this.$message({
                  message: "添加题目成功",
                  type: "success",
                });
                this.$parent.$parent.componentsNumChange(num);
                this.$parent.$parent.$parent.getList();
                resove(true);
              }
            });
          }
        });
      });
    },

    saveAndNext() {
      this.save(3).then((res) => {
        if (res) {
          this.reset();
          // this.questionNextNum++;
          this.getQuestion();
        }
      });
    },
    reset() {
      this.form = {
        topicTitle: "",
        questions: [{ value: "" }, { value: "" }],
      };
      this.answerNum = [];
      this.addValue = "";
    },
  },
};
</script>
<style lang="scss" scoped>
.add-question {
  width: 100%;
  height: 550px;
  // overflow: hidden;
  flex-direction: column;
  padding-bottom: 7px;
  margin-bottom: 20px;
  border-bottom: 1px solid #bbbbbb;
  .form {
    flex: 1;
    flex-direction: column;
    height: 100%;
    .bottom {
      overflow-y: auto;
      height: 330px;
      box-sizing: border-box;

      .algin-items {
        align-items: center;
        width: 200px;
      }
      .right {
        display: inline-block;
        width: 133px;
        margin-right: 10px;
        line-height: initial;
        padding: 4px 0;
        border: 1px solid #bbbbbb;
        color: #101010;
        font-size: 12px;
        text-align: center;
        border-radius: 4px;
        box-sizing: border-box;
        cursor: pointer;
        &.active {
          background-color: #0bab0c;
          color: #ffffff;
        }
        &:hover {
          background-color: rgba(11, 171, 12, 0.5);
          color: #ffffff;
        }
      }
    }
  }
  .text {
    margin-top: 13px;
    margin-bottom: 34px;
    justify-content: space-between;
    height: 28px;
    .left {
      line-height: 28px;
      color: #101010;
      font-size: 14px;
    }
    .right {
      width: 411px;
      line-height: 28px;
      background: #1d84ff;
      padding-right: 5px;
      color: #fff;
      text-align: right;
    }
  }
}
</style>