'use strict';

exports.__esModule = true;
exports.default = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _class, _temp, _initialiseProps; // require PrototypeDate.js和PrototypeString.js


var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDom = require('react-dom');

var _instance = require('./instance.js');

var _instance2 = _interopRequireDefault(_instance);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var PickerDate = (_temp = _class = function (_Component) {
  _inherits(PickerDate, _Component);

  // 全局配置
  function PickerDate(props, context) {
    _classCallCheck(this, PickerDate);

    var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));

    _initialiseProps.call(_this);

    return _this;
  }
  // 过滤已经回调的属性


  PickerDate.prototype.render = function render() {
    var _this2 = this;

    // 全局配置
    var _context$locale = this.context.locale,
        locale = _context$locale === undefined ? {} : _context$locale;

    var _props = this.props,
        portal = _props.portal,
        data = _props.data,
        split = _props.split,
        timeSplit = _props.timeSplit,
        type = _props.type,
        show = _props.show,
        value = _props.value,
        valueForKey = _props.valueForKey,
        _props$maskAttribute = _props.maskAttribute,
        maskAttribute = _props$maskAttribute === undefined ? {} : _props$maskAttribute,
        _props$submitAttribut = _props.submitAttribute,
        submitAttribute = _props$submitAttribut === undefined ? {} : _props$submitAttribut,
        _props$cancelAttribut = _props.cancelAttribute,
        cancelAttribute = _props$cancelAttribut === undefined ? {} : _props$cancelAttribut,
        fail = _props.fail,
        others = _objectWithoutProperties(_props, ['portal', 'data', 'split', 'timeSplit', 'type', 'show', 'value', 'valueForKey', 'maskAttribute', 'submitAttribute', 'cancelAttribute', 'fail']);
    // 剔除掉onClick事件, 因为在instance时已经回调了


    maskAttribute = this.filterProps(maskAttribute);
    submitAttribute = this.filterProps(submitAttribute);
    cancelAttribute = this.filterProps(cancelAttribute);
    return (0, _reactDom.createPortal)(_react2.default.createElement(
      'div',
      _extends({ ref: function ref(el) {
          _this2.$el = el;
        } }, maskAttribute, { className: 'mask picker-mask' + (maskAttribute.className ? ' ' + maskAttribute.className : '') }),
      _react2.default.createElement(
        'div',
        _extends({}, others, { className: 'picker' + (others.className ? ' ' + others.className : '') }),
        _react2.default.createElement(
          'div',
          { className: 'picker-header' },
          _react2.default.createElement(
            'a',
            _extends({}, cancelAttribute, { className: 'picker-cancel' + (cancelAttribute.className ? ' ' + cancelAttribute.className : '') }),
            cancelAttribute.caption || locale['cancel'] || '取消'
          ),
          _react2.default.createElement(
            'a',
            _extends({}, submitAttribute, { className: 'picker-submit' + (submitAttribute.className ? ' ' + submitAttribute.className : '') }),
            cancelAttribute.caption || locale['finish'] || '完成'
          )
        ),
        _react2.default.createElement(
          'div',
          { className: 'picker-wrapper' },
          _react2.default.createElement(
            'div',
            { className: 'picker-layer' },
            _react2.default.createElement('div', { className: 'picker-layer-frame' })
          ),
          _react2.default.createElement('div', { className: 'picker-slotbox' })
        )
      )
    ), portal || this.context.portal || document.getElementById('root') || document.body);
  };

  return PickerDate;
}(_react.Component), _class.contextTypes = {
  locale: _propTypes2.default.object,
  portal: _propTypes2.default.object
}, _class.defaultProps = {
  split: '-',
  timeSplit: ':',
  type: 'date'
}, _initialiseProps = function _initialiseProps() {
  var _this3 = this;

  this.componentDidMount = function () {
    _this3.initInstance();
  };

  this.shouldComponentUpdate = function (nextProps) {
    if (nextProps.show === _this3.props.show) return false;
    return true;
  };

  this.componentDidUpdate = function () {
    if (_this3.instance) {
      if (_this3.props.show) {
        _this3.update();
        _this3.instance.show();
      } else _this3.instance.hide();
    }
  };

  this.update = function () {
    // 全局配置
    var _context$locale2 = _this3.context.locale,
        locale = _context$locale2 === undefined ? {} : _context$locale2;

    _this3.instance.updateParams({
      yyUnit: typeof locale['unit_year'] === 'string' ? locale['unit_year'] : '年',
      MMUnit: typeof locale['unit_month'] === 'string' ? locale['unit_month'] : '月',
      ddUnit: typeof locale['unit_date'] === 'string' ? locale['unit_date'] : '日',
      hhUnit: typeof locale['unit_hour'] === 'string' ? locale['unit_hour'] : '时',
      mmUnit: typeof locale['unit_minute'] === 'string' ? locale['unit_minute'] : '分'
    });
    var def = _this3.getDefault();
    _this3.instance.setDefaults(def);
    _this3.instance.update();
  };

  this.getDefault = function () {
    var _context$locale3 = _this3.context.locale,
        locale = _context$locale3 === undefined ? {} : _context$locale3;
    var _props2 = _this3.props,
        split = _props2.split,
        timeSplit = _props2.timeSplit,
        type = _props2.type,
        fail = _props2.fail;

    var defaultValue = _this3.props.valueForKey || _this3.props.value;
    var now = new Date();
    var nowYear = now.getFullYear();
    var nowMonth = now.getMonth() + 1;
    var nowDate = now.getDate();
    var nowHour = now.getHours();
    var nowMinute = now.getMinutes();
    var defaultYear = nowYear;
    var defaultMonth = nowMonth < 10 ? '0' + nowMonth : nowMonth;
    var defaultDay = nowDate < 10 ? '0' + nowDate : nowDate;
    var defaultHour = nowHour < 10 ? '0' + nowHour : nowHour;
    var defaultMinute = nowMinute < 10 ? '0' + nowMinute : nowMinute;
    // 默认值
    if (type === 'date') {
      // 如果不是合法的日期格式
      var _e = _this3.instance ? _this3.instance : {};
      if (!defaultValue || !defaultValue.isDate(split)) {
        if (fail) fail({ errMsg: '' + (locale['hint_invalid_date'] || '无效的日期格式'), event: _e });
      } else {
        var dateValues = defaultValue.split(split);
        defaultYear = dateValues[0];
        defaultMonth = dateValues[1];
        defaultDay = dateValues[2] || '01';
      }
    } else if (type === 'month') {
      // 如果不是合法的日期格式
      if (!defaultValue || !defaultValue.isMonth(split)) {
        if (fail) fail({ errMsg: (locale['hint_invalid_date'] || '无效的日期格式') + ', YYYY-MM-DD', event: e });
      } else {
        var monthValues = defaultValue.split(split);
        defaultYear = monthValues[0];
        defaultMonth = monthValues[1];
      }
    } else if (type === 'datetime') {
      // 如果不是合法的日期格式
      if (!defaultValue || !defaultValue.isDateTime(split, timeSplit)) {
        if (fail) fail({ errMsg: (locale['hint_invalid_date'] || '无效的日期格式') + ', YYYY-MM-DD hh:mm', event: e });
      } else {
        var values = defaultValue.split(' ');
        var _dateValues = values[0].split(split || '-');
        var timeValues = values[1].split(timeSplit || ':');
        defaultYear = _dateValues[0];
        defaultMonth = _dateValues[1];
        defaultDay = _dateValues[2];
        defaultHour = timeValues[0];
        defaultMinute = timeValues[1];
      }
    } else if (type === 'time') {
      // 如果不是合法的日期格式
      if (!defaultValue || !defaultValue.isTime(split, timeSplit)) {
        if (fail) fail({ errMsg: (locale['hint_invalid_date'] || '无效的日期格式') + ', hh' + (timeSplit || ':') + 'mm', event: e });
      } else {
        var _timeValues = defaultValue.split(timeSplit || ':');
        defaultHour = _timeValues[0];
        defaultMinute = _timeValues[1];
      }
    }
    return {
      year: defaultYear,
      month: defaultMonth,
      day: defaultDay,
      hour: defaultHour,
      minute: defaultMinute
    };
  };

  this.getData = function () {
    var _context$locale4 = _this3.context.locale,
        locale = _context$locale4 === undefined ? {} : _context$locale4;
    // 自定义数据

    var yearsData = null;
    var monthsData = null;
    var daysData = null;
    var hoursData = null;
    var minutesData = null;
    if (_this3.props.data) {
      if (_this3.props.data.year) {
        yearsData = _this3.props.data.year.map(function (n) {
          return {
            'key': '' + n,
            'value': '' + n + (locale['unit_year'] || '年')
          };
        });
      }
      if (_this3.props.data.month) {
        monthsData = _this3.props.data.month.map(function (n) {
          return {
            'key': '' + n,
            'value': '' + n + (locale['unit_month'] || '月')
          };
        });
      }
      if (_this3.props.data.day) {
        daysData = _this3.props.data.day.map(function (n) {
          return {
            'key': '' + n,
            'value': '' + n + (locale['unit_date'] || '日')
          };
        });
      }
      if (_this3.props.data.hour) {
        hoursData = _this3.props.data.hour.map(function (n) {
          return {
            'key': '' + n,
            'value': '' + n + (locale['unit_hour'] || '时')
          };
        });
      }
      if (_this3.props.data.minute) {
        minutesData = _this3.props.data.minute.map(function (n) {
          return {
            'key': '' + n,
            'value': '' + n + (locale['unit_minute'] || '分')
          };
        });
      }
    }
    return {
      yearsData: yearsData,
      monthsData: monthsData,
      daysData: daysData,
      hoursData: hoursData,
      minutesData: minutesData
    };
  };

  this.initInstance = function () {
    // 全局配置
    var _context$locale5 = _this3.context.locale,
        locale = _context$locale5 === undefined ? {} : _context$locale5;

    var data = _this3.getData();
    var def = _this3.getDefault();
    // render数据
    var _props3 = _this3.props,
        split = _props3.split,
        timeSplit = _props3.timeSplit,
        type = _props3.type,
        show = _props3.show,
        _props3$maskAttribute = _props3.maskAttribute,
        maskAttribute = _props3$maskAttribute === undefined ? {} : _props3$maskAttribute,
        _props3$submitAttribu = _props3.submitAttribute,
        submitAttribute = _props3$submitAttribu === undefined ? {} : _props3$submitAttribu,
        _props3$cancelAttribu = _props3.cancelAttribute,
        cancelAttribute = _props3$cancelAttribu === undefined ? {} : _props3$cancelAttribu;

    _this3.instance = new _instance2.default({
      mask: _this3.$el,
      split: split,
      timeSplit: timeSplit,
      viewType: type,
      yearsData: data.yearsData,
      monthsData: data.monthsData,
      daysData: data.daysData,
      hoursData: data.hoursData,
      minutesData: data.minutesData,
      defaultYear: def.year,
      defaultMonth: def.month,
      defaultDay: def.day,
      defaultHour: def.hour,
      defaultMinute: def.minute,
      onClickMask: function onClickMask(e) {
        if (maskAttribute.onClick) maskAttribute.onClick(e);
      },
      onClickCancel: function onClickCancel(e) {
        if (cancelAttribute.onClick) cancelAttribute.onClick(e);
      },
      onClickSubmit: function onClickSubmit(e) {
        if (submitAttribute.onClick) submitAttribute.onClick(e);
      },
      onHid: function onHid(e) {},
      yyUnit: locale['unit_year'] || '年',
      MMUnit: locale['unit_month'] || '月',
      ddUnit: locale['unit_date'] || '日',
      hhUnit: locale['unit_hour'] || '时',
      mmUnit: locale['unit_minute'] || '分'
    });
    if (show && _this3.instance) {
      setTimeout(function () {
        this.instance.show();
      }, 10);
    }
  };

  this.filterProps = function (props) {
    var propsed = {};
    for (var n in props) {
      if (n !== 'onClick') {
        propsed[n] = props[n];
      }
    }
    return propsed;
  };
}, _temp);
exports.default = PickerDate;
PickerDate.propTypes = process.env.NODE_ENV !== "production" ? {
  portal: _propTypes2.default.object,
  data: _propTypes2.default.object, // {year: [], month: [], day: [], hour: [], minute: []}
  split: _propTypes2.default.string,
  timeSplit: _propTypes2.default.string,

  type: _propTypes2.default.string, // date | month | time | datetime
  show: _propTypes2.default.bool,
  value: _propTypes2.default.string, // '2018-02-26'
  valueForKey: _propTypes2.default.string, // '2018-02-26'

  maskAttribute: _propTypes2.default.object,
  submitAttribute: _propTypes2.default.object,
  cancelAttribute: _propTypes2.default.object,

  fail: _propTypes2.default.func
} : {};
module.exports = exports['default'];