<template>
  <el-date-picker :value="tmpValue" :type="type" placeholder="选择日期时间" @change="startDateChange" :format="dateFormat" :value-format="dateFormat" @input="inputHandler">
  </el-date-picker>
</template>

<style scoped>

</style>

<script>
import util from '@src/common/util.js'
export default {
  props: [
    'value',
    'config'
  ],

  data() {
    return {
      type: 'date',
      dateFormat: 'yyyy-MM-dd',
      tmpValue: ''
    }
  },

  watch: {
    config(val) {
      this.type = val.type || 'date'
      this.dateFormat = this.type === 'datetime' ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd'
    },

    value(val) {
      this.tmpValue = val
    }
  },

  created() {
    this.tmpValue = this.value
  },

  mounted() {
    this.type = this.config.type || 'date'
    if (this.type === 'datetime') {
      this.dateFormat = 'yyyy-MM-dd HH:mm:ss'
    }
  },

  methods: {
    inputHandler(val) {
      this.tmpValue = this.validateDate(val)
      this.$emit('input', this.tmpValue)
    },
    startDateChange(val) {
      this.tmpValue = val
      this.$emit('input', this.tmpValue)
    },
    blurDateChange(val) {
      this.tmpValue = this.validateDate(val.valueOnOpen | val)
      this.$emit('input', this.tmpValue)
    },
    validateDate(val) {
      try {
        new Date(val)
      } catch (e) {
        util.showError('日期格式错误')
        return ''
      }
      return val
    }
  }
}
</script>
