<template>
  <div class="component-upload-image" :class="{ 'is-disabled': disabled }">
    <MaterialSingle
      v-if="imageLimit <= 1"
      :value="singleUrl"
      type="image"
      :num="1"
      :width="width"
      :height="height"
      :allow-upload="allowUpload"
      @input="handleSingleInput"
    />
    <MaterialMulti
      v-else
      :value="urlArray"
      type="image"
      :num="imageLimit"
      :width="width"
      :height="height"
      :allow-upload="allowUpload"
      @input="handleMultiInput"
    />
  </div>
</template>

<script>
import MaterialSingle from '@/components/Material/single'
import MaterialMulti from '@/components/Material/index'

export default {
  name: 'ImageUpload',
  components: { MaterialSingle, MaterialMulti },
  props: {
    value: [String, Object, Array],
    /** 最多选取张数；兼容旧 prop num */
    limit: {
      type: Number,
      default: 10
    },
    num: {
      type: Number,
      default: undefined
    },
    width: {
      type: Number,
      default: 148
    },
    height: {
      type: Number,
      default: 148
    },
    disabled: {
      type: Boolean,
      default: false
    },
    /** 素材库弹窗内是否允许上传新素材 */
    allowUpload: {
      type: Boolean,
      default: true
    },
    // 以下保留兼容，不再使用
    fileSize: Number,
    fileType: Array,
    isShowTip: Boolean,
    type: String
  },
  computed: {
    imageLimit() {
      return this.num != null ? this.num : this.limit
    },
    singleUrl() {
      if (!this.value) return ''
      if (Array.isArray(this.value)) return this.value[0] || ''
      return String(this.value).split(',').filter(Boolean)[0] || ''
    },
    urlArray() {
      if (!this.value) return []
      if (Array.isArray(this.value)) return this.value.filter(Boolean)
      return String(this.value).split(',').filter(Boolean)
    }
  },
  methods: {
    handleSingleInput(url) {
      this.$emit('input', url || '')
    },
    handleMultiInput(arr) {
      const list = Array.isArray(arr) ? arr.filter(Boolean) : []
      this.$emit('input', list.join(','))
    }
  }
}
</script>

<style scoped lang="scss">
.is-disabled {
  pointer-events: none;
  opacity: 0.6;
}
</style>
