<template>
  <div>
    <el-dialog
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="title + '题目'"
      :visible="visible"
      custom-class="bbsl-location-dialog"
      top="5vh"
      width="60%"
    >
      <div class="dialog-content">
        <el-form
          ref="formInfo"
          :model="params"
          :rules="rules"
          label-position="top"
          label-width="150px"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="课目" prop="subId">
                <el-select
                  v-model="subject"
                  placeholder="请选择课目"
                  style="width:80%"
                  v-on:click.native="subjectDUsers"
                >
                  <el-option
                    v-for="(item, index) in subjectList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <!-- 	<el-cascader v-model="params.subId" :options="subjectlist" clearable filterable
									:props="{ value: 'id', label: 'name', checkStrictly: true }" style="width: 100%"
									@change="handleChange">
								</el-cascader> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="难度" prop="difficulty">
                <el-select
                  v-model="params.difficulty"
                  placeholder="请选择难度"
                  style="width:100%"
                >
                  <el-option
                    v-for="item in difficultyList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="参考分数" prop="score">
                <el-input
                  v-model="params.score"
                  placeholder="请输入参考分数"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item label="评卷方式" prop="markType">
								<el-select v-model="params.markType" placeholder="请选择评卷方式" style="width:100%">
									<el-option v-for="item in markTypeList" :label="item.name" :value="item.value"
										:key="item.value"></el-option>
								</el-select>
							</el-form-item> -->
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col>
              <el-form-item prop="type">
                <div style="display: flex;">
                  <div
                    v-for="(item, index) in typeList"
                    :key="index"
                    :class="{btnActive: params.type == item.value}"
                    class="typeBtn"
                    @click="topicType(item)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col>
              <el-form-item prop="question">
                <!-- <el-input @focus='focus("t")' placeholder="请输入考试题目" v-if="!focusNum"></el-input> -->
                <div class="quill-editor">
                  <!--富文本编辑器组件-->
                  <quill-editor
                    ref="QuillEditor"
                    v-model="params.question"
                    :content="params.question"
                    :options="editorOption"
                    @blur="onEditorBlur($event)"
                    @change="onEditorChange"
                    @focus="onEditorFocus($event)"
                    @ready="onEditorReady($event)"
                  ></quill-editor>
                  <!-- 图片上传组件辅助-->
                  <el-upload
                    :accept="acceptImg"
                    :action="uploadUrl"
                    :before-upload="beforeUpload"
                    :headers="header"
                    :on-success="qeuploadSuccess"
                    :show-file-list="false"
                    class="avatar-qeuploader"
                    name="img"
                    style="height: 0;"
                  ></el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="params.type == '1' || params.type == '2'" :gutter="24">
            <el-col>
              <!-- 单选 -->
              <el-radio-group
                v-if="params.type == '1'"
                v-model="params.rightOption"
              >
                <el-radio
                  v-for="(item, index) in params.options"
                  :key="index"
                  :label="item.optionKey"
                >
                  {{ item.optionKey }}、
                  <el-input
                    v-model="item.optionContent"
                    placeholder="请输入选项"
                    style="width: 100%;"
                  >
                  </el-input>
                </el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group
                v-if="params.type == '2'"
                v-model="params.rightOption"
              >
                <el-checkbox
                  v-for="(item, index) in params.options"
                  :key="index"
                  :label="item.optionKey"
                >
                  {{ item.optionKey }}、
                  <el-input
                    v-model="item.optionContent"
                    placeholder="请输入选项"
                    style="width: 100%;"
                  >
                  </el-input>
                </el-checkbox>
              </el-checkbox-group>
              <div v-if="params.type == '1' || params.type == '2'">
                <span style="color: red;">*</span>
                请勾选正确答案
                <div style="text-align: center;">
                  <el-button size="mini" @click="generateBig()">添加</el-button>
                  <!-- <i class="el-icon-circle-plus" @click="generateBig()"></i>
									<i class="el-icon-remove" @click="deleteOption()"></i> -->
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col
              v-if="
                params.type == '3' ||
                  params.type == '4' ||
                  params.type == '5' ||
                  params.type == '7'
              "
            >
              <el-form-item label="正确答案" prop="rightOption">
                <!-- 单选 -->
                <el-radio-group
                  v-if="params.type == '1'"
                  v-model="params.rightOption"
                >
                  <el-radio
                    v-for="(item, index) in params.options"
                    :key="index"
                    :label="item.optionKey"
                    >{{ item.optionKey }}
                  </el-radio>
                </el-radio-group>
                <!-- 多选 -->
                <el-checkbox-group
                  v-if="params.type == '2'"
                  v-model="params.rightOption"
                >
                  <el-checkbox
                    v-for="(item, index) in params.options"
                    :key="index"
                    :label="item.optionKey"
                  >
                    {{ item.optionKey }}
                  </el-checkbox>
                </el-checkbox-group>
                <!-- 判断 -->
                <el-radio-group
                  v-if="params.type == '3'"
                  v-model="params.rightOption"
                >
                  <el-radio label="1">对</el-radio>
                  <el-radio label="0">错</el-radio>
                </el-radio-group>
                <!-- 填空 -->
                <el-input
                  v-if="params.type == '4'"
                  v-model="params.rightOption"
                  placeholder="请输入正常答案"
                >
                </el-input>
                <el-input
                  v-if="params.type == '5' || params.type == '7'"
                  v-model="params.rightOption"
                  placeholder="请输入正常答案"
                  type="textarea"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col>
              <el-form-item label="题目解析" prop="parsing">
                <el-input
                  v-model="params.parsing"
                  placeholder="请输入题目解析"
                  type="textarea"
                ></el-input>
                <!-- <div class="quill-editor" v-if="focusJ">
									<quill-editor v-model="params.parsing" :content="params.parsing"
										:options="editorOption" @blur="onEditorBlur($event)"
										@focus="onEditorFocus($event)" @ready="onEditorReady($event)"
										@change="onEditorChange" ref="QuillEditor">
									</quill-editor>
									<el-upload name="img" class="avatar-qeuploader" :action="uploadUrl"
										style="height: 0;" :show-file-list="false" :on-success="qeuploadSuccess"
										:before-upload="beforeUpload" :headers="header" :accept="acceptImg"></el-upload>
								</div> -->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave(1)">继续添加</el-button>

        <el-button @click="handleSave(2)">确认</el-button>
        <!-- <el-button @click="handleClose">取 消</el-button> -->
      </span>
    </el-dialog>
    <subjectDialog ref="subjectDialog" @getUser="getUser"></subjectDialog>
  </div>
</template>

<script>
import questionListMenu from '@/api/examination/questionListMenu.js'
import dictUtils from '@/components/dict/DictSelectUtils.js'
import subjectDialog from './subjectDialog.vue'
import {mapState} from 'vuex'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {quillEditor} from 'vue-quill-editor'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
  ['blockquote', 'code-block'], //引用，代码块
  [
    {
      header: 1
    },
    {
      header: 2
    }
  ], // 几级标题
  [
    {
      list: 'ordered'
    },
    {
      list: 'bullet'
    }
  ],
  // 字体大小
  [
    {
      header: [1, 2, 3, 4, 5, 6, false]
    }
  ], // 标题
  [
    {
      color: []
    }
  ], // 颜色选择

  ['clean'], // 清除样式,
  ['link', 'image'] // 上传图片、上传视频
]
export default {
  name: 'questionListMenuDialog',
  components: {
    quillEditor,
    subjectDialog
  },
  data() {
    return {
      visible: false,
      uploadUrl: window.context.portal + '/file/v1/uploadFileForConfig', // 服务器上传地址
      acceptImg: '.jpg,.jpeg,.png,.JPG,.JPEG,.gif,.PNG,.GIF',
      params: {
        difficulty: '',
        memo: '',
        options: [
          {
            optionContent: '',
            optionKey: 'A'
          },
          {
            optionContent: '',
            optionKey: 'B'
          },
          {
            optionContent: '',
            optionKey: 'C'
          },
          {
            optionContent: '',
            optionKey: 'D'
          }
        ],
        parsing: null,
        question: '',
        rightOption: '',
        subId: '',
        type: ''
      },
      title: '',
      subject: '',
      subjectList: [],
      //难度
      difficultyList: [],
      // 评卷方式
      focusNum: false,
      focusJ: false,
      rules: {
        subId: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ]
      },
      // 富文本配置
      editorOption: {
        placeholder: '请输入题目',
        theme: 'snow', //主题 snow/bubble
        modules: {
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                  // 调用element的图片上传组件
                  document.querySelector('.avatar-qeuploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  created() {
    // 难度
    this.difficultyList = dictUtils.getDictItemsFromCache('stnd')
    //题目类型
    this.typeList = dictUtils.getDictItemsFromCache('sttx')
    console.log(this.typeList)
    //评卷方式
    // this.markTypeList = dictUtils.getDictItemsFromCache('pjfs')
  },
  computed: mapState({
    header: state => {
      return {
        Authorization: `Bearer ${state.login.currentUser.token}`
      }
    }
  }),
  mounted() {},
  methods: {
    add(id, list) {
      console.log(id, list)
      this.title = '新增'
      this.visible = true
      this.subjectList = []
      this.subject = []
      if (id.length > 0 && list.length > 0) {
        this.subjectList.push({
          id: list[0].id,
          name: list[0].name
        })
        this.subject = list[0].id
      }
      this.params.difficulty = this.difficultyList[0].value
      this.params.type = this.typeList[0].value
      // this.params.markType = this.markTypeList[0].value
    },
    edit(val) {
      questionListMenu.detailId(val.id, res => {
        if (res) {
          this.params = res
          this.focusNum = true
          this.focusJ = true
          this.params.options.map(e => {
            e.focusNum = true
          })
          if (this.params.type == 2) {
            this.params.rightOption = this.params.rightOption.split(',')
          }
          this.subjectList.push({
            id: this.params.subId,
            name: this.params.subjectName
          })
          this.subject = this.params.subId
          this.title = '修改'
          this.visible = true
        }
      })
    },
    //打开课目弹框
    subjectDUsers() {
      this.$refs.subjectDialog.add(this.subjectList)
    },
    // 课目树选中ID
    handleChange(val) {
      let ArrIds = []
      ArrIds = val
      if (ArrIds.length == 0) {
        this.params.subId = ArrIds[0]
      } else {
        this.params.subId = ArrIds[val.length - 1]
      }
    },
    focus(val, index) {
      console.log(1)
      if (val == 't') {
        this.focusNum = true
      } else if (val == 'j') {
        this.focusJ = true
      } else {
        val.focusNum = true
        this.$set(this.params.options, index, this.params.options[index])
      }
    },
    getUser(val) {
      console.log(val)
      this.subjectList = []
      this.subject = val.id

      this.$set(this.subjectList, 0, val)
      console.log(this.subjectList)
    },
    generateBig() {
      var ch_big = 'A'
      var str_big = ''
      for (var i = 0; i < 26; i++) {
        str_big += String.fromCharCode(ch_big.charCodeAt(0) + i)
      }
      this.params.options.push({
        optionKey: str_big[this.params.options.length],
        optionContent: '',
        focusNum: true
      })
    },
    //删除选择
    deleteOption(index) {
      if (index > 0) {
        this.params.options.splice(index, 1)
      }
    },
    // 关闭新增人员窗口
    handleClose() {
      this.focusNum = false
      this.focusJ = false
      this.params = {
        difficulty: '',
        groupFlag: '',
        // markType: "",
        memo: '',
        options: [
          {
            optionContent: '',
            optionKey: 'A'
          },
          {
            optionContent: '',
            optionKey: 'B'
          },
          {
            optionContent: '',
            optionKey: 'C'
          },
          {
            optionContent: '',
            optionKey: 'D'
          }
        ],
        parsing: '',
        question: '',
        rightOption: '',
        subId: '',
        type: ''
      }
      this.subjectList = []
      this.subject = ''
      this.visible = false
      this.$emit('loadData')
    },
    topicType(val) {
      if (this.params.question != '') {
        this.$confirm(
          '您确定要修改题目类型吗？切换后原有的题目将清空',
          '温馨提示',
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          }
        )
          .then(() => {
            this.params.type = val.value
            this.focusNum = false
            this.focusJ = false
            this.params.question = ''
            this.params.parsing = ''
            if (this.params.type == 2) {
              this.params.rightOption = []
            } else {
              this.params.rightOption = ''
            }
            if (this.params.type == '1' || this.params.type == '2') {
              this.params.options = [
                {
                  optionContent: '',
                  optionKey: 'A'
                },
                {
                  optionContent: '',
                  optionKey: 'B'
                },
                {
                  optionContent: '',
                  optionKey: 'C'
                },
                {
                  optionContent: '',
                  optionKey: 'D'
                }
              ]
              this.$set(this.params.options)
            } else {
              this.params.options = []
            }
          })
          .catch(() => {})
      } else {
        this.params.type = val.value
        this.focusNum = false
        this.focusJ = false
        this.params.question = ''
        this.params.parsing = ''
        if (this.params.type == 2) {
          this.params.rightOption = []
        } else {
          this.params.rightOption = ''
        }
        if (this.params.type == '1' || this.params.type == '2') {
          this.params.options = [
            {
              optionContent: '',
              optionKey: 'A'
            },
            {
              optionContent: '',
              optionKey: 'B'
            },
            {
              optionContent: '',
              optionKey: 'C'
            },
            {
              optionContent: '',
              optionKey: 'D'
            }
          ]
          this.$set(this.params.options)
        } else {
          this.params.options = []
        }
      }
    },
    // 保存
    handleSave(val) {
      this.typeList.forEach(item => {
        if (item.name == this.params.type) {
          this.params.type = item.value
        }
      })
      if (typeof this.params.rightOption == 'object') {
        this.params.rightOption = this.params.rightOption.toString()
      }
      this.params.subId = this.subject
      this.$refs.formInfo.validate(valid => {
        if (valid) {
          let method
          if (this.title === '新增') {
            method = questionListMenu.addQuestions
          }
          if (this.title === '修改') {
            method = questionListMenu.editQuestions
          }
          console.log(this.params)
          method(this.params, response => {
            if (response.state) {
              this.$notify({
                type: 'success',
                message: this.title + '成功',
                duration: 2000
              })
              if (val == 1) {
                if (['1', '2'].includes(this.params.type)) {
                  this.params.options = [
                    {
                      optionContent: '',
                      optionKey: 'A'
                    },
                    {
                      optionContent: '',
                      optionKey: 'B'
                    },
                    {
                      optionContent: '',
                      optionKey: 'C'
                    },
                    {
                      optionContent: '',
                      optionKey: 'D'
                    }
                  ]
                } else {
                  this.params.options = []
                }

                this.params.parsing = ''
                this.params.question = ''
                if (this.params.type == 2) {
                  this.params.rightOption = []
                } else {
                  this.params.rightOption = ''
                }
              } else if (val == 2) {
                this.handleClose()
              }
            } else {
              this.$message.warning(response.message)
            }
          })
        }
      })
    },
    //继续添加
    continueAdd() {},
    qeuploadSuccess(res) {
      // 获取富文本组件实例
      let quill = this.$refs.QuillEditor.quill
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let fileId = res.fileId
        let url = this.previewUrl + fileId
        let length = quill.getSelection().index
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
        this.$message.error('图片插入失败！')
      }
    },
    beforeUpload(file) {
      return true
    },
    // 失去焦点
    onEditorBlur(editor) {},
    // 获得焦点
    onEditorFocus(editor) {},
    // 开始
    onEditorReady(editor) {},
    // 值发生变化
    onEditorChange(editor) {}
  }
}
</script>
<style>
.ql-toolbar.ql-snow {
  padding: 0 !important;
}
</style>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 100% !important;
  max-height: 80%;
}

::v-deep .el-dialog {
  height: 80% !important;
}

::v-deep .el-radio-group {
  width: 100%;
}

::v-deep .el-radio {
  width: 95%;
  display: flex;
  align-items: center;
  margin: 10px 0;
}

::v-deep .el-radio__label {
  width: 100%;
}

::v-deep .el-checkbox-group {
  width: 100%;
}

::v-deep .el-checkbox {
  width: 95%;
  display: flex;
  align-items: center;
  margin: 10px 0;
}

::v-deep .el-checkbox__label {
  width: 100%;
}

.typeBtn {
  width: 80px;
  height: 40px;
  border: 1px solid #dcdfe6;
  text-align: center;
  border-radius: 3px;
  margin-right: 5px;
}

.btnActive {
  background-color: #1289fe;
  color: #fff;
}

.el-message-box {
  position: absolute;
  top: 20%;
  left: 40%;
}

.options {
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: space-between;

  i {
    font-size: 16px;
  }

  i:nth-child(1) {
    color: #1289fe;
    margin-right: 10px;
  }

  i:nth-child(2) {
    color: #999;
  }
}
</style>
