<script>
import NBuilder from '@uif/next/lib/components/builder'
import NInput from '@uif/next/lib/components/input'
import NSelect from '@uif/next/lib/components/select'
import NDatePicker from '@uif/next/lib/components/date-picker'
import NFilePicker from '@uif/next/lib/components/file-picker'
import NSwitch from '@uif/next/lib/components/switch'
import NChanger from '@uif/next/lib/components/changer'
import NRadioGroup from '@uif/next/lib/components/radio-group'
import NCheckboxGroup from '@uif/next/lib/components/checkbox-group'
import {prop, normalizeValue} from '@uif/next/lib/utils/tools'
import {fireInputEvent} from '_common/formUtils'

function getComponent (input) {
  switch (input.type.toLowerCase()) {
    case 'text':
    case 'textarea':
    case 'password':
      return NInput
    case 'select':
      return NSelect
    case 'date':
    case 'minute':
    case 'time':
    case 'dates':
    case 'month':
    case 'months':
      return NDatePicker
    case 'file':
      return NFilePicker
    case 'switch':
      return NSwitch
    case 'checkbox':
      return NCheckboxGroup
    case 'radio':
      return NRadioGroup
    case 'changer':
      return NChanger
  }
}

export default {
  inheritAttrs: false,
  components: {NBuilder},
  props: {
    input: prop.object(),
    // 完整 inputs
    inputs: prop.array(),
    size: prop.inArray(['small', 'middle', 'large'], 'middle')
  },
  render (h) {
    const component = getComponent(this.input) || normalizeValue(this.input.getComponent, this.input)
    return h(component, {
      ref: 'item',
      props: {
        border: 'none',
        size: this.size,
        value: this.input.value,
        input: this.input,
        ...this.input,
        suffixIcon: null
      },
      on: {
        ...this.$listeners,
        // 双向绑定
        input: (value) => this.$set(this.input, 'value', value),
        // update 事件
        'u-update': (value) => this.onInputEvent('u-update', 'onUUpdate', value),
        // change 事件
        'u-change': (value) => this.onInputEvent('u-change', 'onUChange', value),
        // focus 事件
        'u-focus': (value) => this.onInputEvent('u-focus', 'onUFocus', value),
        // blur 事件
        'u-blur': (value) => this.onInputEvent('u-blur', 'onUBlur', value),
        // 绑定事件
        'u-bind': (name, value) => (this.input[name] = value)
      }
    })
  },
  methods: {
    onInputEvent (eventName, inputEventName, value) {
      fireInputEvent(inputEventName, value, this.input, this.inputs)
      this.$emit(eventName, this.input.name, value)
    }
  }
}
</script>
