import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import WPicker from "../WPicker"; // Mixins

import Picker from "../../../es5/mixins/picker"; // Utils

import mixins from "../../../es5/utils/mixins";
var currentYear = new Date().getFullYear();

var isValidDate = function isValidDate(date) {
  return Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime());
};

export default mixins(Picker).extend({
  name: 'w-datetime-picker',
  components: {
    WPicker: WPicker
  },
  props: {
    type: {
      type: String,
      default: 'datetime'
    },
    startDate: {
      type: Date,
      default: function _default() {
        return new Date(currentYear - 10, 0, 1);
      },
      validator: isValidDate
    },
    endDate: {
      type: Date,
      default: function _default() {
        return new Date(currentYear + 10, 11, 31);
      },
      validator: isValidDate
    },
    startHour: {
      type: Number,
      default: 0
    },
    endHour: {
      type: Number,
      default: 23
    },
    yearFormat: {
      type: String,
      default: '{value}'
    },
    monthFormat: {
      type: String,
      default: '{value}'
    },
    dateFormat: {
      type: String,
      default: '{value}'
    },
    hourFormat: {
      type: String,
      default: '{value}'
    },
    minuteFormat: {
      type: String,
      default: '{value}'
    },
    visibleItemCount: {
      type: Number,
      default: 7
    },
    value: {}
  },
  data: function data() {
    return {
      internalValue: this.value
    };
  },
  computed: {
    ranges: function ranges() {
      if (this.type === 'time') {
        return {
          hour: [this.startHour, this.endHour],
          minute: [0, 59]
        };
      }

      var _this$getBoundary = this.getBoundary('start', this.internalValue),
          startYear = _this$getBoundary.startYear,
          startMonth = _this$getBoundary.startMonth,
          startDate = _this$getBoundary.startDate,
          startHour = _this$getBoundary.startHour,
          startMinute = _this$getBoundary.startMinute;

      var _this$getBoundary2 = this.getBoundary('end', this.internalValue),
          endYear = _this$getBoundary2.endYear,
          endMonth = _this$getBoundary2.endMonth,
          endDate = _this$getBoundary2.endDate,
          endHour = _this$getBoundary2.endHour,
          endMinute = _this$getBoundary2.endMinute;

      if (this.type === 'datetime') {
        return {
          year: [startYear, endYear],
          month: [startMonth, endMonth],
          date: [startDate, endDate],
          hour: [startHour, endHour],
          minute: [startMinute, endMinute]
        };
      } else {
        return {
          year: [startYear, endYear],
          month: [startMonth, endMonth],
          date: [startDate, endDate]
        };
      }
    },
    columns: function columns() {
      var result = [];

      for (var rangeKey in this.ranges) {
        result.push({
          options: this.fillColumnOptions(rangeKey, this.ranges[rangeKey][0], this.ranges[rangeKey][1])
        });
      }

      return result;
    }
  },
  watch: {
    value: function value(val) {
      val = this.correctValue(val);
      var isEqual = this.type === 'time' ? val === this.internalValue : val.valueOf() === this.internalValue.valueOf();

      if (!isEqual) {
        this.internalValue = val;
      }
    },
    internalValue: function internalValue(val) {
      this.updateColumnValue(val);
    }
  },
  created: function created() {
    this.internalValue = this.correctValue(this.value);
  },
  mounted: function mounted() {
    if (!this.value) {
      this.internalValue = this.type.includes('date') ? this.startDate : "".concat(('0' + this.startHour).slice(-2), ":00");
    } else {
      this.internalValue = this.correctValue(this.value);
    }

    this.updateColumnValue(this.internalValue);
  },
  methods: {
    getMonthEndDay: function getMonthEndDay(year, month) {
      // Date() 第三参数为 0，实际返回上一个月最后一天，注意 Date 对象中 month 实际从 0 开始，而形参 month 表示实际月份
      return new Date(year, month, 0).getDate();
    },
    getTrueValue: function getTrueValue(formattedValue) {
      while (isNaN(parseInt(formattedValue, 10))) {
        formattedValue = formattedValue.slice(1);
      }

      return parseInt(formattedValue, 10);
    },
    correctValue: function correctValue(value) {
      // validate value
      var isDateType = this.type.includes('date');

      if (isDateType && !isValidDate(value)) {
        value = this.startDate;
      } else if (!value) {
        var _startHour = this.startHour;
        value = "".concat(_startHour > 10 ? _startHour : '0' + _startHour, ":00");
      } // time type


      if (!isDateType) {
        var _value$split = value.split(':'),
            _value$split2 = _slicedToArray(_value$split, 2),
            hour = _value$split2[0],
            minute = _value$split2[1];

        var correctedHour = Math.max(parseInt(hour), this.startHour);
        correctedHour = Math.min(correctedHour, this.endHour);
        return "".concat(correctedHour, ":").concat(minute);
      } // date type


      var _this$getBoundary3 = this.getBoundary('end', value),
          endYear = _this$getBoundary3.endYear,
          endMonth = _this$getBoundary3.endMonth,
          endDate = _this$getBoundary3.endDate,
          endHour = _this$getBoundary3.endHour,
          endMinute = _this$getBoundary3.endMinute;

      var _this$getBoundary4 = this.getBoundary('start', value),
          startYear = _this$getBoundary4.startYear,
          startMonth = _this$getBoundary4.startMonth,
          startDate = _this$getBoundary4.startDate,
          startHour = _this$getBoundary4.startHour,
          startMinute = _this$getBoundary4.startMinute;

      var startDay = new Date(startYear, startMonth - 1, startDate, startHour, startMinute);
      var endDay = new Date(endYear, endMonth - 1, endDate, endHour, endMinute);
      value = Math.min(Math.max(value.getTime(), startDay.getTime()), endDay.getTime());
      return new Date(value);
    },
    onChange: function onChange(picker) {
      var values = picker.getValues();
      var value;

      if (this.type === 'time') {
        value = values.join(':');
      } else {
        var year = this.getTrueValue(values[0]);
        var month = this.getTrueValue(values[1]);
        var date = this.getTrueValue(values[2]);
        var endDate = this.getMonthEndDay(year, month);
        date = date > endDate ? endDate : date;
        var hour = 0;
        var minute = 0;

        if (this.type === 'datetime') {
          hour = this.getTrueValue(values[3]);
          minute = this.getTrueValue(values[4]);
        }

        value = new Date(year, month - 1, date, hour, minute);
      }

      value = this.correctValue(value);
      this.internalValue = value;
      this.$emit('change', picker);
    },
    fillColumnOptions: function fillColumnOptions(type, start, end) {
      var options = [];

      for (var i = start; i <= end; i++) {
        if (i < 10) {
          options.push(this["".concat(type, "Format")].replace('{value}', ('0' + i).slice(-2)));
        } else {
          options.push(this["".concat(type, "Format")].replace('{value}', i));
        }
      }

      return options;
    },
    getBoundary: function getBoundary(type, value) {
      var boundary = type === 'start' ? this.startDate : this.endDate;
      var year = boundary.getFullYear();
      var month = 1;
      var date = 1;
      var hour = 0;
      var minute = 0;

      if (type === 'end') {
        month = 12;
        date = this.getMonthEndDay(value.getFullYear(), value.getMonth() + 1);
        hour = 23;
        minute = 59;
      }

      if (value.getFullYear() === year) {
        month = boundary.getMonth() + 1;

        if (value.getMonth() + 1 === month) {
          date = boundary.getDate();

          if (value.getDate() === date) {
            hour = boundary.getHours();

            if (value.getHours() === hour) {
              minute = boundary.getMinutes();
            }
          }
        }
      }

      return type === 'start' ? {
        startYear: year,
        startMonth: month,
        startDate: date,
        startHour: hour,
        startMinute: minute
      } : {
        endYear: year,
        endMonth: month,
        endDate: date,
        endHour: hour,
        endMinute: minute
      };
    },
    updateColumnValue: function updateColumnValue(value) {
      var _this = this;

      var values = [];

      if (this.type === 'time') {
        var internalValue = value.split(':');
        values = [this.hourFormat.replace('{value}', "0".concat(internalValue[0]).slice(-2)), this.minuteFormat.replace('{value}', "0".concat(internalValue[1]).slice(-2))];
      } else {
        values = [this.yearFormat.replace('{value}', "".concat(value.getFullYear())), this.monthFormat.replace('{value}', "0".concat(value.getMonth() + 1).slice(-2)), this.dateFormat.replace('{value}', "0".concat(value.getDate()).slice(-2))];

        if (this.type === 'datetime') {
          values.push(this.hourFormat.replace('{value}', "0".concat(value.getHours()).slice(-2)), this.minuteFormat.replace('{value}', "0".concat(value.getMinutes()).slice(-2)));
        }
      }

      this.$nextTick(function () {
        _this.setColumnByValues(values);
      });
    },
    setColumnByValues: function setColumnByValues(values) {
      this.$refs.picker.setValues(values);
    },
    onCancel: function onCancel() {
      this.isActive = false;
      this.$emit('cancel');
    },
    onConfirm: function onConfirm() {
      this.isActive = false;
      this.$emit('input', this.internalValue);
      this.$emit('confirm', this.internalValue);
    }
  },
  render: function render() {
    var _this2 = this;

    var h = arguments[0];
    return h(WPicker, {
      "ref": "picker",
      "attrs": {
        "visible": this.isActive,
        "columns": this.columns,
        "confirm-text": this.confirmText,
        "cancel-text": this.cancelText,
        "close-on-click-mask": this.closeOnClickMask,
        "visible-item-count": this.visibleItemCount
      },
      "on": {
        "change": function change() {
          _this2.onChange(_this2.$refs.picker);
        },
        "cancel": this.onCancel,
        "confirm": this.onConfirm
      }
    });
  }
});
//# sourceMappingURL=WDatetimePicker.js.map