<template>
  <!-- #ifndef MP-DINGTALK -->
  <l-label @click="click" :arrow="!disabled" :required="required" :title="title" :class="className" :style="style">
    {{ value || displayPlaceholder }}
    <l-datetime-panel
      v-if="datetimeModal"
      @confirm="confirm"
      @cancel="cancel"
      :val="value"
      :startYear="1900"
      ref="datetime"
      allShow
      isAll
    />
  </l-label>
  <!-- #endif -->

  <!-- #ifdef MP-DINGTALK -->
  <l-label :arrow="arrow" :required="required" :title="title" :class="className" :style="style">
    <text @click="click">{{ value || displayPlaceholder }}</text>
  </l-label>
  <!-- #endif -->
</template>

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

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

  // #ifndef MP-DINGTALK
  data() {
    return {
      datetimeModal: false
    }
  },
  // #endif

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

      // #ifndef MP-DINGTALK
      // 支付宝
      if (this.datetimeModal) {
        return
      }

      const datetimePanel = this.$refs.datetime
      this.datetimeModal = true

      this.$nextTick(() => {
        datetimePanel.setDate(this.value)
        datetimePanel.show()
        this.$emit('open')
      })
      // #endif

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

        const year = now.getFullYear().toString()
        const month = (now.getMonth() + 1).toString().padStart(2, '0')
        const date = now
          .getDate()
          .toString()
          .padStart(2, '0')

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

        return `${year}-${month}-${date} ${hours}:${minutes}`
      }

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

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

    // #ifndef MP-DINGTALK
    confirm({ selectRes }) {
      setTimeout(() => {
        this.datetimeModal = false
        this.$emit('input', selectRes)
        this.$emit('change', selectRes)
        this.$emit('close')
      }, 300)
    },

    cancel() {
      setTimeout(() => {
        this.datetimeModal = false
      }, 300)
      this.$emit('close')
    }
    // #endif
  },

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

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

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