<template>
  <div>
    <div class="upload">
      <div class="upload-img" v-if="img">
        <img :src="componentKey === 'freedomVideo' ? `${img}?vframe/jpg/offset/1` : img" v-if="isUrl">
        <cr-icon :type="img" class="upload-img-none-icon" v-else />
       <!-- <Icon type="image" size="20" class="upload-img-none-icon"></Icon> -->
        <div class="upload-img-cover">
          <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
        </div>
      </div>
      <div :id="containerId" class="upload-container">
        <Progress v-if="percent" vertical :percent="percent"></Progress>
        <div :id="id">
          <Icon type="camera" size="20"></Icon>
        </div>
      </div>
    </div> 
    <Input v-if="showInput" v-model="img" @input="handleImgUrlChange"></Input>
  </div>
</template>        
<script>   
  import '@/service/qiniu.service';
  import config from '@/config';
  import uuidv4 from 'uuid/v4';

  // const id = uuidv4().substr(0, 8);

  export default {
    props: {
      value: String,
      showInput: {
        type: Boolean,
        default: true
      },
      componentKey: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        id: uuidv4().substr(0, 8),
        percent: 0,
        img: this.value,
        fileType: ''
      }
    },
    computed: {
      containerId() {
        return `container_${this.id}`;
      },
      isUrl() {
        return /(https|http):\/\//gi.test(this.img);
      }
    },
    watch: {
      value: {
        handler(newVal) {
          this.img = newVal;
        },
        immediate: true
      }
    },
    methods: {
      handleRemove () {
        this.img = '';
        this.$emit('input', this.img);
        this.$emit('change', this.img);
      },
      handleImgUrlChange(val) {
        this.$emit('input', this.img);
        this.$emit('change', this.img);
      },
      uploadQiniu() {
         var uploader = Qiniu.uploader({
           runtimes: 'html5', // 上传模式,依次退化
           browse_button: this.id, // 上传选择的点选按钮，**必需**
           uptoken_url: 'https://opapi.xyqb.com/upload/getToken',
           // uptoken_url: `${config.apiHost}/upload/getToken`, //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
           save_key: true, // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK会忽略对key的处理
           domain: config.qiniuHost, // bucket 域名，下载资源时用到，**必需**
           get_new_uptoken: true, // 设置上传文件的时候是否每次都重新获取新的token
           container: this.containerId, // 上传区域DOM ID，默认是browser_button的父元素，
           max_file_size: '10mb', // 最大文件体积限制
           max_retries: 3, // 上传失败最大重试次数
           chunk_size: '4mb', // 分块上传时，每片的体积
           auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
           init: {
              FilesAdded: (up, files) => {
                if (this.componentKey === 'freedomVideo') {
                  console.log(files.length)
                  if (files.length > 1) {
                    up.removeFile(files[0]);
                    this.$toast('视频背景只允许上传单个文件');
                    return false;
                  }
                  console.log(files[0].type, 999)
                  if (files[0].type.indexOf('video') === -1) {
                    up.removeFile(files[0]);
                    this.$toast('只允许上传视频格式文件');
                    return false;
                  }
                  // 自由容器视频背景，只允许上传video
                }
              },
              FileUploaded: (up, file, info) => {
               // console.log(this);
               this.percent = 0;
               var res = JSON.parse(info);
               if (res.businessCode === '0001') {
                 this.$Notice.error({
                   title: res.msg,
                   desc: '',
                 });
               } else {
                 this.$Notice.success({
                   title: '上传成功',
                   desc: '',
                 });
                 this.img = config.qiniuHost + '/' + res.hash;
                 this.$emit('input', this.img);
                 this.$emit('change', this.img);
                 // this.url = config.qiniuHost + res.hash;
               }
              },
              BeforeUpload: (up, file) => {
                const {type, size} = file;
                console.log(type);
                let limit = 0;
                let fileType = '';
                // 来自量子积木v1.5需求中的优化点
                if (type === 'image/gif') {
                  // gif限制5M
                  this.fileType = 'image';
                  limit = 5 * 1024 * 1024;
                   if (size > limit) {
                    this.$toast('gif图大小不允许超过5Mb');
                    up.removeFile(file);
                    return false;
                  }
                } else if (type.toLowerCase().indexOf('video/') === 0) {
                  // 视频文件，限制4M
                  this.fileType = 'video';
                  limit = 4 * 1024 * 1024;
                  if (size > limit) {
                    this.$toast('文件大小不允许超过4Mb');
                    up.removeFile(file);
                    return false;
                  }
                } else {
                  // 其他格式限制800KB
                  this.fileType = 'image';
                  limit = 800 * 1024;
                  if (size > limit) {
                    this.$toast('文件大小不允许超过800Kb');
                    up.removeFile(file);
                    return false;
                  }
                }
                // if ()
                // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                this.percent = 0;
              },
              UploadProgress: (up, file) => {
                // var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                this.percent = file.percent;
                console.log('UploadProgress', file.percent);
              },
              Error: (up, err, errTip) => {
                this.percent = 0;
              }
           },
         });
       },
    },
    
    mounted () {
      this.uploadQiniu();
    }
  }
</script>
<style lang="less" scoped>
  .upload {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    width: 100%;
    overflow: hidden;

    &-img {
      display: inline-block;
      width: 60px;
      height: 60px;
      text-align: center;
      line-height: 60px;
      border: 1px solid transparent;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
      margin-right: 4px;
      z-index: 1;

      img {
        width: 100%;
        height: 100%;
      }

      &-none-icon {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: #fff;
        z-index: 1;
        line-height: 58px;
        border: 1px solid #dddee1;
      }

      &-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        z-index: 3;

        i {
          margin: 0 2px;
          color: #fff;
          font-size: 20px;
          cursor: pointer;
        }
      }

      &:hover {
        .upload-img-cover {
          display: block;
        }
      }
    }

    &-container {
      text-align: center;
      border: 1px dashed;
      width: 56px;
      height: 56px;
      line-height: 56px;

      #upload_pic {

      }

      /deep/ .ivu-progress {
        box-sizing: content-box;
        height: 50px;
        line-height: 50px;
      }
    }
  }
</style>