<template>
    <div class="fl-uplaod-container"
      :id="uploadId"
    >

  
      <div class="el-upload el-upload--file-card"
        :class="{'is-disabled': disabled}"
        v-show="(!isQiniu || (isQiniu && token)) && fileList.length < length"
        :style="{width: width+'px', height: height+'px'}"
        @click.self="handleAdd"
      >
      <span class="el-file-plus" @click.self="handleAdd" :style="{fontSize:12+'px',marginTop: (-miniWidth/8)+'px'}"> 点击上传</span>
        <input  v-if="multiple"  multiple ref="uploadInput" @change="handleChange" type="file" :style="{width: 0, height: 0}" name="file" class="el-upload__input upload-input">
        <input  v-else ref="uploadInput" @change="handleChange" type="file" :style="{width:0, height: 0}" name="file" class="el-upload__input upload-input">
      </div>


        <div 
          :id="item.key"
          :class="{uploading: item.status=='uploading', 'is-success': item.status=='success', 'is-diabled': disabled}"
          class="upload-file" v-for="(item) in fileList" :key="item.key">
          <a class="el-upload-list__item-name" @click="handleClick(file)">
          <i class="el-icon-document"></i>{{item.name}}
          </a>
         
          <el-progress v-if="item.status=='uploading'" :width="miniWidth*0.9"  :stroke-width="2" class="upload-progress" :percentage="item.percent"></el-progress>
          <label v-if="item.status=='success'" class="item-status" >
          <i class="el-icon-upload-success el-icon-circle-check"></i>
          </label>

          <div class="uplaod-action" :style="{height: 27 + 'px'}" v-if="!disabled">
            <i class="el-icon-download" :title="$t('fm.upload.down')" @click="downloadFile(item)" :style="{'font-size': miniWidth/8+'px'}"></i>
            <i class="el-icon-delete" :title="$t('fm.upload.delete')" @click="handleRemove(item.key)" :style="{'font-size': miniWidth/8+'px'}"></i>
          </div>
        </div>
        <p class="upload-tip">上传格式支持：xlsx, word, excel, ppt, docx, mp3, wav, ape,大小不超过20MB</p>
    </div>
  </template>
  
  <script>
  import Viewer from 'viewerjs'
  import * as qiniu from 'qiniu-js'
  import { getFileExt } from '../../util/index.js'
  require('viewerjs/dist/viewer.css')
  export default {
    props: {
      value: {
        type: Array,
        default: () => []
      },
      width: {
        type: Number,
        default: 80
      },
      height: {
        type: Number,
        default: 32
      },
      token: {
        type: String,
        default: ''
      },
      domain: {
        type: String,
        default: ''
      },
      multiple: {
        type: Boolean,
        default: false
      },
      length: {
        type: Number,
        default: 9
      },
      isQiniu: {
        type: Boolean,
        default: false
      },
      isDelete: {
        type: Boolean,
        default: false
      },
      min: {
        type: Number,
        default: 0
      },
      meitu: {
        type: Boolean,
        default: false
      },
      isEdit: {
        type: Boolean,
        default: false
      },
      action: {
        type: String,
        default: ''
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        fileList: this.value.map(item => {
          return {
            key: item.key ? item.key : (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999),
            url: item.url,
            name: item.name,
            percent: item.percent ? item.percent : 100,
            status: item.status ? item.status : 'success'
          }
        }),
        viewer: null,
        uploadId: 'upload_' + new Date().getTime(),
        editIndex: -1,
        meituIndex: -1,
        acceptImg: ['.doc', '.xls', '.xlsx', '.pptx', '.word', '.excel', '.ppt', '.docx', '.mp3', '.wav', '.ape',]
      }
    },
    computed: {
      miniWidth () {
        if (this.width > this.height) {
          return this.height
        } else {
          return this.width
        }
      }
    },
    mounted () {
      this.$emit('input', this.fileList)
    },
    methods: {
      handleChange () {
        const files = this.$refs.uploadInput.files
        for (let i = 0; i < files.length; i++) {
          const file = files[i]
          const reader = new FileReader()
          const key = (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999)
          reader.readAsDataURL(file)
          reader.onload = () => {
            if (this.editIndex >= 0) {
  
              this.$set(this.fileList, this.editIndex, {
                key,
                url: reader.result,
                name: file.name,
                percent: 0,
                status: 'uploading'
              })
  
              this.editIndex = -1
            } else {
              this.fileList.push({
                key,
                url: reader.result,
                name: file.name,
                percent: 0,
                status: 'uploading'
              })
            }
  
            this.$nextTick(() => {
              if (this.isQiniu) {
                this.uplaodAction2(reader.result, file, key)
              } else {
                this.uplaodAction(reader.result, file, key)
              }
            })
          }
        }
        this.$refs.uploadInput.value = []
      }, 
      uplaodAction (res, file, key) {
        const fileType = getFileExt(file.name)
        const fileSize = file.size / (1024 * 1024)
        if (!this.acceptImg.includes(fileType)) {
          this.$message.error('请上传xlsx、word、excel、ppt 、doct、 mp3、wav、ape类型的文件')
          this.fileList.pop()
          return
        }
        if (fileSize > 20) {
          this.$message.error('文件大小不超过20MB')
          this.fileList.pop()
          return
        }
        const xhr = new XMLHttpRequest()
        
        const url = this.action
        xhr.open('POST', url, true)
        let formData = new FormData()
        formData.append('file', file)
  
        xhr.send(formData)
        // 没有到这一步---->>> 
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            
            let resData = JSON.parse(xhr.response)
            if (resData && resData.data) {
              this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
                ...this.fileList[this.fileList.findIndex(item => item.key === key)],
                url: resData.data,
                percent: 100
              })
              setTimeout(() => {
                this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
                  ...this.fileList[this.fileList.findIndex(item => item.key === key)],
                  status: 'success'
                })
                this.$emit('input', this.fileList)
              }, 200)
            } else {
              this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
                ...this.fileList[this.fileList.findIndex(item => item.key === key)],
                status: 'error'
              })
              this.fileList.splice(this.fileList.findIndex(item => item.key === key), 1)
            }
          }
        }
        xhr.onprogress = (res) => {
          console.log('progress', res)
          if (res.total && res.loaded) {
            this.$set(this.fileList[this.fileList.findIndex(item => item.key === key)], 'percent', res.loaded/res.total*100)
          }
        }
      },
      uplaodAction2 (res, file, key) {
        const _this = this
        const observable = qiniu.upload(file, key, this.token, {
          fname: key,
          mimeType: []
        }, {
          useCdnDomain: true,
          region: qiniu.region.z2
        })
        observable.subscribe({
          next (res) {
            _this.$set(_this.fileList[_this.fileList.findIndex(item => item.key === key)], 'percent', parseInt(res.total.percent))
            
          },
          error (err) {
            _this.$set(_this.fileList, _this.fileList.findIndex(item => item.key === key), {
              ..._this.fileList[_this.fileList.findIndex(item => item.key === key)],
              status: 'error'
            })
            _this.fileList.splice(_this.fileList.findIndex(item => item.key === key), 1)
          },
          complete (res) {
            _this.$set(_this.fileList, _this.fileList.findIndex(item => item.key === key), {
              ..._this.fileList[_this.fileList.findIndex(item => item.key === key)],
              url: _this.domain + res.key,
              percent: 100
            })
            setTimeout(() => {
              _this.$set(_this.fileList, _this.fileList.findIndex(item => item.key === key), {
                ..._this.fileList[_this.fileList.findIndex(item => item.key === key)],
                status: 'success'
              })
              _this.$emit('input', _this.fileList)
            }, 200)
          }
        })
      },
      handleRemove (key) {
        this.fileList.splice(this.fileList.findIndex(item => item.key === key), 1)
        this.$emit('input', this.fileList)
      },
      handleMeitu (key) {
  
        this.$emit('on-meitu', this.fileList.findIndex(item => item.key === key))
      },
      handleAdd () {
        if (!this.disabled) {
          this.editIndex = -1
          this.$refs.uploadInput.click()
        }
      },
      downloadFile(val){
       const a = document.createElement('a');
        a.setAttribute('href', val.url + '?response-content-type=application/octet-stream');
        a.setAttribute('download', val.name);
        a.click();
      },
      handlePreviewFile (key) {
        this.viewer && this.viewer.destroy()
        this.uploadId = 'upload_' + new Date().getTime()
        console.log(this.viewer)
        this.$nextTick(() => {
          this.viewer = new Viewer(document.getElementById(this.uploadId))
          this.viewer.view(this.fileList.findIndex(item => item.key === key))
        })
      }
    },
    watch: {
      'fileList': {
        deep: true,
        handler (val) {
          // this.$emit('input', this.fileList)
        }
      }
    }
  }
  </script>
  
  <style lang="scss">
    .upload-tip{
      margin: 0;
      padding: 0;


    }
    .el-upload-list__item-name{
      text-align: left !important;
      width: 100%;
    }
    // feat file
  .fl-uplaod-container{
    .is-disabled{
      position: relative;
  
      &::after{
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        // background: rgba(0,0,0,.1);
        content: '';
        display: block;
        cursor:not-allowed;
      }
    }
  
    .upload-file{
      margin: 0 10px 10px 0;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      border: none !important;
      border-radius: 0px !important;
      box-sizing: border-box;
      position: relative;
      vertical-align: top;
      height: 27px;
      width: 100%;
      &:hover{
        .uplaod-action{
          display: flex;
          cursor: pointer;
          height: 100px;
        }
        .item-status{
          display: none;
        }
      }
      .uplaod-action{
        position: absolute;
        bottom: 0;
        right: 0;
        left: 0;
        background: rgba(0,0,0,0.1);
        height: 100%;
        display: none;
        justify-content: flex-end;
        align-items: center;
        i{
          color: #000;
          cursor: pointer;
          font-size: 14px;
          margin: 0 5px;
        }
      }
      &.is-success{
        .item-status{
          position: absolute;
          right: -15px;
          top: -3px;
          width: 40px;
          height: 24px;
          text-align: center;
          transform: rotate(45deg);
          &>i{
            font-size: 14px;
            margin-top: 11px;
            color: #13ce66 !important;
            transform: rotate(-45deg);
          }
        }
      }
      &.uploading{
        &:before{
          display: block;
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0,0,0,0);
        }
      }
      .upload-progress{
        position: absolute;
        right: 0;
        .el-progress__text{
          color: #000;
          font-size: 12px !important;
          position: absolute;
          top: 0;
          right: 0;
        }
        .el-progress-bar{
          position: relative;
          right: 0;
          top: 10px;
          background: #fff;
          width: 100vw;
        }
      }
    }
    .el-upload--file-card{
      position: relative;
      overflow: hidden;
      background-color: #1890ff;
      border-color: #1890ff;
      margin-top: 2px;
      border-radius: 4px;
      .el-file-plus{
        position: absolute;
        color: #fff !important;
        top: 46%;
        left: 20%;
        font-family: element-icons !important;
        speak: none;
        font-style: normal;
        font-weight: 400;
        font-variant: normal;
        text-transform: none;
        line-height: 1;
        vertical-align: baseline;
        display: inline-block;
        -webkit-font-smoothing: antialiased;
      }
    }
    .upload-input{
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: block;
      opacity: 0;
      cursor: pointer;
    }
  
    .drag-img-list{
      display: block;
      .ghost{
        position: relative;
        &::after {
          width: 100%;
          height: 100%;
          display: block;
          content: '';
          background: #fbfdff;
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          border: 1px dashed #3bb3c2;
        }
      }
  
      &>div{
        cursor: move;
      }
    }
  }
  
  .viewer-container{
    z-index: 9999 !important;
  }
  </style>
  