<template>
  <div class="my-upload-image-cmp">
    <!-- :before-upload="beforeUpload" -->
    <el-upload
      :action="uploadUrl"
      :data="dataObj"
      :headers="{ Authorization }"
      :limit="limit"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="onChange"
      :on-success="onSuccess"
      :class="{disUoloadSty: noneBtnImg}"
      list-type="picture-card"
      accept="image/jpeg,image/gif,image/png,image/bmp"
    >
      <!-- :on-progress="onProgress"
      :on-change="onChange" -->
      <!-- :auto-upload="false" -->
      <slot>
        <i slot="default" class="el-icon-plus" />
      </slot>
      <!-- <div slot="file" slot-scope="{file}">
        <img
          class="el-upload-list__item-thumbnail"
          :src="file.url"
          alt=""
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in" />
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete" />
          </span>
        </span>
      </div> -->
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
// import { getToken } from '@/api/qiniu'
import { getFileHash } from '@/utils'
import { getToken } from '@/utils/auth'
const baseApi = process.env.VUE_APP_BASE_API
export default {
  name: 'UploadImage',
  props: {
    limit: {
      type: Number,
      default: 1
    },
    value: {
      type: [String, Array],
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      noneBtnImg: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,

      dataObj: {
        // token: '',
        // key: null,
        uploadType: 'PC'
        // key: '123.png'
      },
      // uploadUrl: 'http://upload.qiniup.com/'
      // uploadUrl: 'http://up-z2.qiniup.com'
      // uploadUrl: 'http://storage.cdlangli.com'
      // uploadUrl: 'http://qiniu.region.z2'
      uploadUrl: baseApi + '/commonLogin/upload',
      Authorization: getToken()
    }
  },
  watch: {
    value() {
      this.initData()
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      const { value } = this
      if (!value) {
        this.fileList = []
      } else if (typeof value === 'string') {
        this.fileList = value.split(',').map(item => ({
          status: 'success',
          url: item
        }))
      } else {
        this.fileList = value.map(item => ({
          status: 'success',
          url: item
        }))
      }
      this.noneBtnImg = this.fileList.length >= this.limit
    },
    beforeUpload(file) {
      // console.log(file)
      const { name } = file
      const extension = name.split('.')[1]
      getFileHash(file)
      const _self = this
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          getFileHash(file).then(res => {
            const key = `${res}.${extension}`
            const token = response.data
            _self._data.dataObj.token = token
            _self._data.dataObj.key = key
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    handleRemove(file, fileList) {
      this.noneBtnImg = fileList.length >= this.limit
      // console.log(fileList)
      this.submitData(fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    onChange(file, fileList) {
      // console.log(fileList)
      this.noneBtnImg = fileList.length >= this.limit
      // this.submitData(fileList)
    },
    onSuccess(response, file, fileList) {
      this.submitData(fileList)
    },
    onProgress(event, file, fileList) {
      // console.log(event, file, fileList)
    },
    submitData(fileList) {
      const urls = fileList.map((item) => {
        if (item.response) {
          return item.response.d
        } else {
          return item.url
        }
      })
      if (typeof this.value === 'string') {
        this.$emit('input', urls.join(','))
      } else {
        this.$emit('input', urls)
      }
    }
  }
}
</script>

<style lang="scss">
.my-upload-image-cmp{
  .disUoloadSty{
    .el-upload--picture-card{
      display:none;   /* 上传按钮隐藏 */
    }
  }
}
</style>
