<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-select style="width:100%;margin-bottom:10px;" v-model="form.status" placeholder="请选择状态" clearable size="small">
              <el-option label="待发布" value="待发布" />
              <el-option label="上架" value="上架" />
            </el-select>
          <el-input v-model="form.productTitle" placeholder="请输入标题"></el-input>
          <div style="margin-top:10px;">
            <el-input
              type="textarea"
              :rows="4"
              maxlength="500"
              placeholder="请输入简介（选填，最多支持500个字符）"
              v-model="form.productIntroduction">
            </el-input>
          </div>
          
        </el-col>
      </el-row>
      <div class="rich-container">
        <textarea id="ck-editor"  name="editor" rows="10" cols="80"></textarea>
      </div>
      <el-collapse v-model="activeNames" >
        <el-collapse-item title="搜索引擎优化" name="1">
            <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="每个关键词之间请按回车键分隔"></el-input>
            <div class="searchTitle">产品描述</div>
            <el-input
              type="textarea"
              :rows="4"
              maxlength="500"
              placeholder="请输入产品描述"
              v-model="form.productDescribe">
            </el-input>
        </el-collapse-item>
    </el-collapse>
  
   </div> 
  </template>
  
  <script>
  import { listDict } from "@/api/cloud/articleManagement";
  import { updateProductManagement,getProductManagement } from "@/api/cloud/productManagement";
  import { uploadPath } from '@/api/storage'
  import { getToken } from '@/utils/auth'
  export default {
    data() {
      return {
        uploadPath,
        editor: null,
        activeNames: ['1'],
        // 表单参数
        form: {classification:'未分类'},
        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:'product_type',}).then(response => {
        this.options=response.data.data.items
      });
      getProductManagement(this.$route.query.Id).then(response => {
        this.form = response.data.data
        this.InsertHTML(this.form.content)
      });
      // 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(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()
        updateProductManagement(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>