<template>
  <u-upload class="uif-file-picker" :accept="accept" :ext="ext"
            :modifiers="modifiers" :disabled="disabled" @change="handlePicker"
            @focus="$emit('focus')" @blur="$emit('blur')">
    <template v-slot:default="{hover}">
      <u-input :name="name" :class="classes" :border="border" :size="size"
               :value="fileName" :placeholder="placeholder" :disabled="disabled"
               :focus="hover" readonly ellipsis v-bind="bindIcon"
               @icon-click="handleIconClick"></u-input>
    </template>
  </u-upload>
</template>

<script>
import UInput from '@uif/hq/src/components/input'
import UUpload from '@uif/hq/src/components/upload'
import {oneOf} from '@uif/hq/src/utils/assist'

export default {
  inheritAttrs: false,
  name: 'u-file-picker',
  components: {
    UInput,
    UUpload
  },
  props: {
    value: {
      default: null
    },
    name: {
      type: String
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择文件'
    },
    size: {
      validator (value) {
        return oneOf(value, ['small', 'default', 'large'])
      },
      default: 'default'
    },
    border: {
      validator (value) {
        return oneOf(value, ['none', 'line', 'rect'])
      },
      default: 'rect'
    },
    // input原生属性
    accept: {
      type: String
    },
    // 文件类型检查
    ext: {
      type: Array,
      default () {
        return []
      }
    },
    // 检查文件方法
    modifiers: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      currentValue: null,
      fileName: ''
    }
  },
  computed: {
    classes () {
      return [
        'uif-file-picker',
        {
          'uif-file-picker-available': !this.disabled
        }
      ]
    },
    // 右侧图标
    bindIcon () {
      if (this.clearable && !this.disabled && this.currentValue) {
        return {icon: 'circle-x', iconScene: 'action'}
      }
      return {icon: 'folder-opened', iconScene: 'none'}
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (val) {
        this.syncValue()
        this.$emit('sync', val)
      }
    }
  },
  created () {
  },
  mounted () {
  },
  methods: {
    syncValue () {
      if (this.value !== this.currentValue) {
        this.setCurrentValue(this.value)
      }
    },
    handlePicker (values) {
      this.setCurrentValue(values[0])
      this.setValue(values[0])
    },
    setCurrentValue (value) {
      this.currentValue = value
      this.fileName = value ? value.name : ''
    },
    setValue (value) {
      this.$emit('input', value)
      this.$emit('u-change', value)
    },
    handleIconClick (event) {
      if (this.clearable && this.value) {
        this.setCurrentValue(null)
        this.setValue(null)
        event.stopPropagation()
        return false
      }
    }
  }
}
</script>
