<template>
  <n-upload tag="div" class="n-file-picker" :ext="ext" :multiple="multiple" :modifiers="modifiers" :disabled="disabled"
            @change="onFilesSelected" @u-focus="onFocus" @u-blur="onBlur">
    <n-form-refer v-model="isFocus" v-bind="{name, values, multiple, size, border,  disabled, placeholder,clearable, builder: builders.value}"
                  drop-icon-type="folder-opened" @u-update="onReferUpdateValues"></n-form-refer>
  </n-upload>
</template>

<script>
import vModel from '_common/vModel'
import NUpload from '@uif/next/lib/components/upload'
import NFormRefer from '@uif/next/lib/components/form-refer'
import {isArray, normalizeArray, prop, propsArray} from '@uif/next/lib/utils/tools'

function getStringify (file) {
  return normalizeArray(file).filter(file => file).map(file => `${file.name}_${file.type}_${file.size}`).join('&')
}

export default {
  name: 'n-file-picker',
  mixins: [vModel],
  components: {
    NUpload,
    NFormRefer
  },
  props: {
    // 表单名
    name: prop.string(),
    // 初始值 multiple 下 value 需为 Array
    value: {
      default: null
    },
    // 多选
    multiple: prop.boolean(),
    // 禁用
    disabled: prop.boolean(),
    // 可删除
    clearable: prop.boolean(true),
    // 选择框提示文本
    placeholder: prop.string('请选择文件'),
    // 大小
    size: propsArray(['small', 'middle', 'large'], 'middle'),
    // 边框
    border: propsArray(['none', 'line', 'rect'], 'rect'),
    // 自定义渲染
    builders: prop.object(() => ({value: null})),

    // 文件类型检查
    ext: {
      type: [Array, String],
      default: ''
    },
    // 检查文件方法
    modifiers: prop.array()
  },
  data () {
    return {
      isFocus: false,
      nValue: this.multiple && !isArray(this.value) ? [] : this.value
    }
  },
  computed: {
    values ({nValue}) {
      return normalizeArray(nValue).filter(file => file).map(file => ({label: file.name, value: file.name, file}))
    }
  },
  methods: {
    onFocus () {
      this.backup = getStringify(this.nValue)
      this.$emit('u-focus', this)
    },
    onBlur () {
      this.isFocus = false
      this.$emit('u-blur', this)
      if (getStringify(this.nValue) !== this.backup) {
        this.$emit('u-change', this.nValue)
      }
    },
    onFilesSelected (files) {
      this.nValue = this.multiple ? files : files[0] || null
      this.$emit('u-update', this.nValue)
    },
    // refer 点击删除按钮
    onReferUpdateValues (values) {
      const files = values.map(option => option.file)
      this.onFilesSelected(files)
      this.$emit('u-change', this.nValue)
    }
  }
}
</script>
