<template class="choose_wrap">
  <div>
    <!-- <div class="choose" @click="qsShow = true">试 题 录 入</div> -->
    <el-drawer
      title="添加题目"
      :visible.sync="qsShow"
      :modal="true"
      :show-close='false'
      size="50%"
    >
      <template v-slot:title>
        <div style='font-size: 20px;margin-bottom: 10px;display: flex;justify-content: space-between;'>
          <span>添加题目</span>
          <span><i @click="closeQs" class="el-icon-close"></i></span>
        </div>
        <div style="border-bottom: 1px #ccc solid; margin-bottom: 20px;text-align: left;">
          <el-button
            type="primary"
            class="from_btn"
            @click="addTopic('select')"
            >新增选择题</el-button
          >
          <el-button
            type="primary"
            class="from_btn"
            @click="addTopic('short')"
            >新增简答题</el-button
          >
        </div>
      </template>

      <div class="dialog_height" :style="{'height':dialog_height+'px'}">
        <div class="from_box" v-for="(item, index) in topicList" :key="index">
          <el-form
            :model="item.qsForm"
            ref="qsForm"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item
              prop="title"
              label="题目"
              :rules="[
                {
                  required: true,
                  message: '请输入题目',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                type="textarea"
                v-model="item.qsForm.title"
                style="width: 320px"
              ></el-input>
            </el-form-item>
            <template v-if="item.qsForm.type=='select'">
              <el-form-item
                v-for="(domain, index) in item.qsForm.domains"
                :label="sortList[index]"
                :key="domain.key"
                :prop="'domains.' + index + '.value'"
                :rules="{
                  required: true,
                  message: '选项不能为空',
                  trigger: 'blur',
                }"
              >
                <el-input
                  v-model="domain.value"
                  style="width: 320px; margin-right: 10px"
                ></el-input
                ><el-button
                  @click.prevent="removeDomain1(domain, item)"
                  icon="el-icon-delete"
                ></el-button>
              </el-form-item>
              <el-form-item
                prop="answer"
                label="正确答案"
                :rules="[
                  {
                    required: true,
                    message: '请输入正确答案',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="item.qsForm.answer"
                  placeholder="请选择"
                  clearable
                  multiple

                  style="width: 320px"
                >
                  <el-option
                    v-for="i in item.qsForm.sortListfor"
                    :key="i"
                    :label="i"
                    :value="i"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              </template>
              <el-form-item>
                <el-button
                  v-if="item.qsForm.type=='select'"
                  type="primary"
                  @click="addDomain1(item)"
                  >新增选项</el-button>
                <el-button
                  type="danger"
                  @click="remove_dom(item)"
                  >删除题目</el-button
                >
              </el-form-item>

          </el-form>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button @click="closeQs">取 消</el-button>
        <el-button type="primary" @click="submitForm('qsForm')"
          >提 交</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  //dialogType：区分考试和模拟
  props: ["dialogType"],
  data() {
    return {
      qsShow: false,
      dialog_height:0,
      //录入的题目等信息
      topicList: [
        {
          //唯一识别码，当前时间戳
          key: Date.now(),
          //题目信息
          qsForm: {
            //选项
            domains: [
              {
                id: "A",
                value: "",
              },
              {
                id: "B",
                value: "",
              },
              {
                id: "C",
                value: "",
              },
            ],
            //题目
            title: "",
            //正确答案
            answer: [],
            //默认下拉框选项
            sortListfor: ["A", "B", "C"],
            //类型
            type: 'select',
            type_name:''
          },
        },
      ],
      //每个选项的id
      uid: "",
      //每个选项的排序号
      sortList: ["A", "B", "C", "D", "E", "F", "G", "H"],
    };
  },
  created() {
    this.initHeight()
  },
  methods: {
    initHeight(){
      let clientHeight = document.documentElement.clientHeight;
      let titleHeight = 136
      let footerHeight = 60
      this.dialog_height =clientHeight-titleHeight - footerHeight - 30;
      console.log(clientHeight,this.dialog_height)
    },
    closeQs(){
      this.qsShow=false
      this.topicList=[
        {
          //唯一识别码，当前时间戳
          key: Date.now(),
          //题目信息
          qsForm: {
            //选项
            domains: [
              {
                id: "A",
                value: "",
              },
              {
                id: "B",
                value: "",
              },
              {
                id: "C",
                value: "",
              },
            ],
            //题目
            title: "",
            //正确答案
            answer: [],
            //默认下拉框选项
            sortListfor: ["A", "B", "C"],
            //类型
            type: 'select',
            type_name:''
          },
        },
      ]
    },
    //弹框内新增选项
    addDomain1(item) {
      //item：题目
      //先拿到题目的角标
      let index = this.topicList.indexOf(item);
      //保存一下题目选项的长度，用来下面判断用
      let listLength =
        this.topicList[index].qsForm.domains.length + 1;
      //判断：题目选项的长度超过6个了就不能继续添加了，并提示上限
      if (listLength > 6) {
        this.$message({
          message: "答题选项最多设置6条",
          type: "warning",
        });
        return;
      } else {
        //需要拿到对应的id添加到新创建的选项中，所以直接对题目选项筛选
        this.topicList[index].qsForm.domains.filter(
          (item, index) => {
            //判断：当前已有的每一项选项的id和我们提前设置的排序号数组按顺序对比是否一致，一致的不管，当按顺序比到最后一个的时候，我们用角标+1的方式，拿到后面的一个字母，用来当id
            if (item.id == this.sortList[index]) {
              this.uid = this.sortList[index + 1];
            }
          }
        );
        //添加选项时，同时往下拉框内添加选项，添加的是序列号数组的角标对应位置数据。
        this.topicList[index].qsForm.sortListfor.push(
          this.sortList[listLength - 1]
        );
        //按照id和value的格式把新的一个选项添加进选项数组内
        this.topicList[index].qsForm.domains.push({
          id: this.uid,
          value: "",
        });
      }
    },
    //两个参数，arr：题目数组，index：角标。传入两个参数用来在删除选项的时候把每个选项的id从新排列，避免混乱
    delOne(arr, index) {
      arr.splice(index, 1),
        arr.forEach((ele, key) => {
          ele.id = this.sortList[key];
        });
      return arr;
    },
    //弹框删除选项
    removeDomain1(i, item) {
      //i：选项数据
      //item：题目
      //先拿到传来的题目在数组中的角标
      let index = this.topicList.indexOf(item);
      let listLength =
        this.topicList[index].qsForm.domains.length - 1;
      if (listLength < 2) {
        this.$message({
          message: "答题选项最少需要设置2条",
          type: "warning",
        });
        return;
      } else {
        //然后利用角标在数组中对应的题目中找到这一条选项的角标
        let indexs =
          this.topicList[index].qsForm.domains.indexOf(i);
        //判断选项角标是否存在
        if (indexs !== -1) {
          //存在，就删除对应题目的对应一条选项数据
          let L = this.topicList[index].qsForm.domains;
          let v = this.delOne(L, indexs);
          console.log("新数组:", v);
          //并把下拉框选中的清空
          this.topicList[index].qsForm.answer = [];
          //并删除下拉框选项数据的最后一位
          this.topicList[index].qsForm.sortListfor.pop();
        }
      }
    },
    //弹框删除题目
    remove_dom(item) {
      //查找点击删除的这一项的角标,保存
      let index = this.topicList.indexOf(item);
      //判断有没有在题目数组内找到，-1代表没找到
      if (index !== -1) {
        //找到了就删除这一条题目
        this.topicList.splice(index, 1);
      }
    },
    //弹框增加题目
    addTopic(types) {
      //点击增加，按照格式新增一个对象
      if(types=='select'){
        this.topicList.push({
          key: Date.now(),
          qsForm: {
            domains: [
              {
                id: "A",
                value: "",
              },
              {
                id: "B",
                value: "",
              },
              {
                id: "C",
                value: "",
              },
            ],
            title: "",
            answer: [],
            sortListfor: ["A", "B", "C"],
            type:'select',
            type_name:''
          },
        });
      }else if(types=='short'){
        this.topicList.push({
          key: Date.now(),
          qsForm: {
            domains: [],
            title: "",
            answer: [],
            sortListfor: [],
            type:'short',
            type_name:''
          },
        });
      }

    },
    //提交按钮
    submitForm(formName) {
      //用来记录验证通过的题目数量
      let n = 0;
      //提交时，循环题目数组
      this.topicList.forEach((item, index) => {
        //formName：ref绑定的表单dom传参进去
        //循环表单内的每一项题目是否通过验证，验证规格写在了html标签上的rules就是
        this.$refs[formName][index].validate((valid) => {
          if (valid) {
            //通过验证的n+1,这里计数用来判断是不是所有题都通过验证了
            n++;
            //判断这个题目数组的长度和n一致，那么验证成功数和数组长度一致，也就是全部验证成功。
            if (n == this.topicList.length) {
              //全部验证通过执行方法：
              //把所有的题目遍历判断一下，当选择的答案大于一个的时候就把type改成多选题，反之单选
              this.topicList.forEach(i=>{
                if(i.qsForm.type=='select'){
                  i.qsForm.type_name=i.qsForm.answer.length>1?"多选题":"单选题"
                }else if(i.qsForm.type=='short'){
                  i.qsForm.type_name = '简答题'
                }
              })
              this.$emit('submitQs',this.topicList)
              this.qsShow = false
              console.log(this.topicList);
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
    },
  },
};
</script>

<style scoped lang='scss'>
  ::v-deep .el-drawer__wrapper{
    padding:20px 0;
    padding-right:10px;
  }
  ::v-deep .el-drawer__header{
    display: block!important;
    margin-bottom:0
  }
.choose {
  width: 300px;
  height: 200px;
  margin: auto;
  margin-top: 180px;
  text-align: center;
  line-height: 200px;
  font-size: 38px;
  color: #fff;
  font-weight: bold;
  border-radius: 30px;
  cursor: pointer;
  background-image: linear-gradient(#32cbc6, #2d94a7);
  margin-bottom: 25px;
  box-shadow: 0px 0px 15px 5px #97d9e1;
}
.choose:hover {
  background-image: linear-gradient(#0093e9, #2d94a7);
  box-shadow: 0px 0px 15px 5px #0093e9;
}
.from_box {
  border-bottom: 1px #ccc solid;
  margin-bottom: 20px;
}
.el-form-item{
  margin-bottom:10px;
}
.from_btn {
  margin-left: 10px;
  margin-bottom: 10px;
}
.dialog_height {
  /* height: 430px; */
  overflow: auto;
}
.dialog-footer{
      position: fixed;
      bottom: 35px;
      right: 20px;
}
</style>
<style >
.choose_wrap .el-dialog {
  border-radius: 20px;
}
</style>
