<template>
  <base-render :render="inputRender" :params="input"></base-render>
</template>

<script>
import BaseRender from '@uif/hq/lib/components/base-render'
import Input from '@uif/hq/lib/components/input'
import Select from '@uif/hq/lib/components/select'
import DatePicker from '@uif/hq/lib/components/date-picker'
import FilePicker from '@uif/hq/lib/components/file-picker'
import Switch from '@uif/hq/lib/components/switch'
import RadioGroup from '@uif/hq/lib/components/radio-group'
import CheckboxGroup from '@uif/hq/lib/components/checkbox-group'
import {assign, addAttr} from '@uif/hq/lib/utils/object'
import {toString} from '@uif/hq/lib/utils/format'

function getComponentByInput (input) {
  switch (input.type.toLowerCase()) {
    case 'text':
    case 'textarea':
    case 'password':
      return Input
    case 'select':
      return Select
    case 'date':
    case 'minute':
    case 'time':
      return DatePicker
    case 'file':
      return FilePicker
    case 'switch':
      return Switch
    case 'checkbox':
      return CheckboxGroup
    case 'radio':
      return RadioGroup
    default:
      return input.component
  }
}

export default {
  inheritAttrs: false,
  components: {BaseRender},
  props: {
    input: {
      type: Object,
      default () {
        return {}
      }
    },
    // 是否强制 transfer
    transfer: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'default'
    }
  },
  data () {
    return {
    }
  },
  methods: {
    inputRender (h) {
      return h(getComponentByInput(this.input), {
        class: this.input.type === 'textarea' ? this.textareaClasses() : {},
        props: assign({
          input: this.input,
          border: 'none',
          value: this.input.value,
          size: this.size,
          transfer: this.transfer
        }, this.input),
        on: assign({}, this.$listeners, this.input.on, {
          input: (value) => this.$set(this.input, 'value', value),
          focus: this.handleFocus,
          blur: this.handleBlur,
          'u-change': this.handleUChange
        })
      })
    },
    handleUChange (value) {
      this.handleAutoRows(true)
      this.$emit('u-change', this.input.name, value)
    },
    handleFocus () {
      this.handleAutoRows(true)
      this.$emit('focus', this.input.name)
    },
    handleBlur () {
      this.handleAutoRows(false)
      this.$emit('blur', this.input.name)
    },
    textareaClasses () {
      const classes = {
        'auto-rows': this.input.autoRows
      }
      addAttr(classes, 'auto-rows-' + this.size, this.input.autoRows)
      return classes
    },
    // 自动行高
    handleAutoRows (setAuto) {
      if (this.input.type === 'textarea' && this.input.autoRows) {
        const rows = setAuto ? toString(this.input.value).split(/\r|\n/).length : 1
        if (this.input.rows !== rows) {
          this.$set(this.input, 'rows', rows)
        }
      }
    }
  }
}
</script>
