<template>
  <span class="uif-upload-image">
    <template v-if="value">
      <span class="image-bg image-bg-source" :style="styles" @click="onClick"></span>
      <span v-if="remove && !disabled" class="image-bg image-bg-mask" @click="setValue('')">
        <u-icon type="trash" class="mask-icon"></u-icon>
        <span class="mask-text">删除</span>
      </span>
    </template>
    <span v-else-if="uploading" class="image-bg image-bg-uploading">
      <u-icon type="image" class="image-icon"></u-icon>
    </span>
    <u-upload v-else class="image-bg" accept="image/*" :disabled="disabled" v-bind="$attrs" @change="onUpload">
      <u-icon type="camera" class="image-icon"></u-icon>
    </u-upload>
  </span>
</template>

<script>
import {isFunction} from '@uif/hq/src/utils/assist'
import UUpload from '@uif/hq/src/components/upload'
export default {
  inheritAttrs: false,
  name: 'u-upload-image',
  components: {
    UUpload
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    upload: {
      type: Function,
      default: null
    },
    remove: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    ext: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      uploading: false
    }
  },
  computed: {
    styles () {
      return this.value ? 'background-image: url(' + this.value + ')' : null
    }
  },
  methods: {
    onUpload ([file]) {
      this.uploading = true
      if (isFunction(this.upload)) {
        Promise.resolve(this.upload(file))
          .then(value => this.next(value))
          .catch(() => this.next())
      } else {
        this.$emit('upload', file, (value) => this.next(value))
      }
    },
    next (value) {
      this.uploading = false
      value && this.setValue(value)
    },
    setValue (value) {
      this.$emit('input', value)
    },
    onClick () {
      this.$emit('click', this.value)
    }
  }
}
</script>
