<template>
  <view>
    <u-datetime-picker
      v-if="isShow"
      :value="datePickerValue"
      :show="isShow"
      :mode="type"
      placeholder="选择时间"
      @confirm="confirmDate"
      @cancel="isShow = false"
      @close="isShow = false"
      :minDate="minDate"
      :maxDate="maxDate"
      :formatter="formatter"
      :style="{ width: '100%' }"
    />
  </view>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    datePickerValue: {
      type: [String, Number],
      default: new Date().getTime()
    },
    minDate: {
      type: [String, Number],
      default: null
    },
    maxDate: {
      type: [String, Number],
      default: null
    },
    type: {
      type: [String, Number],
      default: 'datetime'
    }
  },

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

  methods: {
    showWin() {
      this.isShow = true
    },
    confirmDate(e) {
      this.$emit('input', this.formatTimestamp(e.value))
      this.$nextTick(() => {
        this.isShow = false
      })
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },
    formatTimestamp(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      if (this.type === 'datetime') {
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } else if (this.type === 'date') {
        return `${year}-${month}-${day}`
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
