<template>
    <div class="app-container">
      <el-row style="padding:0 0 20px 0px;">
        <el-col :span="12"><div class="grid-content bg-purple"><div style="'line-height:35px;'">编辑文章</div></div></el-col>
        <el-col style="text-align:right;" :span="12">
          <div class="grid-content bg-purple-light">
            <el-button @click="edit" type="success" plain>保存</el-button>
            <!-- <el-button type="info" plain>复制</el-button> -->
            <!-- <el-button type="primary" plain>预览</el-button> -->
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-upload
          ref="mYupload"
            class="avatar-uploader"
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadSuccessHandle"
            :before-upload="onBeforeUpload">
            <img v-if="form.coverImage" :src="form.coverImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-col>
        <el-col :span="20">
          <el-select style="width:100%;margin-bottom:10px;" v-model="form.classification" placeholder="请选择分类">
            <el-option label="未分类" value="未分类"></el-option>
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.classifyName"
              :value="item.classifyName">
            </el-option>
          </el-select>
          <el-input  v-model="form.articleTitle" placeholder="请输入标题"></el-input>
          <el-select style="width:100%;margin:10px 0;" v-model="form.status" placeholder="请选择状态" clearable size="small">
              <el-option label="待发布" value="待发布" />
              <el-option label="已上线" value="已上线" />
            </el-select>
          <div style="margin-top:10px;">
            <el-input
              type="textarea"
              :rows="3"
              maxlength="500"
              placeholder="请输入文章简介（选填，最多支持500个字符）"
              v-model="form.articleIntroduction">
            </el-input>
          </div>
          
        </el-col>
      </el-row>
      <div class="rich-container">
        <textarea id="ck-editor"  name="editor" rows="10" cols="80"></textarea>
      </div>

    <div class="searchTitle flex">
    <div>搜索关键词</div> 
    <el-radio-group v-model="form.language">
      <el-radio-button label="中文"></el-radio-button>
      <el-radio-button label="English"></el-radio-button>
    </el-radio-group>
  </div>
  <el-input @keyup.enter.native="keyup" v-model="form.searchKeywords" placeholder="关键词将使用该网站的搜索结果更加准确，每篇文章最多填写5个，每个关键词之间请按回车键分隔"></el-input>
   </div> 
  </template>
  
  <script>
  import { listDict, updateManagement, getManagement } from "@/api/cloud/articleManagement";
  import { uploadPath } from '@/api/storage'
  import { getToken } from '@/utils/auth'
  export default {
    data() {
      return {
        uploadPath,
        editor: null,
        // 表单参数
        form: {classification:'未分类',language:'中文'},
        input:'',
        // 表单校验
        rules: {
          gmtCreate: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],        gmtUpdate: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],        deleteFlag: [
            { required: true, message: "删除标识不能为空", trigger: "blur" }
          ]      
        },
        options:[],
        editor: null,
        editorData: '<p>Content of the editor.</p>',
        editorConfig: {
          // The configuration of the editor.
        }
      }
    },
    computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
    created() {
      // this.getList();
    },
    mounted() {
    var that = this
      window.CKEDITOR.replace('ck-editor', {height: '400px', width: '100%', toolbar: 'toolbar_Full'});
      this.editor = window.CKEDITOR.instances['ck-editor']
      listDict({ classifyType:'article_type',}).then(response => {
        this.options=response.data.data.items
      });
      getManagement(this.$route.query.Id).then(response => {
        this.form = response.data.data
        setTimeout(()=>{that.InsertHTML(that.form.content)},1000) 
      });
      // this.initEditor()
    },
    methods: {
      InsertHTML(html) {
      // Get the editor instance that you want to interact with.
      // var value = document.getElementById('ck-editor').value;
      console.log(this.editor)
      // Check the active editing mode.
      if ( this.editor.mode == 'wysiwyg') {
        // Insert HTML code.
        // https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-insertHtml

        this.editor.setData(html);
      } else
        alert('You must be in WYSIWYG mode!');
    },
      getContent() {
        console.log(this.editor.getData())
      },
      keyup(e){
        var content= this.form.searchKeywords.split(',')
        if(content.length>5){
          this.$message.error('关键词最多5个!')
        }else{
          if(this.form.searchKeywords[this.form.searchKeywords.length-1]==','){
            this.$message.error('请输入关键词内容!')
          }else{
            this.form.searchKeywords=this.form.searchKeywords+','
          }
        }
        
      },
      // 上传图片了处理图片
      uploadSuccessHandle(e, file) {
        const that = this
        this.form.coverImage = e.url
        console.log(this.form,this.editor)
      },
      onBeforeUpload(file) {
        const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png' || 'image/jpg'
        const isLt1M = file.size / 1024 / 1024 < 1

        if (!isIMAGE) {
          this.$message.error('上传文件只能是图片格式!')
        }
        if (!isLt1M) {
          this.$message.error('上传文件大小不能超过 1MB!')
        }
        return isIMAGE && isLt1M
      },
      edit(){
        if(this.form.searchKeywords){
            if(this.form.searchKeywords.split(',').length>5){
            this.$message.error('关键词最多5个!')
            return 
            }
        }
        
        this.form.content=this.editor.getData()
        updateManagement(this.form).then(response => {
              if (response.data) {
                this.msgSuccess("修改成功");
                this.$refs['mYupload'].clearFiles();
                this.form={classification:'未分类'}
                this.$router.go(-1)
              } else {
                this.msgError(response.msg);
              }
            });
      }
        
    }
  };
  </script>
  <style lang="scss" scoped>
  .avatar-uploader{ 
    /deep/.el-upload {
      border: 1px dashed #ccc;
      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: 183px;
    height: 183px;
    line-height: 183px;
    text-align: center;
  }
  .avatar {
    width: 183px;
    height: 183px;
    display: block;
  }
  .searchTitle{
    margin:20px 0;
  }
  /*编辑框最低高度*/
  .ck-editor__editable{
    min-height: 400px;
  }
  .rich-container{
    margin-top:20px;
  }
  </style>