<template>
  <DatePicker
    :value="currentValue"
    @input.native="inputHandler"
    @on-change="changeHandler"
    transfer
    style="width: 100%;"
    :type="type"
  />
</template>
<script>
import create from '../utils/create'
import { DatePicker } from 'view-design'
import fecha from 'view-design/src/utils/date'

export default create({
  name: 'date-input',
  components: {
    DatePicker
  },
  props: {
    value: {
      required: false,
      validator (val) {
        return typeof val === 'string' || val === '' || val === null
      }
    },
    format: {
      type: String,
      defaul: 'yyyy-MM-dd'
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  computed: {
    type () {
      if (this.format.length < 12) {
        return 'date'
      } else {
        return 'datetime'
      }
    }
  },
  methods: {
    changeHandler (val) {
      this.currentValue = val
    },
    inputHandler (event) {
      this.currentValue = event.target.value
    }
  },
  watch: {
    currentValue (newval, oldval) {
      function getFormattedDate (val, formatter) {
        try {
          return fecha.format(fecha.parse(val, formatter), formatter)
        } catch (e) {
          return ''
        }
      }
      let str = newval ? getFormattedDate(newval, this.format) : ''
      this.$emit('input', str)
    },
    value (val) {
      this.currentValue = val
    }
  }
})
</script>
