<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"  :rules="rules" :model="form" ref="vidoform">
           <el-row>
             <el-col :span="24">
                 <div style="margin-bottom: 100px">
                   <el-form-item>
                       <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="clear();centercancelVisible = true">取消</el-button>
                       </el-form-item>
                     </el-col>
                   </el-row>                   
             </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>
  
       </div>
    </div>
</template>

<script>
    import BreadCrumb from '../components/bread-crumb'
    import {getEditVidoInfo,getMenus,updataVidoInfo,SaveVidodraft} from '@/api/act/submitinfo'
    import { getFileExtension} from '@/utils/tools'
    import { getToken } from '@/api/qiniu'
    export default {
        name: "editVido",
        components:{
         BreadCrumb,
      },
      data(){
         return{
         crumbs: [
           { path: false, name: '文章管理' },
           { path: '/articles/articleList', name: '视频编辑' }
          ],
          form:{ 
            file:'',
            vid_pic:'',
            vio_upload:'',
            vid_name:'',
            vid_type:'',
          },
          show:true,
          shows:false,
          dialogVisible:false,
          options: [],
          qiniuDomain: 'https://images.shengws.com/',
          uploadFileData:{token:'',key:''},
          uploadvidoData:{token:'',key:''},
          rules: {
            vid_name: [{required: true, message: "视频标题不能为空"},],
            vid_type: [{required: true,message:"所属分类不能为空"}]
          },
         } 
      },
      methods:{
        //视频上传
        handleChange(file, fileList) {
          this.form.file =  file.raw
        }, 
        handleSuccess(res,file,fileList){  
            this.$message.success("视频上传成功")          
             this.form.vio_upload = this.qiniuDomain + res.url; 
              this.form.vid_pic = this.form.vio_upload+"?vframe/jpg/offset/1/w/300/h/200",               
             console.log("上传之后是什么",this.form.vio_upload)

             this.show=false;
             this.shows = true;
        },
        handlevioSuccess(res,file,fileList){
            console.log("上传成功没有?")
           this.form.vid_pic = this.qiniuDomain + res.url;  

        },
         handleError(err, file, fileList) {
             this.$message.error("视频上传失败")
         },
        beforeUploadFile(file) {
        console.log("失身",file.size)    
        const isLt2M = file.size / 1024 / 1024 < 2048;
        if (!isLt2M) {
          this.$message.error('上传视频大小不能超过 2G!');
        }
            var date = new Date()
            var ext = getFileExtension(file.name)
            console.log("文件名",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){
          console.log(file.type)
          const isJPG = file.type === 'image/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.picshow = false
      },
      clickitem(){
        this.picshow = 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)
       },
       getEditVidoInfo(id){
           getEditVidoInfo(id,this.form).then(response=>{
               if(response.data.state==1){
                 var vidos = response.data.data.vidos;
                 this.form.vid_name = vidos.title;
                 this.form.vid_pic = vidos.imgs;
                 this.form.vio_upload = vidos.video_url;
                 console.log("得到的是什么?",this.form.vid_pic)
                 this.form.vid_type =  vidos.class_id
                 console.log("视频vidos",vidos)
               }    
           })        
       },
       
       getMenus(){
           getMenus().then(response=>{
               if(response.data.state ==1){
                   var categorys = response.data.data.categorys;
                   this.options = categorys;
                  console.log("分类号",categorys)
               }
           });
       },

       SumitVido(forName){
             const id = this.$route.params && this.$route.params.id;
             console.log("id是多少?",id)
             console.log("视频是什么",this.form.vio_upload)
             if(this.form.vio_upload == ""){
                this.form.vid_pic = this.form.vio_upload;
             }
          this.$refs[forName].validate((valid)=>{
              if(valid){
                 updataVidoInfo(id,this.form).then(response=>{
                     if(response.data.state == 1){
                         this.dialogVisible = true;      
                     }
                 })   
              }
          })
       },
        gobackList(){
         this.$router.push({path:'/articles/articleList'})
        },
        clear(){
          this.$confirm('是否确定取消编辑此文章/视频','取消提示',{
            dangerouslyUseHTMLString:true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
             this.$router.push({path:'/articles/articleList'})  
          }) 
        },

        Savedraft(forName){
           const id = this.$route.params && this.$route.params.id;
           console.log("id是多少?",id);
            this.form.vid_pic = this.form.vio_upload;
           this.$refs[forName].validate((valid)=>{
               if(valid){
                  SaveVidodraft(id,this.form).then(response=>{
                      if(response.data.state == 1){
                          this.dialogVisible = true;
                      }
                  });
               }
           })
        }
      },
      created(){
         const id = this.$route.params && this.$route.params.id;
         console.log("id是什么?",id)
         this.getEditVidoInfo(id);
         this.getMenus();
      }
    }
</script>

<style scoped>
      /*视频*/
  .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;
  }

    .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>
