<template>
  <div v-if="mode === 'time'">
    <a-date-picker
      v-model="modelValue"
      :placeholder="placeholder"
      :show-time="isShowTime"
      :format="modeFormat"
      @change="onDateChange"
      style="width: 100%"
    />
  </div>
  <div v-else>
    <a-date-picker
      v-model="modelValue"
      :placeholder="placeholder"
      :mode="mode"
      :open="isOpen"
      :format="modeFormat"
      @openChange="isOpen = !isOpen"
      @panelChange="onPanelChange"
      @change="onDateChange"
      style="width: 100%"
    />
  </div>
</template>

<script>
import * as dayjs from 'dayjs'

export default {
  name: 'HDatePicker',

  /**
   * 二次封装 DatePicker
   * @property {String|Object} value v-model语法糖
   * @property {String} mode 日期类型 ['time'|'date'|'month'|'year']
   * @property {String} format 格式化类型 [仅 mode='time' 时生效]
   * @property {String} placeholder 提示语
   * @author Matrix
   * @since 2022/09/30
   */
  props: {
    value: {
      type: [String, Object],
      required: false,
      default: null
    },
    mode: {
      type: String,
      required: false,
      default: 'time'
    },
    format: {
      type: String,
      required: false,
      default: 'YYYY-MM-DD HH:mm:ss'
    },
    placeholder: {
      type: String,
      required: false,
      default: '请选择时间'
    }
  },
  computed: {
    isShowTime() {
      return this.modeFormat.indexOf('HH') > 0
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.modelValue = dayjs(val).format(this.modeFormat)
        }
      },
      immediate: true
    },
    mode: {
      handler(type) {
        switch (type) {
          case 'year':
            this.modeFormat = 'YYYY'
            break
          case 'month':
            this.modeFormat = 'YYYY-MM'
            break
          case 'date':
            this.modeFormat = 'YYYY-MM-DD'
            break
          default:
            this.modeFormat = this.format
            break
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      isOpen: false,
      modelValue: this.value,
      modeFormat: this.format
    }
  },
  methods: {
    /**
     * 日期面板变化时的回调
     * @param value
     * @author Matrix
     * @since 2022/09/30
     */
    onPanelChange(value) {
      const dateTime = dayjs(value).format(this.modeFormat)
      this.$emit('input', dateTime)
      this.$emit('change', dateTime)
      this.isOpen = !this.isOpen
    },

    /**
     * 时间发生变化的回调
     * @param {Moment} date
     * @author Matrix
     * @since 2022/09/30
     */
    onDateChange(date) {
      const dateTime = date ? dayjs(date).format(this.modeFormat) : null
      this.$emit('input', dateTime)
      this.$emit('change', dateTime)
    }
  }
}
</script>
