<!--组卷-->
<style>
  .examCreat_Top {
    width: 100%;
    height: 30px;
    line-height: 30px;
    padding: 0 10px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ddd;
  }

  .examTi_List {
    border: 1px solid #ddd;
    margin-bottom: 20px;
  }

  .examCreat_Top i:hover {
    color: red;
    cursor: pointer;
  }

  .setpaperCreat {
    border: 1px dashed #E1E1E5;
    padding-top: 12px;
    border-radius: 4px;
    padding: 12px 4px 0 4px;
    margin: 20px 0 10px 68px;
  }

  .setpaperCreat span {
    display: inline-block;
    background: #F2F5FA;
    padding: 0 10px;
    height: 26px;
    line-height: 26px;
    border-radius: 14px;
    color: #181E33;
    margin-left: 10px;
    margin-bottom: 12px;
    font-size: 12px;
  }

</style>
<template>
  <div class="page-body">
    <div>
      组卷题库
      <q-btn color="accent" size="sm" @click="showQuestionBank" class="q-mr-md" label="选择题库"  /><br />
    </div>
    <div class="setpaperCreat" v-if="QuestionArray.length>0">
      <span v-for="(item,index) in QuestionArray" :key="index">{{item.BankName}}</span>
    </div>
    <q-btn color="accent" size="sm" style="margin-top:20px;"  @click="showExamTemplate"  class="q-mr-md"  label="选择模板"
        /><br />
    <br />
    <div class="row">
      <q-input filled stack-label maxlength="100" :dense="false" v-model="templateMsg.TemplateName"
        class="col-6 q-pb-lg q-pr-lg" label="试卷标题" />
      <q-input filled stack-label maxlength="5" @keyup.native="checkInteger(templateMsg,'TemplateScore')" :dense="false"
        v-model="templateMsg.TemplateScore" class="col-6 q-pb-lg" label="满分" />
    </div>
    <div class="row">
      <q-input filled stack-label maxlength="5" :dense="false" ref="TemplateNum" v-model="templateMsg.TemplateNum"
        class="col-6 q-pb-lg q-pr-lg" label="随机组卷数量" @keyup.native="checkInteger(templateMsg,'TemplateNum')"
        :rules="[val => !!val || '请填写随机组卷数量']" />
      <q-select filled option-value="Id" option-label="Name" :options="questionDifficultyTypeList" emit-value
        map-options label="难易程度" class="col-6" use-input clearable v-model="templateMsg.TemplateDifficultyType" />
    </div>
    <!-- 分割线<br /> -->
    <template v-if="templateMsg&&templateMsg.TemplateData&&templateMsg.TemplateData.length>0">
      <div v-for="(item,index) in templateMsg.TemplateData" :key="index" class="examTi_List">
        <div class="examCreat_Top">
          <span>{{item.QuestionTypeName}}</span> &nbsp;&nbsp;<i @click="delQuestion(templateMsg.TemplateData,index)"
            class="iconfont icon-img_delete_small"></i>
        </div>
        <div style="padding:0 20px 10px 20px;">
          <div class="row">
            <q-input filled stack-label maxlength="5" :dense="false" v-model="item.QuestionScore"
              class="col-6 q-pb-lg q-pr-lg" label="总分" @keyup.native="checkInteger(item,'QuestionScore')" />
            <q-input filled stack-label maxlength="100" :dense="false" v-model="item.QuestionDesc" class="col-6 q-pb-lg"
              label="题型说明" />
          </div>
          <span>
            <q-radio v-model="item.ChooseType" :val="1" label="从题库选题" />
            <template v-if="item.ChooseType==1">
              <span style="position:relative;top:2px;">共 {{item.QuestionTypeNum}} 道 抽
                <el-input style="width:100px;" size="small" :disabled="templateMsg.TemplateBankIds!=''&&item.QuestionTypeNum<=0"
                  @input="getMaxInput(item)" v-model="item.ChooseNum" @keyup.native="checkInteger(item,'ChooseNum')"
                  maxlength="5"></el-input>
                &nbsp;&nbsp;道</span>
            </template>
          </span>
          <br />
          <span>
            <q-radio v-model="item.ChooseType" :val="2" label="从题库按照难易度选题" />
            <template v-if="item.ChooseType==2">
              <div style="margin:0 0 20px 40px;" v-for="(subItem,subIndex) in item.ChooseList" :key="subIndex">
                {{subItem.DifficultyTypeName}} （共
                {{subItem.DifficultyTypeCount}} 道） 抽
                <el-input style="width:100px;" size="small" :disabled="templateMsg.TemplateBankIds!=''&&subItem.DifficultyTypeCount<=0"
                  @input="getMaxMiniInput(subItem)" @keyup.native="checkInteger(subItem,'ChooseNum')"
                  v-model="subItem.ChooseNum" maxlength="5"></el-input>
                &nbsp;&nbsp;道
              </div>
            </template>
          </span>
        </div>
      </div>
    </template>

    <div class="row">
      <q-select filled option-value="QId" option-label="Name" :options="questionTypeList" emit-value map-options
        label="更多题型" class="col-6 q-pr-lg" use-input clearable v-model="MoreQuestionTypeId" @input="changeQuestion" />
      <div class="row col-6" style="align-items:center;">
        <div class="col-6">
          <q-radio v-model="templateMsg.IsOpen" :val="1" label="私有" />
          <q-radio v-model="templateMsg.IsOpen" :val="2" label="公开" />
        </div>
        <div class="col-6">
          <q-checkbox v-model="templateMsg.IsSaveTemplate" label="同时保存为组卷模板" />
        </div>
      </div>
    </div>
    <br />
    <div class="row">
      <q-btn color="accent" size="sm" @click="setPaperTemplate" class="q-mr-md" label="保存" :loading="saveLoading" />
    </div>
    <questionbankForm v-if="isShowQuestionBank"  @close="closeExamForm"  @success="getBankData">
    </questionbankForm>
    <examtemplateForm v-if="isShowExamTemplate"  @close="closeExamForm"  @success="getTemplateData">
    </examtemplateForm>
  </div>
</template>
<script>
  import questionbankForm from '../../components/exam/questionbank-form'
  import examtemplateForm from '../../components/exam/examtemplate-form'
  import {
    queryQuestionTypeList,
    queryDifficultyType,
    queryQuestionCategoryList
  } from '../../api/question/question'
  import {
    savePaperInfo,
    savePaperTemplate
  } from '../../api/teacher/index';
  export default {
    components: {
      questionbankForm,
      examtemplateForm
    },
    meta: {
      title: "组卷"
    },
    data() {
      return {
        isShowQuestionBank: false, //是否显示题库列表
        isShowExamTemplate: false, //是否显示模板列表
        questionDifficultyTypeList: [], //难易程度列表
        //模板数据
        templateMsg: {
          TemplateId: 0, //模板编号
          TemplateName: "", //模板名称
          TemplateScore: 0, //模板分数
          TemplateNum: 0, //随机组卷数量
          TemplateDifficultyType: 1, //难易程度
          TemplateData: [],
          TemplateBankIds: "",
          IsSaveTemplate: false,
          ParentId: 0,
          IsOpen: 1 //(1-私有,2-开放)
        },
        ShowBankName: "", //显示题库名称
        BankList: [],
        MoreQuestionTypeId: "", //更多题型
        questionTypeList: [], //问题列表
        saveLoading: false,
        QuestionArray: []
      }
    },
    created() {
      if (this.$route.query && this.$route.query.ToParentId) {
        if (parseInt(this.$route.query.ToParentId) > 0) {
          this.templateMsg.ParentId = parseInt(this.$route.query.ToParentId);
        }
      }
      this.getQuestionType();
      this.getDifficultyType();
    },
    mounted() {

    },
    methods: {
      //设置最大值
      getMaxInput(item) {
        if (templateMsg.TemplateBankIds!=''&& item.ChooseNum > item.QuestionTypeNum) {
          item.ChooseNum = '';
        }
      },
      getMaxMiniInput(item) {
        if (templateMsg.TemplateBankIds!=''&&item.ChooseNum > item.DifficultyTypeCount) {
          item.ChooseNum = '';
        }
      },
      //获取题型列表
      getQuestionType() {
        queryQuestionTypeList({}).then(res => {
          if (res.Code == 1) {
            this.questionTypeList = res.Data;
          }
        });
      },
      //选择添加题型
      changeQuestion() {
        if (this.MoreQuestionTypeId && this.MoreQuestionTypeId != '') {
          //获取问题类型
          var qTypeObj = this.questionTypeList.find((item) => {
            return item.QId === this.MoreQuestionTypeId;
          });
          var newObj = this.createdTempObj();
          if (qTypeObj) {
            newObj.QuestionTypeId = qTypeObj.QId;
            newObj.QuestionTypeKey = qTypeObj.Key;
            newObj.QuestionTypeName = qTypeObj.Name;
          }
          //获取题库中的题型
          var chooseQuestion = this.BankList.find((item) => {
            return item.QuestionTypeId === this.MoreQuestionTypeId;
          });
          //题库中有此题型
          if (chooseQuestion) {
            newObj.QuestionTypeNum = chooseQuestion.QuestionTypeNum;
            newObj.ChooseList = chooseQuestion.ChooseList;
          }
          if (newObj && newObj.QuestionTypeId > 0) {
            if (!this.checkExists(newObj.QuestionTypeId)) {
              this.templateMsg.TemplateData.push(newObj);
            } else {
              this.$q.notify({
                type: 'negative',
                position: "top",
                message: `已存在此题型,请勿重复选择!`
              })
            }
          }
        }
      },
      //创建模板对象
      createdTempObj() {
        var newObj = {
          ChooseNum: 0,
          ChooseType: 1,
          QuestionDesc: "",
          QuestionScore: 0,
          QuestionTypeId: 0,
          QuestionTypeKey: "",
          QuestionTypeName: "",
          QuestionTypeNum: 0,
          ChooseList: [{
              DifficultyType: 1,
              DifficultyTypeName: "易",
              DifficultyTypeCount: 0,
              ChooseNum: 0
            },
            {
              DifficultyType: 2,
              DifficultyTypeName: "中",
              DifficultyTypeCount: 0,
              ChooseNum: 0
            },
            {
              DifficultyType: 3,
              DifficultyTypeName: "难",
              DifficultyTypeCount: 0,
              ChooseNum: 0
            }
          ]
        }
        return newObj;
      },
      //判断是否存在此题型
      checkExists(QuestionTypeId) {
        var isExists = false;
        if (this.templateMsg && this.templateMsg.TemplateData && this.templateMsg.TemplateData.length > 0) {
          this.templateMsg.TemplateData.forEach(item => {
            if (!isExists) {
              if (item.QuestionTypeId == QuestionTypeId) {
                isExists = true;
              }
            }
          })
        }
        return isExists;
      },
      //获取题库题目分类列表
      getQuestionCategoryList() {
        var qMsg = {
          QBankIds: this.templateMsg.TemplateBankIds
        }
        queryQuestionCategoryList(qMsg).then(res => {
          if (res.Code == 1) {
            var tempArray = res.Data;
            if (tempArray && tempArray.length > 0) {
              this.templateMsg.TemplateData = [];
              this.BankList = tempArray;
              tempArray.forEach(item => {
                //默认添加【单选题，多选题、填空题，单选题(数字)】
                if (item.QuestionTypeKey == 'single' || item.QuestionTypeKey == 'multiple' || item
                  .QuestionTypeKey == 'fill-in' || item.QuestionTypeKey == 'single-number') {
                  this.templateMsg.TemplateData.push(item);
                }
              })
            }
          }
        })
      },
      //获取问题难易程度列表
      getDifficultyType() {
        queryDifficultyType().then(res => {
          if (res.Code == 1) {
            this.questionDifficultyTypeList = res.Data;
          }
        });
      },
      //显示题库
      showQuestionBank() {
        this.isShowQuestionBank = true;
      },
      //显示试卷模板
      showExamTemplate() {
        // if (this.templateMsg.TemplateBankIds == '') {
        //   this.$q.notify({
        //     type: 'negative',
        //     position: "top",
        //     message: `请先选择题库`
        //   })
        //   return;
        // }
        this.isShowExamTemplate = true;
      },
      //关闭题库
      closeExamForm() {
        this.isShowQuestionBank = false;
        this.isShowExamTemplate = false;
      },
      //获取选择的题库
      getBankData(bankArray) {
        this.QuestionArray = bankArray;
        this.isShowQuestionBank = false;
        var qBankIds = "";
        var sBankName = "";
        if (bankArray && bankArray.length > 0) {
          bankArray.forEach(item => {
            qBankIds += "," + item.BankId;
            sBankName += "," + item.BankName;
          });
        }
        if (qBankIds.substr(0, 1) == ',') {
          qBankIds = qBankIds.substr(1);
        }
        if (sBankName.substr(0, 1) == ',') {
          sBankName = sBankName.substr(1);
        }
        this.templateMsg.TemplateBankIds = qBankIds;
        this.ShowBankName = sBankName;
        this.getQuestionCategoryList();
      },
      //获取模板数据
      getTemplateData(tempObj) {
        if (tempObj) {
          this.templateMsg.TemplateId = tempObj.TemplateId;
          this.templateMsg.TemplateName = tempObj.TemplateName;
          this.templateMsg.TemplateNum = tempObj.TemplateNum;
          this.templateMsg.TemplateScore = tempObj.TemplateScore;
          this.templateMsg.TemplateDifficultyType = tempObj.TemplateDifficultyType;
          this.templateMsg.TemplateData = [];
          var tempData = tempObj.TemplateData;
          if (tempData && tempData.length > 0) {
            tempData.forEach(item => {
              var newObj = this.createdTempObj();
              newObj.ChooseNum = item.ChooseNum;
              newObj.ChooseType = item.ChooseType;
              newObj.QuestionDesc = item.QuestionDesc;
              newObj.QuestionScore = item.QuestionScore;
              newObj.QuestionTypeId = item.QuestionTypeId;
              newObj.QuestionTypeKey = item.QuestionTypeKey;
              newObj.QuestionTypeName = item.QuestionTypeName;
              newObj.QuestionTypeNum = item.QuestionTypeNum;
              //获取题库中的题型
              var chooseQuestion = this.BankList.find((bItem) => {
                return bItem.QuestionTypeId === item.QuestionTypeId;
              });
              //题库中有此题型
              if (chooseQuestion) {
                newObj.QuestionTypeNum = chooseQuestion.QuestionTypeNum;
                newObj.ChooseList = chooseQuestion.ChooseList;
              }
              this.templateMsg.TemplateData.push(newObj);
            });
          }
        }
      },
      //根据模板生成试卷
      setPaperTemplate() {
        this.$refs.TemplateNum.validate()
        if (!this.$refs.TemplateNum.hasError) {
          let TotalNum = 0;
          for (let i = 0; i < this.templateMsg.TemplateData.length; i++) {
            if (this.templateMsg.TemplateData[i].ChooseType == 1 && this.templateMsg.TemplateData[i].ChooseNum === '') {
              this.$q.notify({
                type: 'negative',
                position: "top",
                message: `请填写第${i+1}题的抽取数`
              })
              return
            }
            TotalNum += parseInt(this.templateMsg.TemplateData[i].QuestionScore);
          }
          if (TotalNum > this.templateMsg.TemplateScore) {
            this.$q.notify({
              type: 'negative',
              position: "top",
              message: `题目总分之和大于满分`
            })
            return
          }
          this.saveLoading = true;
          savePaperTemplate(this.templateMsg).then(res => {
            this.saveLoading = false;
            if (res.Code == 1) {
              this.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: '创建试卷成功!',
                position: 'top'
              })
              this.$router.push({
                path: '/exam/examPaper',
                query: {}
              });
            } else {
              this.$q.notify({
                type: 'negative',
                position: "top",
                message: `操作失败!`
              })
            }
          });
        }
      },
      //删除
      delQuestion(item, index) {
        this.$q.dialog({
          title: '提示信息',
          message: "是否确定删除?",
          cancel: true,
          persistent: true,
          ok: "确定",
          cancel: "取消",
        }).onOk(() => {
          item.splice(index, 1);
        }).onCancel(() => {});
      }
    }
  }

</script>
