<template>
  <div class="x-date-panel" @click.stop>
    <div class="x-date-panel-day">
      <day ref="vDate" :selected-date="selectedDate" :format="format" :disabled-date="disabledDate" @change="dayChange"></day>
    </div>
    <confirm
      v-if="isConfirm()"
      ref="confirm"
      :format="format"
      :hours="hours"
      type="date"
      @confirm-btn="confirmEvent()"
      @cancel="cancel()"
      @time-change="timeChange"
    >
      <template slot="confirm">
        <slot name="confirm"></slot>
      </template>
    </confirm>
  </div>
</template>

<script>

import day from '../base/day.vue'
import confirm from '../base/confirm.vue'
import ishms from '../util/ishms.js'
import isValid from '../util/isValid.js'
import isType from '../util/isType.js'

export default {
  name: 'PanelDate',
  components: { day, confirm },
  props: {

    // 初始值
    value: {
      type: [Array],
      default() {
        return null
      }
    },

    // 展示的日期格式
    format: String, // eslint-disable-line

    // 不可选日期
    disabledDate: {
      type: Function,
      default: null
    },

    // confirm
    confirm: {
      type: [Number, Boolean],
      default: 0
    },

    // 选项
    options: {
      type: [Array, Object],
      default: null
    },

    // 设置选中日期默认时分秒
    endTime: Array, // eslint-disable-line
    hours: Object
  },
  data() {
    return {
      selectedDate: null,

      // 是否展示times
      isTimesShow: false
    }
  },

  mounted() {
    this.init()
  },

  methods: {
    init(date) {
      const dateValue = date || this.value
      if (dateValue && dateValue.length) {
        this.selectedDate = dateValue
        if (isValid(dateValue[0])) this.$refs.vDate.toDate = dateValue[0]
      } else {
        this.selectedDate = []
      }
      this.$refs.vDate.init(this.selectedDate)
      this.timeInit()
    },

    timeInit() {
      if (this.isTimes()) {
        this.$refs.confirm.timsInit(this.selectedDate[this.selectedDate.length - 1])
      }
    },

    dayChange(date) {
      const endTime = this.endTime
      if (endTime && isType(endTime) === 'array') {
        date.setHours(endTime[0] || '00', endTime[1] || '00', endTime[2] || '00')
      }
      this.selectedDate = [date]
      this.timeInit()
      this.$emit('change', this.selectedDate)
    },

    timeChange(date) {
      this.selectedDate = [date]
      this.$emit('change', this.selectedDate)
    },

    isTimes() {
      return ishms(this.format)
    },

    isConfirm() {
      if (this.confirm || this.isTimes()) return true
      return false
    },

    cancel() {
      this.$emit('cancel')
    },

    confirmEvent() {
      this.$emit('confirm')
    }
  }
}
</script>
