<template>
  <a class="datetime cell" :class="{'cell_access': !readonly}" :data-cancel-text="cancelText" :data-confirm-text="confirmText" href="javascript:;">
    <slot>
      <div>
        <slot name="title">
          <p :style="{width: $parent.labelWidth, textAlign: $parent.labelAlign, marginRight: $parent.labelMarginRight}" v-html="title"></p>
        </slot>
      </div>
      <div class="cell__ft cell-primary datetime-value" :style="{textAlign: valueTextAlign}">
        {{ _value }}
      </div>
    </slot>
  </a>
</template>
<script>
import Picker from './datetimepicker'

function formatDate(date, format){
  date = new Date(date);
  let map = {
    "M": date.getMonth() + 1, //月份
    "D": date.getDate(), //日
    "h": date.getHours(), //小时
    "m": date.getMinutes(), //分
    "s": date.getSeconds(), //秒
    "q": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };

  format = format.replace(/([YMDhmsqS])+/g, (all, t) => {
    var v = map[t];
    if (v !== undefined) {
      if (all.length > 1) {
        v = '0' + v;
        v = v.substr(v.length - 2);
      }
      return v;
    } else if (t === 'Y') {
      return (date.getFullYear() + '').substr(4 - all.length);
    }
    return all;
  });
  return format;
}

export default {
  name: 'dateTime',
  components: {},
  props: {
    format: {
      type: String,
      default: 'YYYY-MM-DD'
    },
    title: {
      type: String,
      required: true
    },
    value: {
      type: String,
      default: ''
    },
    placeholder: String,
    minYear: Number,
    maxYear: Number,
    confirmText: {
      type: String,
      default: '确认'
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    clearText: String,
    yearRow: {
      type: String,
      default: '{value}'
    },
    monthRow: {
      type: String,
      default: '{value}'
    },
    dayRow: {
      type: String,
      default: '{value}'
    },
    hourRow: {
      type: String,
      default: '{value}'
    },
    minuteRow: {
      type: String,
      default: '{value}'
    },
    required: {
      type: Boolean,
      default: false
    },
    minHour: {
      type: Number,
      default: 0
    },
    maxHour: {
      type: Number,
      default: 23
    },
    startDate: String,
    endDate: String,
    valueTextAlign: String,
    displayFormat: Function,
    readonly: Boolean,
    hourList: Array,
    minuteList: Array,
    show: Boolean,
    defaultSelectedValue: String
  },
  created() {
    this.isFirstSetValue = false
    this.currentValue = this.value
  },
  data() {
    return {
      currentValue: null,
      uuid: Math.random().toString(36).substring(3, 8),
      errors: {},
      refreshDate:''
    }
  },
  mounted() {
    window.addEventListener("popstate", () => {
     this.picker && this.picker.destroy()
   }, false);
    const uuid = this.uuid
    if (!this.readonly) {
      this.$nextTick(() => {
        this.$el.setAttribute('id', `datetime-${uuid}`)
        this.render()
      })
    }
  },
  computed: {
    _value() {
      if (!this.currentValue) {
        return this.placeholder || ''
      } else {
        return this.displayFormat ? this.displayFormat(this.currentValue) : this.currentValue
      }
    },
    pickerOptions() {
      const _this = this
      const options = {
        trigger: '#datetime-' + this.uuid,
        format: this.format,
        value: this.currentValue,
        output: '.datetime-value',
        confirmText: _this.getButtonText('confirm'),
        cancelText: _this.getButtonText('cancel'),
        clearText: _this.clearText,
        yearRow: this.yearRow,
        monthRow: this.monthRow,
        dayRow: this.dayRow,
        hourRow: this.hourRow,
        minuteRow: this.minuteRow,
        minHour: this.minHour,
        maxHour: this.maxHour,
        startDate: this.startDate,
        endDate: this.endDate,
        hourList: this.hourList,
        minuteList: this.minuteList,
        defaultSelectedValue: this.defaultSelectedValue,
        onConfirm(value) {
          _this.currentValue = value
          _this.$emit('on-confirm',value)
        },
        onClear(value) {
          _this.$emit('on-clear', value)
        },
        onHide() {
          _this.$emit('update:show', false)
          _this.$emit('on-hide')
        },
        onShow() {
          _this.$emit('update:show', true)
          _this.$emit('on-show')
        },
        onSelect(val){
          _this.refreshDate = this.getValue()
          _this.$emit('on-select',this.getValue())
        }
      }
      if (this.minYear) {
        options.minYear = this.minYear
      }
      if (this.maxYear) {
        options.maxYear = this.maxYear
      }
      return options
    }
  },
  methods: {
    getButtonText(type) {
      if (type === 'cancel' && this.cancelText) {
        return this.cancelText
      } else if (type === 'confirm' && this.confirmText) {
        return this.confirmText
      }
      return this.$el.getAttribute(`data-${type}-text`)
    },
    render() {
      this.$nextTick(() => {
        this.picker && this.picker.destroy()
        this.picker = new Picker(this.pickerOptions)
      })
    },
  },
  watch: {
    show(val) {
      if (val) {
        this.picker && this.picker.show(this.currentValue)
      }
    },
    currentValue(val, oldVal) {
      this.$emit('input', val)
      if (!this.isFirstSetValue) {
        this.isFirstSetValue = true
        oldVal && this.$emit('on-change', val)
      } else {
        this.$emit('on-change', val)
      }
    },
    startDate() {
      this.render()
    },
    endDate() {
      this.render()
    },
    format(val) {
      if (this.currentValue) {
        this.currentValue = formatDate(this.currentValue, val)
      }
      this.render()
    },
    value(val) {
      if (this.currentValue !== val) {
        this.currentValue = val
        this.render()
      }
    },
    minHour(val){
      if (val) {
        this.picker && this.picker.refreshMinHour(val,this.refreshDate)
      }
    },
    minuteList(val){
      if (val) {
        this.picker && this.picker.refreshMintueList(val,this.refreshDate)
      }
    }
  },
  beforeDestroy() {
    this.picker && this.picker.destroy()
  }
}
</script>
<style lang="less">
.cell {
  padding: 10px 15px;
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
}

.cell_access {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  color: inherit;
}

.cell__ft {
  padding-right: 13px;
  position: relative;
  text-align: right;
  color: #999;
}

.cell-primary {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  flex: 1;
}
</style>
