'use strict';

exports.__esModule = true;

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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

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

var _instance2 = _interopRequireDefault(_instance);

var _instance3 = require('../Context/instance.js');

var _instance4 = _interopRequireDefault(_instance3);

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; } // require PrototypeDate.js和PrototypeString.js


var PickerDate = (0, _react.forwardRef)(function (_ref, ref) {
  var portal = _ref.portal,
      data = _ref.data,
      _ref$split = _ref.split,
      split = _ref$split === undefined ? '-' : _ref$split,
      _ref$timeSplit = _ref.timeSplit,
      timeSplit = _ref$timeSplit === undefined ? ':' : _ref$timeSplit,
      _ref$type = _ref.type,
      type = _ref$type === undefined ? 'date' : _ref$type,
      _ref$show = _ref.show,
      show = _ref$show === undefined ? false : _ref$show,
      value = _ref.value,
      selected = _ref.selected,
      _ref$maskAttribute = _ref.maskAttribute,
      maskAttribute = _ref$maskAttribute === undefined ? {} : _ref$maskAttribute,
      _ref$submitAttribute = _ref.submitAttribute,
      submitAttribute = _ref$submitAttribute === undefined ? {} : _ref$submitAttribute,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === undefined ? {} : _ref$cancelAttribute,
      onError = _ref.onError,
      onScrollEnd = _ref.onScrollEnd,
      others = _objectWithoutProperties(_ref, ['portal', 'data', 'split', 'timeSplit', 'type', 'show', 'value', 'selected', 'maskAttribute', 'submitAttribute', 'cancelAttribute', 'onError', 'onScrollEnd']);

  var refEl = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return refEl.current;
  });
  var instance = (0, _react.useRef)(null);
  // context
  var context = (0, _react.useContext)(_instance4.default) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };

  (0, _react.useEffect)(function () {
    initInstance();
  }, []); // eslint-disable-line

  (0, _react.useEffect)(function () {
    if (instance.current) {
      if (show) {
        update();
        instance.current.show();
      } else {
        instance.current.hide();
      }
    }
  }, [show]);

  // 更新句柄, 防止synchronization模式, 每次组件在render的时候都生成上次render的state、function、effects
  if (instance.current) {
    instance.current.params.onClickSubmit = clickSubmit;
    instance.current.params.onClickCancel = clickCancel;
    instance.current.params.onClickMask = clickMask;
    instance.current.params.onScrollEnd = scrollEnd;
  }
  function clickSubmit(e) {
    // 获取选中项
    e.activeText = e.getActiveText(e.activeOptions);
    var activeKeys = e.activeOptions.map(function (n, i, a) {
      return n['id'];
    });
    e.setDefaultsByKeys(activeKeys);
    // Callback
    var value = e.activeText;
    var options = e.activeOptions;
    if (submitAttribute.onClick) submitAttribute.onClick(e, value, options);
  }
  function clickCancel(e) {
    if (cancelAttribute.onClick) cancelAttribute.onClick(e);
  }
  function clickMask(e) {
    if (maskAttribute.onClick) maskAttribute.onClick(e);
  }
  function scrollEnd(e) {
    // 根据月份算日
    if ((e.params.viewType === 'date' || e.params.viewType === 'datetime') && (e.activeSlot.index === 0 || e.activeSlot.index === 1)) {
      var year = e.activeOptions[0]['id'];
      var month = e.activeOptions[1]['id'];
      var defaultDay = e.activeOptions[2]['id'];
      e.updateDays(year, month, defaultDay); // 更新总天数
    }
    // Callback
    if (onScrollEnd) onScrollEnd(e);
  }

  function update() {
    instance.current.updateParams({
      yyUnit: locale('年', 'unit_year'),
      MMUnit: locale('月', 'unit_month'),
      ddUnit: locale('日', 'unit_date'),
      hhUnit: locale('时', 'unit_hour'),
      mmUnit: locale('分', 'unit_minute')
    });
    var def = getDefault();
    instance.current.setDefaults(def);
    instance.current.update();
  }
  function getDefault() {
    var defaultValue = value;
    if (selected && selected.length) {
      defaultValue = selected.map(function (item) {
        return item.id;
      });
      defaultValue = defaultValue.join(split);
    }
    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 = instance.current ? instance.current : {};
      if (!defaultValue || !defaultValue.isDate(split)) {
        if (onError) onError(_e, { errMsg: '' + locale('无效的日期格式', 'hint_invalid_date') });
      } 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 (onError) onError(e, { errMsg: locale('无效的日期格式', 'hint_invalid_date') + ', YYYY-MM-DD' });
      } else {
        var monthValues = defaultValue.split(split);
        defaultYear = monthValues[0];
        defaultMonth = monthValues[1];
      }
    } else if (type === 'datetime') {
      // 如果不是合法的日期格式
      if (!defaultValue || !defaultValue.isDateTime(split, timeSplit)) {
        if (onError) onError(e, { errMsg: locale('无效的日期格式', 'hint_invalid_date') + ', YYYY-MM-DD hh:mm' });
      } 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 (onError) onError(e, { errMsg: locale('无效的日期格式', 'hint_invalid_date') + ', hh' + (timeSplit || ':') + 'mm' });
      } else {
        var _timeValues = defaultValue.split(timeSplit || ':');
        defaultHour = _timeValues[0];
        defaultMinute = _timeValues[1];
      }
    }
    return {
      year: defaultYear,
      month: defaultMonth,
      day: defaultDay,
      hour: defaultHour,
      minute: defaultMinute
    };
  }
  function getData() {
    // 自定义数据
    var yearsData = null;
    var monthsData = null;
    var daysData = null;
    var hoursData = null;
    var minutesData = null;
    if (data) {
      if (data.year) {
        yearsData = data.year.map(function (n) {
          return {
            'id': '' + n,
            'name': '' + n + locale('年', 'unit_year')
          };
        });
      }
      if (data.month) {
        monthsData = data.month.map(function (n) {
          return {
            'id': '' + n,
            'name': '' + n + locale('月', 'unit_month')
          };
        });
      }
      if (data.day) {
        daysData = data.day.map(function (n) {
          return {
            'id': '' + n,
            'name': '' + n + locale('日', 'unit_date')
          };
        });
      }
      if (data.hour) {
        hoursData = data.hour.map(function (n) {
          return {
            'id': '' + n,
            'name': '' + n + locale('时', 'unit_hour')
          };
        });
      }
      if (data.minute) {
        minutesData = data.minute.map(function (n) {
          return {
            'id': '' + n,
            'name': '' + n + locale('分', 'unit_minute')
          };
        });
      }
    }
    return {
      yearsData: yearsData,
      monthsData: monthsData,
      daysData: daysData,
      hoursData: hoursData,
      minutesData: minutesData
    };
  }
  function initInstance() {
    if (!refEl || !refEl.current) return;
    var data = getData();
    var def = getDefault();
    // render数据
    instance.current = new _instance2.default({
      mask: refEl.current,
      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: clickMask,
      onClickCancel: clickCancel,
      onClickSubmit: clickSubmit,
      onScrollEnd: scrollEnd,
      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 && instance) {
      setTimeout(function () {
        instance.current.show();
      }, 10);
    }
  }
  // 过滤已经回调的属性
  function filterProps(props) {
    if (!props) return {};

    var onClick = props.onClick,
        otherProps = _objectWithoutProperties(props, ['onClick']);

    return _extends({}, otherProps);
  }

  // 剔除掉onClick事件, 因为在instance时已经回调了
  var otherMaskAttribute = filterProps(maskAttribute);
  var otherSubmitAttribute = filterProps(submitAttribute);
  var otherCancelAttribute = filterProps(cancelAttribute);
  return (0, _reactDom.createPortal)(_react2.default.createElement(
    'div',
    _extends({ ref: refEl }, otherMaskAttribute, { className: 'mask picker-mask' + (otherMaskAttribute.className ? ' ' + otherMaskAttribute.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({}, otherCancelAttribute, { className: 'picker-cancel' + (otherCancelAttribute.className ? ' ' + otherCancelAttribute.className : '') }),
          otherCancelAttribute.caption || locale('取消', 'cancel')
        ),
        _react2.default.createElement(
          'a',
          _extends({}, otherSubmitAttribute, { className: 'picker-submit' + (otherSubmitAttribute.className ? ' ' + otherSubmitAttribute.className : '') }),
          otherSubmitAttribute.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 || context.portal || document.getElementById('root') || document.body);
});

exports.default = _react2.default.memo(PickerDate, function (prevProps, nextProps) {
  if (nextProps.show === prevProps.show) return true;
  return false;
});
module.exports = exports['default'];