<template>
  <l-label @click="click" :arrow="!disabled" :required="required" :title="title">
    {{ value || displayPlaceholder }}
    <l-datetime-panel
      v-if="datetimeModal"
      @confirm="confirm"
      @cancel="cancel"
      :val="value"
      :startYear="1900"
      ref="datetime"
      isAll
    />
  </l-label>
</template>

<script>
export default {
  name: 'l-datetime-picker',

  props: {
    title: {},
    disabled: {},
    placeholder: {},
    required: {},
    value: {}
  },

  data() {
    return {
      datetimeModal: false
    }
  },

  methods: {
    click(e) {
      if (this.disabled || this.datetimeModal) {
        return
      }

      this.datetimeModal = true
      this.$nextTick(() => {
        this.$refs.datetime.setDate(this.value)
        this.$refs.datetime.show()
        uni.$emit('modal', true)
        this.$emit('open')
      })
    },

    confirm({ selectRes }) {
      setTimeout(() => {
        this.datetimeModal = false
        this.$emit('input', selectRes)
        this.$emit('change', selectRes)
        uni.$emit('modal', false)
        this.$emit('close')
      }, 300)
    },

    cancel() {
      setTimeout(() => {
        this.datetimeModal = false
      }, 300)
      uni.$emit('modal', false)
      this.$emit('close')
    }
  },

  computed: {
    displayPlaceholder() {
      if (this.disabled) {
        return ''
      }

      if (this.placeholder) {
        return this.placeholder
      }

      return this.title ? `请选择${this.title}` : '请选择…'
    }
  }
}
</script>
