<template>
  <l-label @click="click" :class="className" :style="style" :arrow="!disabled" :required="required" :title="title">
    <!-- #ifndef MP-DINGTALK -->
    <picker
      @change="change"
      :value="value"
      :start="start"
      :end="end"
      :disabled="disabled"
      :class="[disabled ? '' : 'picker-arrow']"
      mode="time"
    >
      <view class="picker">{{ value || displayPlaceholder }}</view>
    </picker>
    <!-- #endif -->

    <!-- #ifdef MP-DINGTALK -->
    <text @click="click">{{ value || displayPlaceholder }}</text>
    <!-- #endif -->
  </l-label>
</template>

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

  props: {
    title: {},
    start: { default: '00:00' },
    end: { default: '23:59' },
    disabled: {},
    placeholder: {},
    value: {}
  },

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

      this.$emit('click', e)

      // #ifdef MP-DINGTALK
      const getCurrent = () => {
        const now = new Date()

        const hours = now
          .getHours()
          .toString()
          .padStart(2, '0')
        const minutes = now
          .getMinutes()
          .toString()
          .padStart(2, '0')

        return hours + ':' + minutes
      }

      const currentDate = this.value ? this.value : getCurrent()
      this.$emit('open')

      dd.datePicker({
        currentDate,
        format: 'HH:mm',
        success: ({ date }) => {
          if (date) {
            this.$emit('input', date + ':00')
            this.$emit('change', date + ':00')
          }
        },
        complete: () => {
          this.$emit('close')
        }
      })
      // #endif
    },

    change(e) {
      this.$emit('input', e.detail.value)
      this.$emit('change', e.detail.value)
    }
  },

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

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

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