<template>
  <l-label :class="className" :style="style" :arrow="!disabled" :required="required" :title="title">
    <!-- #ifndef MP-DINGTALK -->
    <picker @change="change" :fields="fields" :disabled="disabled" :value="value" :start="start" :end="end" mode="date">
      <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-date-picker',

  props: {
    title: {},
    start: { default: '1900-01-01' },
    end: { default: '2100-01-01' },
    fields: { default: 'day' },
    disabled: {},
    placeholder: {},
    required: {},
    value: {}
  },

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

      this.$emit('click')

      // #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')

        return `${year}-${month}-${date}`
      }

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

      dd.datePicker({
        currentDate,
        format: 'yyyy-MM-dd',
        success: ({ date }) => {
          if (date) {
            this.$emit('input', date)
            this.$emit('change', date)
          }
        },
        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>
