<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="add" 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">
        <div class="flex" style="">
          <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-radio-group v-model="form.language" style="margin:0 10px 10px 10px;display:flex">
            <el-radio-button label="中文"></el-radio-button>
            <el-radio-button label="English"></el-radio-button>
          </el-radio-group>
          <el-radio-group style="margin:0 10px 10px 10px; display:flex" v-model="form.articleClassify">
            <el-radio-button label="文章"></el-radio-button>
            <el-radio-button label="百科"></el-radio-button>
          </el-radio-group>
        </div>

        <el-input v-model="form.articleTitle" placeholder="请输入标题"></el-input>
        <div style="margin-top:10px;">
          <el-input type="textarea" :rows="4" 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>
    </div>
    <el-input @keyup.enter.native="keyup" v-model="form.searchKeywords"
      placeholder="关键词将使用该网站的搜索结果更加准确，每篇文章最多填写5个，每个关键词之间请按回车键分隔"></el-input>
  </div>
</template>
  
<script>
import { listDict, addManagement } from "@/api/cloud/articleManagement";
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      uploadPath,
      // 表单参数
      form: { classification: '未分类', language: '中文', articleClassify: '文章' },
      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() {
    window.CKEDITOR.replace('ck-editor', { height: '400px', width: '100%', toolbar: 'toolbar_Full' });
    this.editor = window.CKEDITOR.instances['ck-editor']
    let that = this;
    this.editor.on('fileUploadRequest', evt => {
      const requestData = evt.data.requestData
      const upload = requestData.upload
      delete requestData.upload
      requestData.file = upload
    })

    this.editor.on('fileUploadResponse', evt => {
      evt.stop();
      const data = evt.data
      const fileLoader = data.fileLoader
      const res = JSON.parse(fileLoader.xhr.responseText)
      console.log(res)
      if (res.errno !== 200) {
        data.message = '上传失败'
        evt.cancel();
        return
      }
      data.fileName = fileLoader.fileName
      data.url = res.url
      data.message = '上传成功'
    })



    listDict({ classifyType: 'article_type', }).then(response => {
      this.options = response.data.data.items
    });
    // 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.getData())
      // 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
      this.$forceUpdate()
      console.log(e, this.editor.getData())



      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
    },
    add() {
      if (this.form.searchKeywords) {
        if (this.form.searchKeywords.split(',').length > 5) {
          this.$message.error('关键词最多5个!')
          return
        }
      }

      this.form.content = this.editor.getData()
      addManagement(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>