<template>
  <div class="upload">
    <div class="demo-upload-list" v-for="(item, idx) in uploadList" :key="idx">
      <template v-if="item.status === 'finished'">
        <video v-if="video" :src="item.url" controls="controls"></video>
        <img v-else :src="item.url" />
        <div class="demo-upload-list-cover">
          <Icon
            type="ios-trash-outline"
            @click.native="handleRemove(item)"
          ></Icon>
        </div>
      </template>
      <template v-else>
        <Progress
          v-if="item.showProgress"
          :percent="item.percentage"
          hide-info
        ></Progress>
      </template>
    </div>
    <Upload
      ref="upload"
      v-show="uploadList.length<maxLength"
      :show-upload-list="hideUploadList"
      :default-file-list="defaultList"
      :on-success="handleSuccess"
      :max-size="1024*150"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="beforeUpload"
      :data="uploadData"
      :multiple="multiple"
      type="drag"
      :action="uploadHost"
      style="display: inline-block;width:120px;"
    >
      <div style="width: 120px;height:120px;line-height: 120px;">
        <Icon type="ios-camera" size="20"></Icon>
      </div>
    </Upload>
  </div>
</template>
<script>
// import { oss } from '@/view/common/upload'
import {
  getQiNiuToken
} from '@/api/api'
export default {
  props: {
    value: {
      type: [String, Array],
      required: true // 文件url
    },
    maxLength: {
      type: [String, Number],
      default: 1, // 文件个数, 大于一时, multiple=true
      validator (value) {
        value = String(value)
        return !isNaN(parseInt(value, 10))
      }
    },
    video: {
      type: Boolean,
      default: false // 是否视频上传
    },
    hideUploadList: {
      type: Boolean,
      default: false // 是否显示上传列表
    }
  },
  data () {
    return {
      // 附件上传路径
      uploadHost: 'http://up-z2.qiniup.com/',
      // 附件上传携带参数
      uploadData: {},
      // 上传后返回的存储的文件名
      fileName: '',
      // 上传后返回的文件存储地址
      filePath: '',
      uploadList: [],
      defaultList: [],
      baseUrl: ''
    }
  },
  computed: {
    multiple: function () {
      return this.maxLength > 1
    }
  },
  watch: {
    value: {
      handler: function (val) {
        console.log(val)
        this.init(val)
      }
    //  immediate: true
    }
  },
  methods: {
    random_string (len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    handleRemove (file) {
      const fileList = this.$refs['upload'].fileList

      this.$refs['upload'].fileList.splice(fileList.indexOf(file), 1)
      this.updateFileList()
      this.$emit('del', file.url)
    },
    handleSuccess (res, file) {
      console.log(res)
      console.log(file)
      file.url = this.baseUrl + '/' + res.key
      file.name = res.key
      this.$emit('success', file.url)
    },
    /**
     * 供外部组件提取当前文件上传位置
     * @return this.uploadList[0].name
     */
    getData () {
      if (this.uploadList.length === 1) {
        const result = this.uploadList[0] && this.uploadList[0].url
        return result
      }
      if (this.uploadList.length > 1) {
        const urlList = this.uploadList.map((p) => {
          return p.url
        })
        return urlList
      }
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc:
          'File format of ' +
          file.name +
          ' is incorrect, please select jpg or png.'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File  ' + file.name + ' is too large, no more than 2M.'
      })
    },
    clearFiles () {
      // console.log('清除');
      this.$refs['upload'].clearFiles()
      this.updateFileList()
    },
    updateFileList (flag) {
      // flag 是否从外部更新进来的
      if (flag) {
        setTimeout(() => {
          this.uploadList = this.$refs['upload'].fileList
        }, 0)
      } else {
        this.uploadList = this.$refs['upload'].fileList
      }
    },
    init (val) {
      if (val) {
        console.log(val)
        const result = []
        if (typeof val === 'string') {
          result.push({
            url: val
          })
        } else {
          for (const f of val) {
            result.push({
              url: f
            })
          }
        }
        this.defaultList = result
        this.updateFileList(true)
      } else {
        this.clearFiles()
      }
    },
    // 在Upload组件的钩子before-upload中获取到生成的参数信息
    beforeUpload (file) {
      let fileNames = this.random_string(20) + file.name
      let parms = {
        fileName: fileNames
      }
      return getQiNiuToken(parms).then((res) => {
        this.baseUrl = res.data.domain
        this.$set(this.uploadData, 'token', res.data.token)
        this.$set(this.uploadData, 'key', fileNames)
      })
      // return oss(file.name).then(res => {
      //   this.uploadHost = res.host
      //   this.uploadData = res
      // })
    }
  },
  mounted () {
    // 必须这样初始化一下，否则上传第一张图片时会没有进度条
    this.uploadList = this.$refs['upload'].fileList
    this.init(this.value)
  }
}
</script>

<style lang="less">
.demo-upload-list {
  display: inline-block;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  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;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
