
<template>
    <div class="main-contain">
        <div class="position">
            <bread-crumb :crumbs='crumbs'></bread-crumb>
        </div>
        <div class="app-container">
             <el-form label-width="100px" class="clearfix" :model="arctileform" ref="arctileform"  :rules="rules">
          <el-row>
            <el-col :span="23">
                <el-form-item label="文章标题:" required prop="title">
                    <el-input v-model="arctileform.title"></el-input>
                </el-form-item>
              <el-form-item label="文章内容:" required prop="content">
                <keep-alive>
                  <neditor ref="neditor"
                           id="editor"
                           v-bind:r_content="arctileform.content"  @content_changed="paragraphContentChanged">
                  </neditor>
                </keep-alive>
              </el-form-item>
              <el-form-item label="封面图片:">
                  <el-radio v-model="radio" label="1" @click.native.prevent="select()" >单图</el-radio>
                  <el-radio v-model="radio" label="2" @click.native.prevent="clickitem()" >三图</el-radio>
              </el-form-item>
              <el-form-item>
                <el-col :span="3">
                  <div>
                    <el-upload
                      class="avatar-uploader"
                      :data="imageData"
                      action="https://upload.qiniup.com"
                      :show-file-list="false"
                      :on-error="handleAvatarError"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="arctileform.imgs" :src="arctileform.imgs" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-col>

              <!-- 第二张图片 -->
                <el-col :span="3">
                  <div v-if="picshow">
                    <el-upload
                      class="avatar-uploader"
                      :data="uploadData"
                      action="https://upload.qiniup.com"
                      :show-file-list="false"
                      :on-error="handleAvatartwoError"
                      :on-success="handleAvatartwoSuccess"
                      :before-upload="beforeAvatartwoUpload">
                      <img v-if="imageUrl" :src="imageUrl" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-col>

                <!-- 第三张图片 -->
                <el-col :span="3">
                  <div v-if="picshow">
                    <el-upload
                      class="avatar-uploader"
                      :data="uploadData"
                      action="https://upload.qiniup.com"
                      :show-file-list="false"
                      :on-error="handleAvatarlastError"
                      :on-success="handleAvatarlastSuccess"
                      :before-upload="beforeAvatarlastUpload">
                      <img v-if="imageUrlLast" :src="imageUrlLast" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-col>
              </el-form-item>
               <el-form-item label="所属分类:" prop="class_id">
                 <el-select v-model="arctileform.class_id" placeholder="请先选择文章所属分类"  @change="changeActtype()">
                   <el-option
                     v-for="item in options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
                   </el-option>
                 </el-select>
               </el-form-item>
            </el-col>
          </el-row>

          <el-row :span="24">
            <el-col :span="24">
                <el-form-item>
                      <el-button size="small" type="primary" style="width: 100px"  @click="UpdataArticleInfo('arctileform');">发布</el-button>
                      <el-button size="small" style="width: 100px" @click="preview()">预览</el-button>
                      <!-- <el-button size="small" style="width: 100px" @click="saveArticleDraft('arctileform');centerdraftVisible = false">保存草稿</el-button> -->
                  <el-button size="small" style="width: 100px" @click="centercancelVisible = true">取消</el-button>
                </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-dialog
           title="发表成功"
           :visible.sync="dialogVisible"
            width="30%"
            center>
           <span slot="footer" class="dialog-footer">
           <el-button @click="gobackList()">返回文章列表</el-button>
           </span>
         </el-dialog>

        <el-dialog
           title="发表成功"
           :visible.sync="dialogVisible"
            width="30%"
            center>
           <!-- <span>这是一段信息</span> -->
           <span slot="footer" class="dialog-footer">
           <el-button @click="gobackList()" type="primary">返回文章列表</el-button>
           </span>
         </el-dialog>

       <el-dialog
         title="提示"
         :visible.sync = "centercancelVisible"
         width="30%"
         center>
         <span >是否确定取消编辑此文章/视频</span>
         <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="centercancelVisible = false" >确认</el-button>
         <el-button @click="centercancelVisible = false">取消</el-button>
        </span>
       </el-dialog>
        </div>
    </div>
</template>

<script>
    // import BreadCrumb from '../components/bread-crumb'
    import BreadCrumb from "@/scrm_pages/components/bread-crumb"
    import { quillEditor } from 'vue-quill-editor'
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import Neditor from '@/components/Neditor'
    import { getToken } from '@/api/qiniu'
    import { getFileExtension} from '@/utils/tools'
    import {getEditArticle,getMenus,UpdataArticleInfo,previewEditArticle,saveArticleDraft} from '@/api/act/submitinfo'
    export default {
        name: "EditArticle",
         components:{
            BreadCrumb,
            Neditor,
         },
         data(){
            return {
             crumbs: [
              { path: false, name: '文章管理' },
              { path: '/articles/editArticle/:id', name: '编辑文章' }
              ],
               radio:'1',
        options: [],
        value: '',
        show:false,
        content: '',
        editorOption: {},
        company:"",
        fileList: [],
        arctileform:{
            title:"",
            content:"",
            imgs:"",
            class_id:"",
        },
         picshow:false,
         acttypes:[],
         imageUrl:'',
         imageUrlSecond:'',
         imageUrlLast:'',
         formloading:false,
         formsubmit:false,
         qiniuDomain: 'https://images.shengws.com/',
         uploading:false,
         loadingText:'',
         uploadData: { token: '', key: '' },
         imageData: { token:'',key:''},
         uploadFileData:{token:'',key:''},
         uploadvidoData:{token:'',key:''},
         centerDialogVisible: false,
         centerdraftVisible:false,
         centercancelVisible:false,
         formLabelAlign:true,
         show:true,
         shows:false,
        rules:{
            title: [{required: true, message: "文章标题不能为空"},],
            content: [{required: true,message:"文章内容不能为空"}],
            class_id: [{required: true,message:"所属分类不能为空"}]
        },
        // vidoform:[],
        dialogVisible:false,
        }
    },
         methods:{
             //第一个图片
      handleAvatarSuccess(res, file) {
       this.arctileform.imgs = this.qiniuDomain + res.url;
      },
       handleAvatarError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
      },
      beforeAvatarUpload(file) {
         var fileType = file.type
            const isJPG = fileType.indexOf("image") > -1;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("只能上传图片");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("图片大小不能超过 2MB!");
                return false;
         }

            var date = new Date()
            var ext = getFileExtension(file.name)
            var key = date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours()  + date.getMinutes()  + date.getSeconds()  +'_o_' + file.uid + '.' + ext;
            this.uploading = true;
            // this.loadingText = '封面图片上传中'

            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    console.log("第一张图片token是什么?",token)
                    _self._data.imageData.token = token;
                    _self._data.imageData.key = key;
                    resolve(true)
                }).catch(err => {
                    reject(false)

                })
            })
          return isJPG && isLt2M;
      },
      //第二个图片
      handleAvatartwoSuccess(res, file) {
        this.imageUrl = this.qiniuDomain + res.url;
      },
       handleAvatartwoError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
      },
      beforeAvatartwoUpload(file) {
         var fileType = file.type
            const isJPG = fileType.indexOf("image") > -1;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("只能上传图片");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("图片大小不能超过 2MB!");
                return false;
         }
            var date = new Date()
            var ext = getFileExtension(file.name)
            var key = date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours()  + date.getMinutes()  + date.getSeconds()  +'_o_' + file.uid + '.' + ext;
            this.uploading = true;
            // this.loadingText = '封面图片上传中'

            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    console.log("token是什么?",token)
                    _self._data.uploadData.token = token
                    _self._data.uploadData.key = key
                    resolve(true)
                }).catch(err => {
                    reject(false)
                    this.uploading = false;
                })
            })
      },

      //第三张图片
      handleAvatarlastSuccess(res, file) {
        this.imageUrlLast = this.qiniuDomain + res.url;

      },
       handleAvatarlastError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
      },
      beforeAvatarlastUpload(file) {
            var fileType = file.type
            const isJPG = fileType.indexOf("image") > -1;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("只能上传图片");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("图片大小不能超过 2MB!");
                return false;
         }

            var date = new Date()
            var ext = getFileExtension(file.name)
            var key = date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours()  + date.getMinutes()  + date.getSeconds()  +'_o_' + file.uid + '.' + ext;
            this.loadingText = '封面图片上传中'

            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    console.log("token是什么?",token)
                    _self._data.uploadData.token = token
                    _self._data.uploadData.key = key
                    resolve(true)
                }).catch(err => {
                    reject(false)
                })
            })
        },
        getEditArticle(){
            const id = this.$route.params && this.$route.params.id;
            console.log("编辑文章id是什么?",id)
           getEditArticle(id,this.arctileform).then(response=>{
                 if(response.data.state == 1){
                     var articles = response.data.data.articles;

                     console.log("articles是什么",articles)
                     this.arctileform.title = articles.title;
                     this.arctileform.content = articles.content;
                     this.arctileform.imgs = articles.imgs;
                     console.log("ww",this.arctileform.imgs)
                     this.arctileform.class_id = articles.class_id;
                     console.log(articles.title)

                 }
           });
        },
        getMenus(){
            getMenus().then(response =>{
                if(response.data.state == 1){
                   var categorys = response.data.data.categorys;
                   this.options = categorys;
                   console.log("分类号",categorys)

                }
            })
        },

        UpdataArticleInfo(forName){
              this.arctileform.content = this.$refs.neditor.content;
              const id = this.$route.params && this.$route.params.id;
             console.log("发布文章内容",this.arctileform.content);
             console.log("id是多少?",id)
             this.$refs[forName].validate((valid)=>{
                 if(valid){
                    UpdataArticleInfo(id,this.arctileform).then(response=>{
                         if(response.data.state == 1){
                          var aritcls = response.data.data.articls;
                          console.log("更新内容是多少",aritcls)
                             this.dialogVisible = true;
                         }
                    });
                 }
             })
        },
        saveArticleDraft(forName){
          const id = this.$route.params && this.$route.params.id;
           this.arctileform.content = this.$refs.neditor.content;
           this.$refs[forName].validate((valid)=>{
             if(valid){
               saveArticleDraft(id,this.arctileform).then(response=>{
                  if(response.data.state ==1 ){
                      this.dialogVisible = true;
                  }
               })
             }
           })
        },
        gobackList(){
           this.$router.push({path:'/articles/articleList'})
        },
        preview(){
            const id = this.$route.params && this.$route.params.id;
            console.log("id是什么",id)
           this.$router.push("/articles/articleEditPreview/"+id)
            // this.arctileform.content = this.$refs.neditor.content;
            // console.log("内容",this.arctileform.content)
            // const id = this.$route.params && this.$route.params.id;
            // console.log("id是什么",id)
            // this.$refs[forName].validate((valid)=>{
            //   if(valid){
            //      previewEditArticle(id,this.arctileform).then(response=>{
            //        if(response.data.state == 1){
            //            this.$router.push("/articles/articleEditPreview")
            //        }
            //      })
            //   }
            // })
        },
        select(){
        this.picshow = false
        },
       clickitem(){
        this.picshow = true
      },
        //监听图片获取富文本前三张图片
       paragraphContentChanged: function(content) {
            var images = [],temp;
            // console.log("监听获取的文章内容是什么?",content)
            var patt = /<img[^>]+src=['"]([^'"]+)['"]+/g;
            while ((temp = patt.exec(content)) != null) {
            images.push(temp[1]);
            }
            //  console.log("图片数组",images);
            if(images.length!=""){
             this.arctileform.imgs = images[0];
             this.imageUrl = images[1];
             this.imageUrlLast = images [2];
            }
        },
      },
      created(){
          this.getEditArticle();
          this.getMenus();
      },
    }
</script>

<style scoped>
 .avatar-uploader{
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    width: 140px;
    height: 140px;
  }
  .avatar-uploader{
    border-color: #f0f2f5;
  }
  .avatar-uploader-icon {
    font-size: 25px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
