<template>
  <div>
    <el-dialog
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="title + '公告'"
      :visible="visible"
      custom-class="bbsl-location-dialog"
      width="50%"
    >
      <div>
        <el-form
          ref="formInfo"
          :model="this.parameter"
          :rules="rules"
          label-position="top"
          label-width="150px"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="公告标题" prop="title">
                <el-input
                  v-model="parameter.title"
                  clearable
                  placeholder="请输入公告标题"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="公告类型" prop="type">
                <el-select
                  v-model="parameter.type"
                  clearable
                  placeholder="请选择公告类型"
                >
                  <el-option
                    v-for="item in NoticeTypeList"
                    :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="endTime">
                <el-date-picker
                  v-model="parameter.endTime"
                  clearable
                  placeholder="请输入截至日期"
                  style="width: 100%"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="公告内容" prop="content">
                <div class="quill-editor">
                  <!--富文本编辑器组件-->
                  <quill-editor
                    ref="QuillEditor"
                    v-model="parameter.content"
                    :content="parameter.content"
                    :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 :gutter="24">
                        <el-col :span="24">
                            <el-form-item label="备注" prop="">
                                <el-input clearable type="textarea" :rows="2" placeholder="请输入备注"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row> -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave">确认</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dictUtils from '@/components/dict/DictSelectUtils.js'
import noticeMenu from '@/api/examination/noticeMenu.js'
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: 'equSysMenuDialog',
  components: {
    quillEditor
  },
  data() {
    return {
      title: '',
      visible: false,
      parameter: {
        content: '',
        endTime: '',
        memo: '',
        status: '',
        title: '',
        type: ''
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入公告标题',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请输入公告类型',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择公告状态',
            trigger: 'blur'
          }
        ],
        endTime: [
          {
            required: true,
            message: '请选择截至时间',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入公告内容',
            trigger: 'blur'
          }
        ]
      },
      NoticeTypeList: [],
      NoticeStatusList: [],
      // 富文本配置
      uploadUrl: window.context.portal + '/file/v1/uploadFileForConfig', // 服务器上传地址
      acceptImg: '.jpg,.jpeg,.png,.JPG,.JPEG,.gif,.PNG,.GIF',
      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.NoticeTypeList = dictUtils.getDictItemsFromCache('gglx')
    this.NoticeStatusList = dictUtils.getDictItemsFromCache('ggzt')
  },
  computed: mapState({
    header: state => {
      return {
        Authorization: `Bearer ${state.login.currentUser.token}`
      }
    }
  }),
  mounted() {},
  methods: {
    edit(val) {
      this.parameter = val
      this.title = '修改'
      this.visible = true
    },
    add(val) {
      this.title = '新增'
      this.visible = true
      console.log(val)
    },
    // 关闭新增人员窗口
    handleClose() {
      this.visible = false
      this.parameter = {
        content: '',
        endTime: '',
        memo: '',
        status: '',
        title: '',
        type: ''
      }
    },
    // 保存
    handleSave() {
      this.$refs.formInfo.validate(valid => {
        if (valid) {
          let method
          if (this.title === '新增') {
            method = noticeMenu.addNotice
          }
          if (this.title === '修改') {
            method = noticeMenu.editNotice
          }
          method(this.parameter, response => {
            if (response.state) {
              this.$notify({
                type: 'success',
                message: this.title + '成功',
                duration: 2000
              })
              this.handleClose()
              this.$emit('loadData')
            } else {
              this.$message.warning(response.message)
            }
          })
        }
      })
    },
    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 lang="scss" scoped></style>
