/* eslint-disable */
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { falcon as _falcon } from "@mas.io/falcon-core";
import { MasComponent } from './typings/mas';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { defaultFormatter, currentYear, getMonthEndDay, isValidDate, padZero, range, times, formatDate } from './utils/util';
dayjs.extend(customParseFormat);

var Index = /*#__PURE__*/function (_MasComponent) {
  _inheritsLoose(Index, _MasComponent);

  function Index() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _MasComponent.call.apply(_MasComponent, [this].concat(args)) || this;
    _this.props = {
      valueArr: [],
      isShow: false,
      value: '',
      onFilter: null,
      pickerType: 'range',
      type: 'datetime',
      showToolbar: true,
      onFormatter: defaultFormatter,
      minDate: new Date(currentYear - 10, 0, 1).getTime(),
      maxDate: new Date(currentYear + 10, 11, 31).getTime(),
      minHour: 0,
      maxHour: 23,
      minMinute: 0,
      maxMinute: 59,
      hint: null,
      verify: true,
      // eslint-disable-next-line no-unused-vars
      onConfirm: function onConfirm(val) {},
      // eslint-disable-next-line no-unused-vars
      onCancel: function onCancel(val) {}
    };
    _this.data = {
      tabIndex: 0,
      innerValue: Date.now(),
      columns: [],
      innerValueArr: [],
      minDateVal: new Date(currentYear - 10, 0, 1).getTime(),
      startTime: null,
      endTime: null,
      errorText: null
    };
    return _this;
  }

  var _proto = Index.prototype;

  _proto.onInit = /*#__PURE__*/function () {
    var _onInit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var innerValue;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              innerValue = this.props.value ? this.correctValue(this.props.value) : this.data.innerValue;

              if (this.props.pickerType === 'range') {
                innerValue = this.props.valueArr.length > 0 ? this.props.valueArr[this.data.tabIndex] : Date.now();

                if (this.props.valueArr[1]) {
                  this.setData({
                    'innerValueArr[1]': formatDate('YYYY-MM-DD hh:mm', this.props.valueArr[1])
                  });
                }
              }

              _context.next = 4;
              return this.updateColumnValue(innerValue);

            case 4:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

    function onInit() {
      return _onInit.apply(this, arguments);
    }

    return onInit;
  }();

  _proto.deriveDataFromProps = /*#__PURE__*/function () {
    var _deriveDataFromProps = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(nextProps) {
      var startTime, endTime, flag, _flag, minDateVal;

      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              startTime = nextProps.valueArr[0];
              endTime = nextProps.valueArr[1];

              if (!(startTime instanceof Date)) {
                _context2.next = 9;
                break;
              }

              flag = this.props.valueArr[0].getTime() === startTime.getTime();

              if (flag) {
                _context2.next = 9;
                break;
              }

              this.data.innerValueArr[0] = startTime;

              if (!(this.data.tabIndex === 0)) {
                _context2.next = 9;
                break;
              }

              _context2.next = 9;
              return this.updateColumnValue(startTime);

            case 9:
              if (!(endTime instanceof Date)) {
                _context2.next = 16;
                break;
              }

              _flag = this.props.valueArr[1].getTime() === endTime.getTime();

              if (_flag) {
                _context2.next = 16;
                break;
              }

              this.data.innerValueArr[1] = endTime;

              if (!(this.data.tabIndex === 1)) {
                _context2.next = 16;
                break;
              }

              _context2.next = 16;
              return this.updateColumnValue(endTime);

            case 16:
              minDateVal = nextProps.minDate;

              if (minDateVal && minDateVal !== this.props.minDate) {
                this.setData({
                  minDateVal: minDateVal
                });
              }

            case 18:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, this);
    }));

    function deriveDataFromProps(_x) {
      return _deriveDataFromProps.apply(this, arguments);
    }

    return deriveDataFromProps;
  }();

  _proto.updateValue = /*#__PURE__*/function () {
    var _updateValue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
      var val, isEqual;
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              val = this.correctValue(this.props.value);
              isEqual = val === this.data.innerValue;
              _context3.next = 4;
              return this.updateColumnValue(val);

            case 4:
              if (!isEqual) {// this.$emit('input', val);
              }

            case 5:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, this);
    }));

    function updateValue() {
      return _updateValue.apply(this, arguments);
    }

    return updateValue;
  }();

  _proto.correctValue = function correctValue(val) {
    var value = val; // validate value

    var isDateType = this.props.type !== 'time';

    if (isDateType && !isValidDate(value)) {
      value = this.data.minDateVal;
    } else if (!isDateType && !value) {
      value = padZero(this.props.minHour) + ":00";
    } // time type


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

      hour = padZero(range(hour, this.props.minHour, this.props.maxHour));
      minute = padZero(range(minute, this.props.minMinute, this.props.maxMinute));
      return hour + ":" + minute;
    } // date type


    value = Math.max(value, this.data.minDateVal);
    value = Math.min(value, this.props.maxDate);
    return value;
  };

  _proto.updateColumnValue = function updateColumnValue(value) {
    var _this2 = this;

    return new Promise(function (resolve) {
      var values = [];
      var formatter = _this2.props.onFormatter || defaultFormatter; // const picker = this.getPicker();

      var type = _this2.props.type;

      if (type === 'time') {
        var pair = value.split(':');
        values = [formatter('hour', pair[0]), formatter('minute', pair[1])];
      } else {
        var date = new Date(value);
        values = [formatter('year', "" + date.getFullYear()), formatter('month', padZero(date.getMonth() + 1))];

        if (type === 'date') {
          values.push(formatter('day', padZero(date.getDate())));
        }

        if (type === 'datetime') {
          values.push(formatter('day', padZero(date.getDate())), formatter('hour', padZero(date.getHours())), formatter('minute', padZero(date.getMinutes())));
        }
      }

      _this2.setData({
        innerValue: value
      }, function () {
        _this2.updateColumns(); // picker.setValues(values)

      }); // @ts-ignore


      resolve('');
    });
  };

  _proto.updateColumns = function updateColumns() {
    var _this$props$onFormatt = this.props.onFormatter,
        onFormatter = _this$props$onFormatt === void 0 ? defaultFormatter : _this$props$onFormatt;
    var results = this.getOriginColumns().map(function (column) {
      return {
        values: column.values.map(function (value) {
          return onFormatter(column.type, value);
        }),
        defaultIndex: column.defaultIndex
      };
    });
    return this.setData({
      columns: results
    });
  };

  _proto.getOriginColumns = function getOriginColumns() {
    var _this3 = this;

    var onFilter = this.props.onFilter; // eslint-disable-next-line no-shadow

    var results = this.getRanges().map(function (_ref) {
      var type = _ref.type,
          range = _ref.range;
      var values = times(range[1] - range[0] + 1, function (index) {
        var value = range[0] + index;
        return type === 'year' ? "" + value : padZero(value);
      });
      var value = new Date(_this3.props.value || _this3.data.innerValue);
      var time = 0;

      if (type === 'year') {
        time = value.getFullYear();
      } else if (type === 'month') {
        time = value.getMonth() + 1;
      } else if (type === 'day') {
        time = value.getDate();
      } else if (type === 'hour') {
        time = value.getHours();
      } else if (type === 'minute') {
        time = value.getMinutes();
      }

      var index = values.findIndex(function (item) {
        return +item === time;
      });

      if (onFilter && Object.prototype.toString.call(onFilter) === '[object Function]') {
        values = onFilter(type, values);
      }

      return {
        type: type,
        values: values,
        defaultIndex: index
      };
    });
    return results;
  };

  _proto.getRanges = function getRanges() {
    var props = this.props,
        data = this.data;

    if (props.type === 'time') {
      return [{
        type: 'hour',
        range: [props.minHour, props.maxHour]
      }, {
        type: 'minute',
        range: [props.minMinute, props.maxMinute]
      }];
    }

    var _this$getBoundary = this.getBoundary('max', data.innerValue),
        maxYear = _this$getBoundary.maxYear,
        maxDate = _this$getBoundary.maxDate,
        maxMonth = _this$getBoundary.maxMonth,
        maxHour = _this$getBoundary.maxHour,
        maxMinute = _this$getBoundary.maxMinute;

    var _this$getBoundary2 = this.getBoundary('min', data.innerValue),
        minYear = _this$getBoundary2.minYear,
        minDate = _this$getBoundary2.minDate,
        minMonth = _this$getBoundary2.minMonth,
        minHour = _this$getBoundary2.minHour,
        minMinute = _this$getBoundary2.minMinute;

    var result = [{
      type: 'year',
      range: [minYear, maxYear]
    }, {
      type: 'month',
      range: [minMonth, maxMonth]
    }, {
      type: 'day',
      range: [minDate, maxDate]
    }, {
      type: 'hour',
      range: [minHour, maxHour]
    }, {
      type: 'minute',
      range: [minMinute, maxMinute]
    }];
    if (props.type === 'date') result.splice(3, 2);
    if (props.type === 'year-month') result.splice(2, 3);
    return result;
  };

  _proto.getBoundary = function getBoundary(type, innerValue) {
    var _ref2;

    var value = new Date(innerValue); // @ts-ignore

    var boundary = new Date(this.props[type + "Date"]);
    var year = boundary.getFullYear();
    var month = 1;
    var date = 1;
    var hour = 0;
    var minute = 0;

    if (type === 'max') {
      month = 12;
      date = 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 _ref2 = {}, _ref2[type + "Year"] = year, _ref2[type + "Month"] = month, _ref2[type + "Date"] = date, _ref2[type + "Hour"] = hour, _ref2[type + "Minute"] = minute, _ref2;
  };

  _proto.changeHandle = /*#__PURE__*/function () {
    var _changeHandle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(values) {
      var date, innerValueArr, startTime, endTime;
      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              date = this.formatDateStr(values);
              innerValueArr = this.data.innerValueArr;

              if (this.props.pickerType === 'range') {
                innerValueArr[this.data.tabIndex] = date;
              }

              startTime = innerValueArr[0];
              endTime = innerValueArr[1];

              if (!(this.data.tabIndex === 0)) {
                _context4.next = 12;
                break;
              }

              if (this.props.type === 'date' && !dayjs(startTime, 'YYYY-MM-DD', true).isValid()) {
                startTime = dayjs(startTime).subtract(1, 'month').endOf('month').format('YYYY-MM-DD');
              } else if (this.props.type === 'datetime' && !dayjs(startTime, 'YYYY-MM-DD HH:mm', true).isValid()) {
                startTime = dayjs(startTime).subtract(1, 'month').endOf('month').format('YYYY-MM-DD HH:mm');
              }

              this.setData({
                startTime: startTime
              });
              _context4.next = 10;
              return this.updateColumnValue(startTime);

            case 10:
              _context4.next = 16;
              break;

            case 12:
              if (this.props.type === 'date' && !dayjs(endTime, 'YYYY-MM-DD', true).isValid()) {
                endTime = dayjs(endTime).subtract(1, 'month').endOf('month').format('YYYY-MM-DD');
              } else if (this.props.type === 'datetime' && !dayjs(endTime, 'YYYY-MM-DD HH:mm', true).isValid()) {
                endTime = dayjs(endTime).subtract(1, 'month').endOf('month').format('YYYY-MM-DD HH:mm');
              }

              this.setData({
                endTime: endTime
              });
              _context4.next = 16;
              return this.updateColumnValue(endTime);

            case 16:
              this.setData({
                errorText: null
              });

            case 17:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4, this);
    }));

    function changeHandle(_x2) {
      return _changeHandle.apply(this, arguments);
    }

    return changeHandle;
  }();

  _proto.cancel = function cancel(evt) {
    if (Object.prototype.toString.call(this.props.onCancel) === '[object Function]') {
      var type = 'cancel';

      if (evt) {
        var dataset = evt.target.dataset;
        type = dataset.type;
      }

      this.props.onCancel({
        type: type
      });
    }
  };

  _proto.confirm = function confirm() {
    if (this.data.innerValueArr.length < 2) {
      this.setData({
        errorText: '请选择结束日期'
      });
      return;
    }

    var startTime = this.data.startTime;
    var endTime = this.data.endTime;
    startTime = new Date(startTime).getTime();
    endTime = new Date(endTime).getTime();

    if (!startTime) {
      this.setData({
        errorText: '请选择开始时间'
      });
      return false;
    }

    if (!endTime) {
      this.setData({
        errorText: '请选择结束时间'
      });
      return false;
    }

    if (this.props.verify && startTime > endTime) {
      this.setData({
        errorText: '结束时间不能小于开始时间'
      });
      return false;
    } else {
      this.setData({
        errorText: null
      });
    }

    if (Object.prototype.toString.call(this.props.onConfirm) === '[object Function]') {
      var values = this.$page.currentValue; // eslint-disable-next-line array-callback-return

      var date = this.formatDateStr(values);

      if (this.props.pickerType === 'range') {
        date = this.data.innerValueArr;
      }

      this.props.onConfirm(date);
    }
  };

  _proto.formatDateStr = function formatDateStr(values) {
    if (!values || values.length <= 0) {
      return;
    }

    var year = '';
    var month = '';
    var day = '';
    var hour = '';
    var minute = '';

    if (this.props.type === 'datetime' || this.props.type === 'date' || this.props.type === 'year-month') {
      year = values[0].value;
      month = values[1].value;

      if (this.props.type === 'year-month') {
        return year + "-" + month;
      }

      if (this.props.type === 'date') {
        day = values[2].value;
        return year + "-" + month + "-" + day;
      }

      if (this.props.type === 'datetime') {
        day = values[2].value;
        hour = values[3].value;
        minute = values[4].value;
        return year + "-" + month + "-" + day + " " + hour + ":" + minute;
      }
    }
  };

  _proto.switchTab = /*#__PURE__*/function () {
    var _switchTab = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(event) {
      var index, innerValue;
      return _regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              index = event.currentTarget.dataset.index;
              innerValue = this.data.innerValueArr[index] || Date.now();
              _context5.next = 4;
              return this.updateColumnValue(innerValue);

            case 4:
              this.setData({
                tabIndex: index
              });

            case 5:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5, this);
    }));

    function switchTab(_x3) {
      return _switchTab.apply(this, arguments);
    }

    return switchTab;
  }();

  return Index;
}(MasComponent);

export { Index as default };
var instance = new Index();

_falcon.launch(instance, "Component", {
  componentName: "@alipay/adc-datetime-picker"
});

Component(instance);