<template>
  <basic-container>
    <jl-go-back></jl-go-back>
    <el-row>
      <el-col :span="8">
        <avue-form :option="formOption" :upload-before="uploadBefore"  v-model="form" @submit="handleSubmit" ref="form">
        </avue-form>
      </el-col>
      <el-col :span="16">
        <Tinymce v-model="form.note" ref="tinymce"></Tinymce>
        <!--        <quill-editor v-model="ruleForm.content" :options="editorOption" -->
<!--           @change="onEditorChange($event)" ref="QuillEditor">-->
<!--        </quill-editor>-->
<!--        <el-upload class="avatar-uploader" :action="putFile" :show-file-list="false" :on-success="handleAvatarSuccess"-->
<!--          :before-upload="beforeAvatarUpload">-->
<!--          <img v-if="imageUrl" :src="imageUrl" class="avatar">-->
<!--          <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--        </el-upload>-->
      </el-col>
    </el-row>
  </basic-container>
</template>
<script>
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import { quillEditor } from "vue-quill-editor";


  import { addNews, getNewsDetail, editNews } from "@/api/manage/news"
  import { putFile } from "@/api/resource/oss";
  import Tinymce from "@/components/Tinymce";
  import {getClassifyDic} from '@/api/help/article/classify'

  const toolbarItems = [
    ["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"], // 清除文本格式
    ["image"], // 链接、图片、视频
  ]
  export default {
    components: { quillEditor, Tinymce},
    props: {
      id: Number,
      type: String
    },
    mounted() {
      this.onload()
    },
    data() {
      return {
        putFile,
        imageUrl: '',
        ruleForm: {
          content: null,
        },
        form: {
          note: ''
        },
        description:'',
        formOption: {
          // labelWidth:120,
          column: [
            {
              type: "tree",
              label: "分类",
              span: 24,
              size: "small",
              prop: "type",
              rules: [
                {
                  required: true,
                  message: "请选择分类",
                },
              ],
              filterable: true,
              dicUrl: getClassifyDic(),
              props: {
                label: "name",
                value: "type",
              },
              dicFormatter(resp) {
                return resp.data;
              },
            },
            {
              label: "文章名称",
              prop: "articleTitle",
              span: 24,
              row: true,
              maxlength:50,
              showWordLimit:true,
              rules: [
                {
                  required: true,
                  message: '请输入文章名称'
                }
              ]
            },
            {
              label: "摘要",
              prop: "description",
              rows:3,
              type: 'textarea',
              span: 24,
              row: true,
              rules: [
                {
                  required: true,
                  message: '请输入摘要'
                }
              ],
              maxlength:200,
              showWordLimit:true,
            },
            {
              label: "文章来源",
              prop: "articleSrc",
              span: 24,
              row: true,
              maxlength:50,
              showWordLimit:true,

            },
            {
              label: "文章源地址",
              prop: "articleSrcUrl",
              span: 24,
              row: true,
              maxlength:100,
              showWordLimit:true,

            },
            {
              label: "作者",
              prop: "author",
              span: 24,
              row: true,
              rules: [
                {
                  required: true,
                  message: '请输入作者'
                }
              ],
              maxlength:50,
              showWordLimit:true,
            },
            {
              label: "首页图",
              prop: "headPic",
              type: "upload",
              action: putFile(),
              span: 12,
              showFileList: false,
              listType: "picture-img",
              multiple: false,
              canvasOption: {},
              headers: [],
              data: [],
              propsHttp: {
                url: "msg",
              },
              rules: [
                {
                  required: true,
                  message: '请上传首页图'
                }
              ]
            },
          ]
        },
        editorOption: {
          modules: {
            toolbar: {
              container: toolbarItems,
              handlers: {
                'image': function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            },//工具菜单栏配置
          },
          placeholder: "请在这里编写文章内容", //提示
          readyOnly: false, //是否只读
          theme: "snow", //主题 snow/bubble
          syntax: true, //语法检测
        },
      };
    },
    methods: {
      uploadBefore(file, done, loading, column) {
        this.form.headPic = ''
        done()
      },
      // 值发生变化
      onEditorChange(editor) {
        this.content = editor.html;
      },
      handleSubmit(form, done) {
        // this.form['note'] = this.$refs.tinymce.getContent()

        if(this.form.note.length>64*512){
          this.$message.error('文章内容不能超过64KB！');
          done()
        }
        else{
          if (this.type == 'add') {
            addNews(
              this.form.articleTitle,
              this.form.headPic,
              this.form.articleSrc,
              this.form.articleSrcUrl,
              this.form.author,
              this.form.description,
              this.form.note,
              this.form.type
            ).then(() => {
              this.$message.success('添加成功');
              this.$router.go(-1);
            })
        }
        else if (this.type == 'edit') {
          editNews(
            this.id,
            this.form.articleTitle,
            this.form.headPic,
            this.form.articleSrc,
            this.form.articleSrcUrl,
            this.form.author,
            this.form.description,
            this.form.note,
            this.form.type
          ).then(() => {
            this.$message.success('修改成功');
            done()
          })
        }
        }


      },
      /*上传图片*/
      handleAvatarSuccess(res) {
        let quill = this.$refs.QuillEditor.quill
        let length = quill.getSelection().index;//获取光标所在位置
        quill.insertEmbed(length, 'image', res.data.link)
        quill.setSelection(length + 1)//光标后移一位
      },
      beforeAvatarUpload(file) {
        const isJPG = ["image/png", "image/jpeg", "image/svg+xml", "image/gif"].indexOf(file.type) != -1;
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传图片格式不正确');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      onload() {
        if (this.id && this.type == 'edit') {
          getNewsDetail(this.id).then(res => {
            this.form = res.data.data;
            this.description=this.form.description;
          })
        }
      },

    },
  };
</script>
<style>
  .avatar-uploader {
    width: 0;
    height: 0;
    display: none;
  }

  .ql-editor {
    height: 400px;
  }
</style>
