<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel"
                      :content="(pageType == 'create' ? '添加' : '修改') + typeChange(type)"></el-page-header>
    </h2>

    <div class="m-core">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               label-width="120px"
               style="width: 100%">
        <el-form-item label="标题"
                      prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model="form.order"></el-input>
        </el-form-item>
        <el-form-item label="链接地址"
                      prop="linkUrl">
          <el-input v-model="form.linkUrl"></el-input>
        </el-form-item>
        <el-form-item label="封面图"
                      prop="coverImage">
          <el-upload class="avatar-uploader"
                     action="/api-web/uploadFile"
                     :headers="headers"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="form.coverImage"
                 :src="form.coverImage"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="imageSize"
             v-if="imageSize">上传图片尺寸为：{{ imageSize }}</p>
        </el-form-item>
        <el-form-item label="内容"
                      prop="content">
          <!-- bidirectional data binding（双向数据绑定） -->
          <quill-editor v-model="form.content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @change="onEditorChange($event)">
          </quill-editor>

          <el-upload class="ivu-upload"
                     :show-upload-list="false"
                     :headers="headers"
                     :on-success="handleSuccess"
                     :format="['jpg','jpeg','png','gif']"
                     :max-size="2048"
                     multiple
                     action="/api-web/uploadFile">
            <Button icon="ios-cloud-upload-outline"></Button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmit('form')"
                     type="primary">立即{{ pageType == "create" ? '创建' : '修改' }}</el-button>
          <el-button @click="onReSet('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { newsQueryId, newsAdd, newsUpdate } from '@/api/contentManager'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { vaildStudentUrl } from '@/utils/validate'
// import E from 'wangeditor'
// require styles
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 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["link", "image", "video"] // 链接、图片、视频
];
// 标题
const titleConfig = {
  'ql-bold': '加粗',
  'ql-color': '颜色',
  'ql-font': '字体',
  'ql-code': '插入代码',
  'ql-italic': '斜体',
  'ql-link': '添加链接',
  'ql-background': '背景颜色',
  'ql-size': '字体大小',
  'ql-strike': '删除线',
  'ql-script': '上标/下标',
  'ql-underline': '下划线',
  'ql-blockquote': '引用',
  'ql-header': '标题',
  'ql-indent': '缩进',
  'ql-list': '列表',
  'ql-align': '文本对齐',
  'ql-direction': '文本方向',
  'ql-code-block': '代码块',
  'ql-formula': '公式',
  'ql-image': '图片',
  'ql-video': '视频',
  'ql-clean': '清除字体样式',
  'ql-upload': '文件'
};
export default {
  name: 'contentOperation',
  components: {
    quillEditor
  },
  data () {
    return {
      categoryList: [],
      type: this.$route.query.type,
      pageType: this.$route.query.pageType,
      organId: null,
      headers: {
        Authorization: getToken()
      },
      content: null,
      editorOption: {
        placeholder: '请输入内容',
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  // 调用iview图片上传
                  document.querySelector('.ivu-upload .el-upload').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      form: {
        title: null,
        order: null,
        coverImage: null,
        linkUrl: vaildStudentUrl() + '/#/specialdetail',
        type: this.$route.query.type,
        status: 1,
        content: null
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }],
        linkUrl: [{ required: true, message: '请输入连接地址', trigger: 'blur' }],
        coverImage: [{ required: true, message: '请选择封面图', trigger: 'blur' }],
        content: [{ required: true, message: '请编辑内容', trigger: 'blur' }]
      },
      imageSize: null
    }
  },
  mounted () {
    this.getList()
    this.addQuillTitle()

    // this.form.type
    let tempTitle = {
      1: "468px * 552px",
      2: "456px * 288px",
      3: "686px * 140px",
      4: null
    }
    this.imageSize = tempTitle[this.form.type]


  },
  methods: {
    addQuillTitle () {
      const oToolBar = document.querySelector('.ql-toolbar'),
        aButton = oToolBar.querySelectorAll('button'),
        aSelect = oToolBar.querySelectorAll('select');
      aButton.forEach(function (item) {
        if (item.className === 'ql-script') {
          item.value === 'sub' ? item.title = '下标' : item.title = '上标';
        } else if (item.className === 'ql-indent') {
          item.value === '+1' ? item.title = '向右缩进' : item.title = '向左缩进';
        } else {
          item.title = titleConfig[item.classList[0]];
        }
      });
      aSelect.forEach(function (item) {
        item.parentNode.title = titleConfig[item.classList[0]];
      });
    },
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.pageType == 'create') {
            if (this.form.id) { // 判断有没有Id，如果有则删除
              delete this.form.id
            }
            // return false
            newsAdd(this.form).then(res => {
              this.messageTips('添加', res)
            })
          } else if (this.pageType == 'update') {
            newsUpdate(this.form).then(res => {
              this.messageTips('修改', res)
            })
          }
        } else {
          return false
        }
      })
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + '成功')

        this.$router.push({
          path: '/contentManager/contentManager',
          query: {
            type: this.typeIndex(this.type)
          }
        })
      } else {
        this.$message.error(res.msg)
      }
    },
    onCancel () {
      this.$router.push({
        path: '/contentManager/contentManager',
        query: {
          type: this.typeIndex(this.type)
        }
      })
    },
    handleSuccess (res) {
      // 获取富文本组件实例
      let quill = this.editor
      // 如果上传成功
      if (res.code) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', res.data.url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
        this.$message.error('图片插入失败')
      }
    },
    onReSet (formName) {
      this.$refs[formName].resetFields()
    },
    getList () {
      if (this.pageType == 'create') return false
      newsQueryId({ id: this.$route.query.id }).then(res => {
        if (res.code == 200) {
          let result = res.data
          let form = this.form
          this.form = {
            id: result.id,
            title: result.title,
            order: result.order,
            coverImage: result.coverImage,
            linkUrl: result.linkUrl,
            type: result.type,
            status: result.status,
            content: result.content
          }
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.form.coverImage = res.data.url
    },
    beforeAvatarUpload (file) {
      const imageType = {
        'image/png': true,
        'image/jpeg': true
      }
      const isImage = imageType[file.type]
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M;
    },
    typeChange (type) {
      let tempTitle = {
        1: "精彩活动",
        2: "热门资讯",
        3: "活动列表",
        4: "专项训练"
      }
      return tempTitle[type]
    },
    typeIndex (type) {
      let tempTitle = {
        3: 0,
        1: 1,
        2: 2,
        4: 3
      }
      return tempTitle[type]
    },
    onEditorChange ({ quill, html, text }) {
      this.form.content = html
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  },
}
</script>
<style lang="scss" scoped>
.m-container {
  min-width: 100%;
}
.el-input {
  width: 400px;
}
/deep/.ql-editor {
  min-height: 300px;
}
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
.el-row {
  margin-top: 40px;
}
.el-col {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: flex-end;
  margin-right: 50%;
}
.el-input-group {
  width: 200px;
  margin: 0 20px;
}
/deep/.el-tree-node__content {
  height: 40px !important;
}
/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: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.ivu-upload {
  display: none;
}
</style>