<template>
  <div>
    <div
      class="demo-upload-list"
      v-for="(item, index) in uploadList"
      :key="'img-' + index"
      :style="uploadStyle"
    >
      <template v-if="item.status === 'finished'">
        <video :src="item.url" v-if="type==='video'"></video>
        <img :src="getImgUrl(item)" v-else/>
        {{ item.url }}
        <div class="demo-upload-list-cover" v-show="!readonly || showWatch">
          <Icon
            v-if="showWatch && type != 'apk'"
            type="md-eye"
            @click.native="handleDetail(item)"
            :size="iconSize"
          ></Icon>
          <Icon
            v-if="!readonly"
            type="md-trash"
            @click.native="handleRemove(index)"
            :size="iconSize"
          ></Icon>
        </div>
      </template>
      <template v-else>
        <Progress
          v-if="item.showProgress"
          :percent="item.percentage"
          hide-info
        ></Progress>
      </template>
    </div>
    <Upload
      v-show="
        uploadList.length < maxNum &&
        (!readonly || insideDefaultList.length == 0)
      "
      ref="upload"
      :headers="{token: $store.state.admin.token, adminId: $store.state.admin.uid}"
      :show-upload-list="false"
      :default-file-list="insideDefaultList"
      :on-success="handleSuccess"
      :accept="fileAccept"
      :format="fileFormat"
      :max-size="maxSize * 1024"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      :on-progress="handleOnProgress"
      :on-error="handleErr"
      type="drag"
      :action="uploadUrl"
      :style="{ display: 'inline-block', width: width + 'px' }"
      :disabled="readonly"
    >
      <div :style="uploadStyle">
        <Icon :type="iconType" :size="iconSize"></Icon>
      </div>
    </Upload>

    <Modal
      v-model="detailModal"
      footer-hide
      class="upload-detail-modal"
      class-name="vertical-center-modal"
      :width="50"
    >
      <img :src="detailSrc" alt v-if="type == 'image'" style="height: 100%;width: 100%;object-fit: contain;" />
      <video
        :src="detailSrc"
        v-if="detailModal && type == 'video'"
        webkit-playsinline
        playsinline
        x5-playsinline
        controls="controls"
        style="width: 100%;height: 100%"
      />
    </Modal>
  </div>
</template>
<script>
import { uploadImgUrl, uploadVideoUrl, uploadApkUrl, uploadNftUrl } from '@/api/apiConfig'
import { apiVerify } from '@/api/apiVerify'
import { getNameFromUrl, getPosterFromVideoUrl } from '@/libs/tools'
import AndroidBg from '@/assets/images/android-bg.jpg'
import { put, formatTime, getFileNameUUID } from '@/libs/ali-oss'
export default {
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    maxNum: {
      type: Number,
      default: 1
    },
    // 文件大小限制 单位MB
    maxSize: {
      type: Number,
      default: 6
    },
    defaultList: {
      type: Array,
      default: () => {
        return []
      }
    },
    width: {
      type: Number,
      default: 60
    },
    iconType: {
      type: String,
      default: 'ios-camera'
    },
    iconSize: {
      type: Number,
      default: 20
    },
    type: {
      type: String,
      default: 'image'
    },
    readonly: {
      type: Boolean,
      default: false
    },
    showWatch: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    fileAccept () {
      if (this.type === 'image') {
        return '.jpg, .jpeg, .png, .gif,.xlsx'
      } else if (this.type === 'video') {
        return '.mp4,.mkv'
      } else if (this.type === 'apk') {
        return '.apk, .xlsx, '
      } else if (this.type === 'NFT') {
        return '.jpg, .jpeg, .gif, .bmp, .png,.mp4, .mp3, .wav, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .txt '
      }
    },
    fileFormat () {
      if (this.type === 'image') {
        return ['jpg', 'jpeg', 'png', 'gif', 'xlsx']
      } else if (this.type === 'video') {
        return ['mp4', 'mkv']
      } else if (this.type === 'apk') {
        return ['apk', 'xlsx']
      } else if (this.type === 'NFT') {
        return ['jpg', 'jpeg', 'gif', 'bmp', 'png', 'mp4', 'mp3', 'wav', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt']
      }
    },
    uploadUrl () {
      if (this.type === 'image') {
        return uploadImgUrl
      } else if (this.type === 'video') {
        return uploadVideoUrl
      } else if (this.type === 'apk') {
        return uploadApkUrl
      } else if (this.type === 'NFT') {
        return uploadNftUrl
      }
    },

    uploadStyle () {
      return {
        width: this.width + 'px',
        height: this.width + 'px',
        lineHeight: this.width + 'px'
      }
    },
    insideDefaultList () {
      let list = []
      this.defaultList.forEach((url) => {
        list.push({
          url,
          name: getNameFromUrl(url)
        })
      })
      return list
    }
  },
  data () {
    return {
      uploadList: [],
      detailModal: false,
      detailSrc: ''
    }
  },
  watch: {
    value: {
      handler (val) {
        let fileList = this.$refs.upload.fileList
        fileList.splice(0, fileList.length)
        let tempIndex = 0
        val.forEach((item) => {
          fileList.push({
            url: item,
            name: getNameFromUrl(item),
            status: 'finished',
            percentage: 100,
            uid: Date.now() + tempIndex++
          })
        })
        this.uploadList = fileList
      },
      deep: true
    }
  },
  methods: {
    getImgUrl (item) {
      if (this.type === 'image') {
        return item.url
      } else if (this.type === 'video') {
        return getPosterFromVideoUrl(item.url)
      } else if (this.type === 'apk') {
        return AndroidBg
      } else if (this.type === 'NFT') {
        return AndroidBg
      }
    },
    handleRemove (index) {
      this.uploadList.splice(index, 1)
      this.emitChange()
    },
    handleDetail (item) {
      this.detailSrc = item.url
      this.detailModal = true
    },
    handleSuccess (res, file, fileList) {
      apiVerify({
        res: { data: res },
        success: () => {
          file.url = res.data
          file.name = getNameFromUrl(res.data)
          this.emitChange()
        },
        error: () => {
          let index = fileList.indexOf(file)
          fileList.splice(index, 1)
          this.$Notice.error({ title: res.msg })
          this.emitChange()
        }
      })
    },
    emitChange () {
      let urlList = []
      this.uploadList.forEach((item) => {
        item && item.url && urlList.push(item.url)
      })
      this.$emit('input', urlList)
    },
    handleFormatError (file) {
      console.log(file)
      this.$Notice.warning({
        title: '文件格式不正确'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: `上传文件不得超过 ${parseFloat(this.maxSize).toFixed(1)} MB！`
      })
    },
    handleOnProgress (event, file, fileList) {},
    handleBeforeUpload (file) {},
    handleErr () {
      this.$Notice.error({ title: '上传失败，请稍后再试！' })
    }
    // async uploadFile (file, type) {
    //   this.editorLoading = true

    //   let dateStr = formatTime(Date.now(), 'yyyyMMdd')
    //   let fileName = getFileNameUUID() + '.' + file.name.split('.')[1]
    //   let objName = `information/${type}/${dateStr}/${fileName}`

    //   let res = await put(objName, file)
    //   // let url = await signatureUrl(objName);
    //   this.editorLoading = false
    //   return res.url
    // }

  },
  mounted () {
    this.uploadList = this.$refs.upload.fileList
  }
}
</script>
<style lang="less">
.demo-upload-list {
  display: inline-block;
  /* width: 60px;
  height: 60px; */
  text-align: center;
  /* line-height: 60px; */
  border-radius: 5px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 5px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.demo-upload-list video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.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;
}
.upload-detail-modal {
  .ivu-modal-content {
    background: transparent;
    border: none;
    box-shadow: none;
    -webkit-box-shadow: none;
    padding: 20px;
  }
  .ivu-icon-ios-close {
    color: #fff;
  }
  .ivu-modal-body{
    height: 700px;
  }
}
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;

  .ivu-modal {
    top: 0;
  }
}
</style>
