<template>
  <div class="app-container">
    <div class="grid-content bg-purple-light">
      <div class="seetingsDiv" style="">
        <div class="titleText">
          <div style="font-weight: 600;font-size: 16px;">{{TestPaperInfo.TestPaperTitle}}</div>
          <span style="margin-left: 30px;font-size: 14px;">总分：{{TestPaperInfo.TotalScore}}</span>
        </div>
        <el-button type="primary" @click="Add">添加题目
        </el-button>
      </div>
      <div class="areadiv" :style="{'height':TableColHeight+'px'}">
        <el-table :data="QuestList" id="QuestionTable" border
          style="width: 100%;border-radius: 5px;box-shadow: 0 0 10px #efefef;margin-top: 10px;margin-bottom: 40px;"
          :header-cell-class-name="headerStyle" :stripe='true' max-height="750">
          <el-table-column prop="date"  label="题号" width="80" align="center">
            <template slot-scope="scope">
              <span style="padding-left: 10px;">{{ scope.row.index }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="题型" width="100" align="center">
            <template slot-scope="scope">
              <span style="padding-left: 10px;" v-if="scope.row.subjectType==1">单选题</span>
              <span style="padding-left: 10px;" v-if="scope.row.subjectType==2">多选题</span>
              <span style="padding-left: 10px;" v-if="scope.row.subjectType==3">主观题</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="题目分数" width="80" align="center">
            <template slot-scope="scope">
              <span style="padding-left: 10px;">{{ scope.row.fraction }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="单项分数" width="80" align="center">
            <template slot-scope="scope">
              <span style="padding-left: 10px;">{{ scope.row.singleFraction }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="正确答案" width="80" align="center">
            <template slot-scope="scope">
              <span style="padding-left: 10px;">{{ scope.row.answer }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="题目" :show-overflow-tooltip='true'>
            <template slot-scope="scope">
              <!-- <el-button @click="messageDetail(scope.row.subject )">查看详情</el-button> -->
              <span style="padding-left: 10px;">{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="图片" width="160" align="center">
            <template slot-scope="scope">
              <div style="width:120px;margin: 0 auto;" v-if="scope.row.subjectImg">
                <img :src="'https://app.cehuimi.com'+scope.row.subjectImg" style="width: 100%;height: 100%;" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="解析" :show-overflow-tooltip='true'>
            <template slot-scope="scope">
              <span style="padding-left: 10px;">{{ scope.row.analysis }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="" width="120" align="center">
            <template slot-scope="scope">
              <el-dropdown @command="(e)=>{handleCommand(e,scope.row.id)}" style="padding-left: 10px;">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="update">编辑</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div style="clear: both;"></div>
      </div>
    </div>

    <!-- <el-dialog title="题目" :visible.sync="dialogClassIVIsibleT" @close="closeClassDialogT" width="700"
      :close-on-click-modal="false">
      <div style="margin-top: 40px;" v-html="message">

      </div>
    </el-dialog> -->


    <el-dialog title="编辑题目" :visible.sync="dialogsubjectlVisible" @close='closeDialog' width="800px"
      :close-on-click-modal="false">
      <el-form ref="Dataform" :model="Dataform" label-width="60px">
        <el-form-item label="题目">
          <el-input v-model="Dataform.subject" placeholder="请输入题目名称"></el-input>
          <!-- <tinymce v-if="dialogsubjectlVisible" ref="content" v-model="Dataform.subject " :height="350" /> -->
        </el-form-item>
        <el-form-item label="图片" style="padding-top: 5px;">

          <!-- <el-upload class="avatar-uploader" action="/api/Upload/upload"  :headers="header" :show-file-list="true"
            :on-success="handleAvatarSuccess" :on-remove="handleRemove">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload> -->

          <el-upload class="upload-demo" action="/api/Upload/upload" :on-preview="handlePreview" :headers="header"
            :on-remove="handleRemove" :file-list="fileList" :on-success='handleAvatarSuccess' :limit='1'
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>


          <!-- <el-cascader v-model="Dataform.QuestionClassId" style="width:400px" :props="{emitPath:false}" :clearable=true
            :options="QuestionClass">
          </el-cascader> -->
        </el-form-item>
        <el-form-item label="题型" style="padding-top: 5px;">
          <el-select v-model="Dataform.subjectType" value-key="Dataform.subjectType" @change="changeQuestionType"
            placeholder="请选择题型">
            <el-option label="单选题" :value="1"></el-option>
            <el-option label="多选题" :value="2"></el-option>
            <el-option label="主观题" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选项" v-show="OptionVisible">
          <el-table :data="subjectContent" :show-header="false">
            <el-table-column>
              <template slot-scope="scope">
                <el-input placeholder="请输入答案" v-model="scope.row.optionContent" class="optionInput">
                  <template slot="prepend">{{scope.row.option}}</template>
                </el-input>
                <i class="el-icon-circle-plus el-icon" @click="Addlist"></i>
                <i class="el-icon-remove el-icon" @click="RemoveList(scope)" v-if="scope.$index!=0"></i>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="答案" v-show="OptionVisible" class="subjectContentClass">
          <el-radio-group v-for="(item,i) in subjectContent" v-model="Dataform.answer" v-if="GroupVisible">
            <el-radio :label="item.option">{{item.option}}</el-radio>
          </el-radio-group>
          <el-checkbox-group v-for="(item,i) in subjectContent" v-model="Dataform.answer" v-if="!GroupVisible">
            <el-checkbox style="float: left;" :label="item.option">{{item.option}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <el-form-item label="分数" v-show="OptionVisible">
					<el-input-number :step="1" style="float: left;" :min="0" v-model="Dataform.fraction">
					</el-input-number>
					<div style="float: left;margin-left: 20px;" v-if="!GroupVisible">
						<label style="font-weight: bold;">单项分数：</label>
						<el-input-number :step="0.5" :max="Dataform.fraction/2" :min="0"
							v-model="Dataform.singleFraction">
						</el-input-number>
					</div>
				</el-form-item> -->
        <el-form-item label="解析" style="margin-top: 10px;">
          <el-input v-model="Dataform.analysis" :rows="5" type="textarea" placeholder="请输入答案解析" />
        </el-form-item>
      </el-form>
      <el-button @click="EditQuestionHeadler" style="margin: 10px 0 0 0;float:right" type="primary">确定
      </el-button>
      <div style="clear: both;"></div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
  import {
    getQuestionList,
    EditQuestion,
    getQuestionClassList,
    DelQuestionBankEvent,
    GetQuestionBankById,
    CreateQuestionClass,
    AddQuestionBankToTestPaper
  } from '@/api/QuestionBank'
  import {
    GetTestManagerByAdmin,
    DeleteTestPaperDetail
  } from '@/api/TestPaper'
  import {
    parseTime
  } from '@/utils/index.js'

  import Tinymce from '@/components/Tinymce'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    components: {
      Tinymce
    },
    filters: {},
    data() {
      return {
        randomQuestionTypeList:[],
        fileList: [],
        imageUrl: '',
        header: {
          Authorization: '',
        },
        parameter: {
          pageIndex: 1,
          pageSize: 12,
          sort: "id",
          sortOrder: 1,
          keyword: "",
          QuestionClassId: 0,
          status: 1
        },
        TestPaperInfo: {},
        Count: 0,
        QuestList: [],
        message: '',
        dialogsubjectlVisible: false,
        dialogClassIVIsible: false,
        dialogClassIVIsibleT: false,
        OptionVisible: true,
        GroupVisible: true,
        Dataform: {
          TestPaperId: this.$route.query.val,
          subject: "",
          subjectImg: '',
          subjectType: 1,
          subjectContent: "",
          QuestionClassId: 0,
          answer: [],
          analysis: "",
          fraction: 1,
          singleFraction: 1,
          state: 1
        },
        subjectContent: [{
          option: "A",
          optionContent: ""
        }],
        QuestionClass: [],
        QuestionClassInfo: {
          ParentId: 0,
          ClassificationName: "",
          Addtime: ""
        },
        TreeColHeight: 0,
        TableColHeight: 0,
        treeData: [{
          value: 0,
          label: "全部"
        }],
        CreatClassId: 0,
        value: ''
      }
    },
    created() {
      this.GetList();
      this.getQuestionClassListHeadler2();
      this.header.Authorization = getToken()
    },
    mounted() {
      // let ContentAreaHight = window.innerHeight - document.getElementById("elRow").offsetTop - 70;
      // this.TableColHeight = ContentAreaHight - document.getElementById("QuestionTable").offsetTop;
      // let lineNumber = this.TableColHeight - 50 - 20; //减去表头来计算
      // this.TreeColHeight = ContentAreaHight;
      // lineNumber = Math.floor(lineNumber / 49)
      // this.parameter.pageSize = lineNumber;
      // this.getQuestionClassListHeadler();
    },
    watch: {
      'Dataform.subjectType'(val) {
        if (val == 1 ) {
          // this.subjectContent = []
          if(4-this.subjectContent.length<0){
            this.subjectContent.pop()
          }else{
            for (let i = 0; i < 4-this.subjectContent.length; i++) {
            
              var alphabet = String.fromCharCode(64 + parseInt(this.subjectContent.length + 1));
              this.subjectContent.push({
                "option": alphabet,
                "title": ""
              });
            }
          }
          
        }
        if(val==2 ){
          // this.subjectContent = []
          for (let i = 0; i < 5-this.subjectContent.length; i++) {

            var alphabet = String.fromCharCode(64 + parseInt(this.subjectContent.length + 1));
            this.subjectContent.push({
              "option": alphabet,
              "title": ""
            });
          }
        }
      }
    },
    methods: {
      getSubTree(id, list) {
        let result = [];
        result = list.filter((t) => t.ParentId == id);
        if (result.length) {
          result = result.map((item) => {
            item.value = item.id;
            item.label = item.ClassificationName;
            item.children = this.getSubTree(item.id, list);
            if(!item.children || !item.children.length){
              delete item.children;
            }
            return item;
          });
        }
        return result;
      },
      getQuestionClassListHeadler2() {
        let _this = this;
        getQuestionClassList().then((res) => {
          let alllist = res.data.data;
          let list  = alllist.filter(t=>!t.ParentId);
          list = list.map((t) => {
            t.value = t.id;
            t.label = t.ClassificationName;
            t.children = this.getSubTree(t.id,alllist);
            if(!t.children || !t.children.length){
              delete t.children;
            }
            return t;
          });
          this.randomQuestionTypeList = list;
        });
      },
      handleRemove(file, fileList) {
        this.Dataform.subjectImg = ''

      },
      handlePreview(file) {
        console.log('file', file);
      },

      handleAvatarSuccess(res, file) {
        // this.imageUrl = URL.createObjectURL(file.raw);
        this.Dataform.subjectImg = res.data.data.Uri
      },
      messageDetail(val) {
        this.message = val
        this.dialogClassIVIsibleT = true
      },
      closeClassDialogT() {
        this.message = ''
        this.dialogClassIVIsibleT = false
      },
      //表格右边的操作按钮
      handleCommand(value, val) {
        this.value = value
        if (value == "update") {
          this.GetQuestionBankByIdHeadler(val);

        }
        if (value == "del") {
          this.DelQuestionBankEventHeadler(val);
        }
      },
      //添加分类
      // CreateQuestionClassHealder() {
      // 	this.QuestionClassInfo.Addtime = parseTime(new Date(), "");
      // 	CreateQuestionClass(this.QuestionClassInfo).then(res => {
      // 		alert(res.code)
      // 	})
      // },
      //获取选择的题目详细信息
      GetQuestionBankByIdHeadler(id) {
        GetQuestionBankById(id).then(res => {
          this.changeQuestionType(res.data.data.subjectType); //这里先初始化编辑显示内容
          this.Dataform = res.data.data; //内容赋值
          if (this.Dataform.subjectImg) {
            let data = {
              url: 'https://app.cehuimi.com' + this.Dataform.subjectImg
            }
            this.fileList.push(data)
          }
          // this.$nextTick(() => {
          //   this.$refs.content.setContent(this.Dataform.subject);
          // })
          this.subjectContent = JSON.parse(res.data.data.subjectContent); //赋值选项
          if (res.data.data.subjectType == 1) {
            this.Dataform.answer = res.data.data.answer.split(',')[0]; //赋值答案
            this.Dataform.singleFraction = 1
            this.Dataform.fraction = 1
          } else {
            this.Dataform.answer = res.data.data.answer.split(','); //赋值答案
            this.Dataform.singleFraction = 0.5
            this.Dataform.fraction = 2
          }
          this.dialogsubjectlVisible = true;

        });
      },
      showClassDialog(node) {
        this.dialogClassIVIsible = true;
        this.QuestionClassInfo.ParentId = node.data.value;
        alert(this.QuestionClassInfo.ParentId);
      },
      //关闭弹框的事件
      closeDialog() {
        //初始化数据
        // this.Dataform = this.$options.data().Dataform;
        // this.subjectContent = this.$options.data().subjectContent;
        this.Dataform = {
          TestPaperId: this.$route.query.val,
          subject: "",
          subjectType: 1,
          subjectContent: "",
          QuestionClassId: 0,
          answer: [],
          analysis: "",
          fraction: 1,
          singleFraction: 1,
          state: 1
        };
        this.subjectContent = [{
          option: "A",
          optionContent: ""
        }];
        //所有文本框恢复到初始化状态
        this.Dataform.answer = [];
        this.OptionVisible = true;
        this.GroupVisible = true;
        this.fileList = []
        // this.$nextTick(() => {
        //   this.$refs.content.setContent(this.Dataform.subject);
        // })
      },
      //选择题目类型来判断是否显示部分表单
      changeQuestionType(val) {
        if (val == 3) {
          this.OptionVisible = false;
        }
        if (val == 2) {
          this.OptionVisible = true;
          this.Dataform.answer = [];
          this.GroupVisible = false;
          this.Dataform.fraction = 2
          this.Dataform.singleFraction = 0.5
        }
        if (val == 1) {
          this.Dataform.answer = [];
          this.OptionVisible = true;
          this.GroupVisible = true;
          this.Dataform.fraction = 1
          this.Dataform.singleFraction = 1
        }
      },
      headerStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        return 'tableStyle'
      },
      Add() {
        this.dialogsubjectlVisible = true
        if (this.Dataform.subjectType == 1) {
          this.subjectContent = []
          for (let i = 0; i < 4; i++) {

            var alphabet = String.fromCharCode(64 + parseInt(this.subjectContent.length + 1));
            this.subjectContent.push({
              "option": alphabet,
              "title": ""
            });
          }
        }
        if(this.Dataform.subjectType == 2){
          this.subjectContent = []
          for (let i = 0; i < 5; i++) {

            var alphabet = String.fromCharCode(64 + parseInt(this.subjectContent.length + 1));
            this.subjectContent.push({
              "option": alphabet,
              "title": ""
            });
          }
        }
      },
      Addlist() {
        if (this.subjectContent.length < 5) {
          if (this.Dataform.subjectType == 1) {
            this.$confirm('单选题只支持4个答案！', '消息')
            return;
            // for(let i=0;i<3;i++){
            //   var alphabet = String.fromCharCode(64 + parseInt(this.subjectContent.length + 1));
            //   this.subjectContent.push({
            //     "option": alphabet,
            //     "title": ""
            //   });
            // }
          } else {
            var alphabet = String.fromCharCode(64 + parseInt(this.subjectContent.length + 1));
            this.subjectContent.push({
              "option": alphabet,
              "title": ""
            });
          }


        } else {
          this.$confirm('系统暂时只支持5个答案！', '消息')
        }
      },
      RemoveList(val) {
        this.subjectContent.splice(val.$index, 1);
        this.subjectContent.forEach((item, index) => {
          item.option = String.fromCharCode(64 + parseInt(index + 1));
        })
      },
      handleNodeClick(val) {
        this.parameter.QuestionClassId = val.value;
        this.parameter.pageIndex = 1;
        this.GetList();
      },
      DelQuestionBankEventHeadler(id) {
        this.$confirm('确定删除该试题？', '消息', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          callback: (action) => {
            if (action == "confirm") {
              let data = {
                TestPaperId: this.$route.query.val,
                QuestionID: id
              }
              DeleteTestPaperDetail(data).then(res => {
                if (res.data.code == 200) {
                  this.$confirm(res.data.message, '消息')
                  this.GetList();
                }
              });
            }
          },
        })
      },
      EditQuestionHeadler() {
        let reg = new RegExp('"', 'g');
        //this.Dataform.subjectContent = JSON.stringify(this.subjectContent).replace(reg, "\"");
        this.Dataform.subjectContent = this.subjectContent;
        if (typeof(this.Dataform.answer) != 'string') //判断是否为字符串
          this.Dataform.answer = this.Dataform.answer.join(',')
        var _this = this;
        if (this.value == 'update') {
          EditQuestion(this.Dataform).then(res => {
            if (res.data.code == 200) {
              _this.GetList();
              this.$message.success(res.data.message);
              setTimeout(function() {
                _this.dialogsubjectlVisible = false;
              }, 10)
            }
          });
        } else {
          AddQuestionBankToTestPaper(this.Dataform).then(res => {
            if (res.data.code == 200) {
              _this.GetList();
              this.$message.success('添加题目信息成功');
              setTimeout(function() {
                _this.dialogsubjectlVisible = false;
              }, 10)
            }
          });
        }
      },
      GetList() {
        let _this = this;
        let data = {
          TestPaperId: this.$route.query.val
        }

        GetTestManagerByAdmin(data).then(res => {
          _this.QuestList=res.data.data.TestPaperList.map((t,index)=>{
            t.index=index+1
            return t
          })
          _this.QuestList = _this.QuestList.sort((a, b) => {
            return b.id - a.id
          });
          _this.TestPaperInfo = res.data.data.TestPaperInfo
          // _this.Count = res.data.data.total;
          _this.$forceUpdate();
        });
      },
      currentchange(page) {
        this.parameter.pageIndex = page;
        this.GetList();
      },
      getQuestionClassListHeadler() {
        let _this = this;
        getQuestionClassList().then(res => {
          var gettree = function(titem) {
            titem.children = []
            let childrenList = res.data.data.filter(u => u.ParentId == titem.value);
            if (childrenList.length == 0)
              titem.children = undefined;
            res.data.data.filter(u => u.ParentId == titem.value).forEach((item, i) => {
              var model = {
                value: item.id,
                label: item.ClassificationName
              };
              gettree(model);
              titem.children.push(model);
            })
          }
          res.data.data.filter(u => u.ParentId == 0).forEach((item, i) => {
            var model = {
              value: item.id,
              label: item.ClassificationName
            };
            gettree(model);
            _this.QuestionClass.push(model);
            _this.treeData.push(model)
          })
        });
      }
    }
  }
</script>
<style scoped="scoped">
  /deep/.cell {
    padding-left: 0px;
  }

  /deep/.el-form-item {
    margin-bottom: 5px;
  }

  /deep/.el-radio {
    margin-right: 10px;
  }

  /deep/.el-radio__input.is-checked .el-radio__inner {
    border-color: #409EFF;
    background-color: #409EFF;
  }

  /deep/.el-radio__input.is-checked+.el-radio__label {
    color: #409EFF;
    font-weight: bold;
  }

  /deep/.tableStyle {
    background-color: #304156 !important;
    color: #fff;
    font-weight: 400;
  }

  .QuestDiv {
    width: 24%;
    float: left;
    min-height: 50px;
    border: 1px solid #CDCDCD;
    margin-right: 10px;
    box-shadow: 0 0 10px #808080;
    border-radius: 8px;
    min-height: 100px;
    background-color: #FFF;
    opacity: 0.8;
    margin-bottom: 10px;
    height: 313px;
  }

  .clear {
    clear: both;
    margin-bottom: 10px;
  }

  .font-color {
    background-color: #AE1E15 !important;
    color: #FFF;
    box-shadow: 0 0 5px #AE1E15;
  }

  /deep/.el-input-group__prepend {
    font-weight: bold;
    width: 30px;
    text-align: center;
    background: #409EFF;
    color: #FFF;
  }

  .optionInput {
    float: left;
    width: 620px !important;
  }

  .el-icon {
    font-size: 20px;
    line-height: 40px;
    margin: 0 5px;
    cursor: pointer;
    color: #409EFF !important;
  }

  >>>.subjectContentClass .el-checkbox__label {
    padding-right: 10px !important;
  }

  .seetingsDiv {
    width: 100%;
    height: 60px;
    background: #efefef;
    line-height: 60px;
    border-radius: 5px;
    box-shadow: 0 0 5px #cdcdcd;
    display: flex;
    justify-content: space-between;
    padding-left: 20px;
    padding-right: 20px;
  }

  .seetingsDiv button {
    background-color: #304156;
    border: 0px;
    margin-left: 10px;
    box-shadow: 0 0 5px #cdcdcd;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    height: 41px;
  }

  .areadiv {
    background-color: #efefef;
    border-radius: 5px;
    box-shadow: 0 0 5px #efefef;
  }

  .TreeHeader {
    background-color: #304156;
    height: 60px;
    border-radius: 5px;
    box-shadow: 0 0 10px #efefef;
    line-height: 60px;
    color: #FFF;
    padding-left: 10px;
  }

  .classbtn {
    float: right;
    margin: 11px 10px 0 0;
    height: 35px;
    line-height: 12px;
  }

  .eltree {
    background-color: #efefef;
  }

  /deep/.el-tree-node__content {
    min-height: 40px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 8px;
  }

  .titleText {
    display: flex;
    width: 230rpx;
  }

  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
