<template>
  <div class="app-upload">
    <draggable
      v-model="fileList"
      group="people"
      class="file-list el-upload-list--picture-card"
      @end="onEnd"
      v-if="showFileList"
    >
      <div class="file-item" v-for="(file, index) in fileList" :key="index">
        <!-- <el-image style="width: 100%; height: 100%" :src="file.url" :preview-src-list="fileList.map(item => item.url)"> -->
        <img :src="file.url" />
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!$attrs.disabled" class="el-upload-list__item-delete" @click="handleRemove(index)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </draggable>
    <el-upload
      action="https://webapp-pub.oss-cn-beijing.aliyuncs.com"
      type="drag"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :show-file-list="false"
      :on-exceed="handleExceed"
      :data="data"
      v-bind="$attrs"
      v-on="$listeners"
      style="display: inline"
    >
      <slot>
        <i class="el-icon-plus"></i>
      </slot>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="previewFile.url" />
    </el-dialog>
  </div>
</template>
<script>
import { getSignature } from '@/api/base'
import md5 from 'blueimp-md5'
import draggable from 'vuedraggable'
export default {
  name: 'AppUpload',
  components: { draggable },
  props: {
    value: { type: [String, Array] },
    prefix: { type: String, default: 'upload/shop-admin/' },
    showFileList: { type: Boolean, default: true }
  },
  data() {
    return {
      data: {}, // 请求参数
      fileList: [], // 文件列表
      dialogVisible: false,
      previewFile: {},
      message: null
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (!value) {
          return
        }
        let fileList = []
        if (this.isMultiple) {
          fileList = value.map(item => {
            return { name: item.name || item, url: item.url || item }
          })
        } else {
          fileList.push({ name: '附件', url: value })
        }
        this.fileList = [...fileList]
      }
    }
  },
  computed: {
    isMultiple() {
      return Array.isArray(this.value)
    }
  },
  methods: {
    beforeUpload(file) {
      const limit = this.$attrs.limit
      if (limit && this.fileList.length >= limit) {
        this.message && this.message.close()
        this.message = this.$message({ type: 'error', message: '文件超出个数限制' })
        return false
      }
      const fileName = file.name
      const key = this.prefix + md5(fileName + new Date().getTime()) + fileName.substr(fileName.lastIndexOf('.'))
      return new Promise((resolve, reject) => {
        getSignature()
          .then(response => {
            const { accessid, policy, signature, host } = response
            this.data = { key, OSSAccessKeyId: accessid, policy, signature, success_action_status: '200' }
            file.url = `${host}/${key}`
            resolve(true)
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    handleSuccess(response, file) {
      let value = null
      if (this.isMultiple) {
        const limit = this.$attrs.limit
        if (limit && this.fileList.length >= limit) {
          return
        }
        this.fileList.push({ name: file.name, url: file.raw.url })
        value = this.fileList
      } else {
        this.fileList = [file.raw.url]
        value = file.raw.url
      }
      this.$emit('input', value)
      this.dispatch('ElFormItem', 'el.form.change', value)
    },
    // 删除
    handleRemove(index) {
      this.fileList.splice(index, 1)
      this.$emit('input', this.fileList)
      this.dispatch('ElFormItem', 'el.form.change', this.fileList)
    },
    // 预览
    handlePreview(file) {
      this.previewFile = file
      this.dialogVisible = true
    },
    handleExceed() {
      this.$message({ type: 'error', message: '文件超出个数限制' })
    },
    onEnd() {
      this.$emit('input', this.fileList)
    },
    dispatch(componentName, eventName, params) {
      let parent = this.$parent || this.$root
      let name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.componentName
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params))
      }
    }
  }
}
</script>
<style lang="scss">
.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  object-fit: cover;
}
.el-upload-list__item {
  transition: none !important;
}
.file-list {
  margin: 0;
  display: inline;
  vertical-align: top;
}
.file-item {
  position: relative;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  margin: 0 8px 8px 0;
  display: inline-block;
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
