<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs='crumbs'></bread-crumb>
    </div>
  <div>
    <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="文章">
        <el-form label-width="100px" class="clearfix" :model="form" ref="arctileform"  :element-loading-text="loadingText" :rules="staffrules">
          <el-row>
            <el-col :span="23">
                <el-form-item label="文章标题:" required prop="act_name">
                    <el-input v-model="form.act_name"></el-input>
                </el-form-item>
              <el-form-item label="文章内容:" required prop="act_content">
                <keep-alive>
                  <neditor ref="neditor"
                           id="editor"
                           v-bind:r_content="form.act_content">
                  </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
                      v-loading="uploading"
                      :element-loading-text="loadingText"
                      class="avatar-uploader"
                      :data="uploadData"
                      action="https://upload.qiniup.com"
                      :show-file-list="false"
                      :on-error="handleAvatarError"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="form.org_logo" :src="form.org_logo" 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="show">
                    <el-upload
                      v-loading="uploading"
                      :element-loading-text="loadingText"
                      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="imageUrlSecond" :src="imageUrlSecond" 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="show">
                    <el-upload
                      v-loading="uploading"
                      :element-loading-text="loadingText"
                      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="act_type">
                 <el-select v-model="form.act_type" 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="submitForm('arctileform');centerDialogVisible=false">发布</el-button>
                      <el-button size="small" style="width: 100px" @click="preview('arctileform')">预览</el-button>
                      <el-button size="small" style="width: 100px" @click="save('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-tab-pane>
      <el-tab-pane label="视频">
        <el-form label-width="100px" class="clearfix"  :rules="rules" :model="form" ref="vidoform">
           <el-row>
             <el-col :span="24">
                 <div style="margin-bottom: 100px">
                   <el-form-item  required prop="vio_upload">
                       <div class="video-select" v-if="show">
                        <el-upload
                            class="upload-demo"
                            :data="uploadFileData"
                            action="https://upload.qiniup.com"
                            :on-change="handleChange"
                            :on-success="handleSuccess"
                            :on-error="handleError"
                            :before-upload="beforeUploadFile"
                             accept="video/x-flv,video/mpeg,video/avi,video/x-ms-wmv,video/quicktime,.asf,.rm,.rmvb,video/x-matroska,video/x-m4v,video/mp4">                         
                             <el-button size="small" type="primary" v-if="show">点击上传</el-button>
                             <div slot="tip" class="el-upload__tip" v-if="show">支持大多视频文件格式,大小不超过2G</div>
                        </el-upload>
                       </div>
                         <div class="video" v-if="shows">
                         <img v-if="form.vio_upload" :src="form.vio_upload+'?vframe/jpg/offset/1/w/300/h/200'" class="avatar" id="upvideo">
                       </div>
                        <div id="upvideo"></div>                  
                    </el-form-item>
                  </div>

                 <el-form-item label="视频标题:" required prop="vid_name">
                   <el-input v-model="form.vid_name"></el-input>
                 </el-form-item>

                 <el-form-item label="视频封面:">
                   <el-upload  class="avatar-uploader" :show-file-list="false" 
                   :on-success="handlevioSuccess" 
                   :before-upload="beforevidoFile" 
                   :on-change="handleChange"
                   action="https://upload.qiniup.com"
                   :data="uploadvidoData">
                     <img v-if="form.vid_pic" :src="form.vid_pic" class="avatar">                  
                     <img v-if="form.vio_upload" :src="form.vio_upload+'?vframe/jpg/offset/1/w/300/h/200'" class="avatar">
                     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                   </el-upload>
                 </el-form-item>
                 <div class="eltip">
                   视频封面若不上传，系统会根据视频内容进行自动截取<br>
                   目前支持PNG和JPG格式，图片大小不能超过1MB
                   </div>
                  <el-form-item label="所属分类:" required prop="vid_type">
                    <el-select v-model="form.vid_type">
                      <el-option
                          v-for="item in options"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"> 
                      </el-option>
                      </el-select>
                  </el-form-item>
                   <el-row :span="24">
                     <el-col :span="24">
                       <el-form-item>
                         <el-button size="small" type="primary" style="width: 100px" @click="SumitVido('vidoform');centerDialogVisible = false">发布</el-button>
                         <el-button size="small" style="width: 100px" @click="Savedraft('vidoform');centerdraftVisible = false">保存草稿</el-button>
                         <el-button size="small" style="width: 100px" @click="centercancelVisible = true">取消</el-button>
                       </el-form-item>
                     </el-col>
                   </el-row>                   
             </el-col>
           </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
     </div>
    </div>
      <el-dialog
        title="发布成功"
        :visible.sync="centerDialogVisible"
         width="30%"
         center>
         <span slot="footer" class="dialog-footer">
        <el-button @click="gotolink()">再发一条</el-button>
        <el-button type="primary" @click="gobacklist">返回文章列表</el-button>
       </span>
      </el-dialog>

      <el-dialog
       title="保存草稿成功"
       :visible.sync = "centerdraftVisible"
        width="30%"
        center>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="gobacklist">返回文章列表</el-button>  
         </span>
      </el-dialog>

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

<script>
  import BreadCrumb from '../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 {submitForm,getArticleType,addVido,Savedraft,previewArticle,save} from '@/api/act/submitinfo'
  import { getToken } from '@/api/qiniu'
  import { getFileExtension} from '@/utils/tools'
  export default {
    name: 'createArticle',
    components:{
     BreadCrumb,
      Neditor,
   },
    data(){
      return {
        crumbs: [
          { path: false, name: '文章管理' },
          { path: '/articles/createArticle', name: '发布文章' }
        ],
        radio:'1',
        options: [],
        value: '',
        show:false,
        content: '',
        editorOption: {},
        company:"",
        fileList: [],
        form:{
          act_name:'',
          act_content:'',
          act_picture:'',
          act_category:'',
          org_logo:'',
          act_type:'',
          file:'',
          vid_pic:'',
          vio_upload:'',
          vid_name:'',
          vid_type:'',
        },
         acttypes:[],
         imageUrl:'',
         imageUrlSecond:'',
         imageUrlLast:'',
         formloading:false,
         formsubmit:false,
         qiniuDomain: 'https://images.shengws.com/',
         uploading:false,
         loadingText:'',
         uploadData: { token: '', key: '' },
         uploadFileData:{token:'',key:''},
         uploadvidoData:{token:'',key:''},
         centerDialogVisible: false,
         centerdraftVisible:false,
         centercancelVisible:false,
         formLabelAlign:true,
         modlevidel:'',
         filsListArray:[],
         show:true,
         shows:false,
         rules: {
            vid_name: [{required: true, message: "视频标题不能为空"},],
            vio_upload: [{required: true,message:"请上传视频"}],
            vid_type: [{required: true,message:"所属分类不能为空"}]
          },
        artilcrules:{
            act_name: [{required: true, message: "文章标题不能为空"},],
            act_content: [{required: true,message:"文章内容不能为空"}],
            act_type: [{required: true,message:"所属分类不能为空"}]
        },
        vidoform:[],
      }
    },
    created(){
        this.getArticleType();
    },
    methods: {
      //第一个图片
      handleAvatarSuccess(res, file) {
       this.form.org_logo = this.qiniuDomain + res.url;
        this.uploading = false
      },
       handleAvatarError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }

            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;
                })
            })
      },
      //第二个图片
      handleAvatartwoSuccess(res, file) {
        this.imageUrlSecond = URL.createObjectURL(file.raw);
        this.form.org_logo = this.qiniuDomain + res.url;
        this.uploading = false
      },
       handleAvatartwoError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
      },
      beforeAvatartwoUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }

            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;
                })
            })

          //return isJPG && isLt2M;
      },

      //第三张图片
      handleAvatarlastSuccess(res, file) {
        this.imageUrlLast = URL.createObjectURL(file.raw);
        this.form.org_logo = this.qiniuDomain + res.url;
        this.uploading = false
      },
       handleAvatarlastError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
      },
      beforeAvatarlastUpload(file) {
        console.log("冷醒是",file.type)
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }

            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)
                })
            }) 
        }, 
        //视频上传
        handleChange(file, fileList) {
          this.form.file =  file.raw
        }, 
        handleSuccess(res,file,fileList){  
            this.$message.success("视频上传成功")               
             this.form.vio_upload = this.qiniuDomain + res.url;           
             console.log("是什么",this.form.vio_upload)

             this.show=false;
             this.shows = true;
        },
        handlevioSuccess(res,file,fileList){
           this.form.vid_pic = this.qiniuDomain + res.url;  
        },
        changeImg(url){
          console.log("路径是多少?",url)
        },
         handleError(err, file, fileList) {
             this.$message.error("视频上传失败")
         },
        beforeUploadFile(file) {
        const isLt2M = file.size / 1024 / 1024 < 2048;
        if (!isLt2M) {
          this.$message.error('上传视频大小不能超过 2G!');
        }
            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;
            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    //console.log("token2是什么?",token)
                    _self._data.uploadFileData.token = token
                    _self._data.uploadFileData.key = key
                    resolve(true)
                }).catch(err => {
                    reject(false)                  
                })
            })
      },
      beforevidoFile(file){
          const isJPG = file.type === 'png/jpg';
          if (!isJPG) {
          this.$message.error('上传头像图片只能是 png或者jpg格式!');
        }
          const isLt2M = file.size / 1024 / 1024 < 1;
        if (!isLt2M) {
          this.$message.error('上传视频大小不能超过 1M!');
        }
            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;
            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    //console.log("token2是什么?",token)
                    _self._data.uploadvidoData.token = token
                    _self._data.uploadvidoData.key = key
                    resolve(true)
                }).catch(err => {
                    reject(false)                  
                })
            })
       },
      select(){
        this.show = false
      },
      clickitem(){
        this.show = true
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      changeActtype(){
         console.log("所属分类",this.form.act_type)
      },
      submitForm(formName){
        this.form.act_content = this.$refs.neditor.content;
        console.log("文章内容",this.$refs.neditor.content)
        this.$refs[formName].validate((valid)=>{
            if(valid){
              submitForm(this.form).then(response => {
                   if(response.data.state == 1){
                     this.centerDialogVisible = true;
                     var articles = response.data.data.articles;
                     console.log("返回的数据是啥?",articles);
                   }
              })
            }
        });
      },
      getArticleType(){
        getArticleType().then(response =>{
            console.log(response.data.state)
            if(response.data.state === 1){
            var category = response.data.data.category
            this.options = response.data.data.category
             //console.log("文章内容:",category)
             //console.log("文章",this.options)
            }
        })
      },
      gotolink(){
         this.$router.go(0);
      },
      gobacklist(){
        this.$router.push({path:'/articles/articleList'})
      },
      SumitVido(formName){
         this.$refs[formName].validate((valid)=>{
           if(valid){
               addVido(this.form).then(response=>{
                   if(response.data.state == 1){
                     this.centerDialogVisible = true;
                     var vido = response.data.data.vido;
                     console.log("返回数据",vido)
                   }
               });
           }
         });
      },
      Savedraft(formName){
        this.$refs[formName].validate((valid)=>{
           if(valid){
               Savedraft(this.form).then(response=>{
                   if(response.data.state==1){
                     this.centerdraftVisible = true;
                     var savedraft = response.data.data.savedraft;
                     console.log("保存草稿数据",savedraft)
                   }
               });
           }
        });
      },
      preview(formName){
         this.form.act_content = this.$refs.neditor.content;
         console.log("文章内容",this.$refs.neditor.content)
         this.$refs[formName].validate((valid)=>{
            if(valid){
              //  console.log("内容是什么?",this.form)
              //  this.$router.push({path:'/articles/articlePreview'})
               previewArticle(this.form).then(response=>{
                    if(response.data.state ==1){
                        var art = response.data.data.art
                        console.log("act的数据是",art);
                        this.$router.push({path:'/articles/articlePreview'})
                    }
               });
            }
         });
      },
      save(formName){
         this.form.act_content = this.$refs.neditor.content;
         console.log("文章内容",this.$refs.neditor.content);
         this.$refs[formName].validate((valid)=>{
             if(valid){
                 save(this.form).then(response=>{
                   if(response.data.state ==1){
                     this.centerdraftVisible = true;
                     var articles = response.data.data.articles;
                     console.log("返回的数据是",articles)                   
                   }
                 });
             }
         });
      },
      confirm(){
         this.$router.push({path:"/articles/articleList"})
      }
    },
  }
</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;
  }
  /*视频*/
  .video-select {
    padding: 150px 0 30px;
    background: url("/static/images/video_load.png") no-repeat;
    background-position: center 0;
    background-size: 192px 132px;
    text-align: center;
    width: 200px;
    height: 200px;
    position: relative;
    left: 500px;
    margin-bottom: 1px;
  }
  .video{
    padding: 150px 0 30px;
    background-position: center 0;
    background-size: 192px 132px;
    text-align: center;
    width: 200px;
    height: 200px;
    position: relative;
    left: 500px;
    margin-bottom: 60px;
    margin-top: -140px;
  }
  .eltip{
    font-size: 12px;
    position: relative;
    left: 80px;
    margin-bottom: 20px;
  }
</style>
