var _excluded = ["portal", "data", "params", "split", "timeSplit", "type", "show", "value", "selected", "maskAttribute", "submitAttribute", "cancelAttribute", "onError", "onScrollEnd"],
    _excluded2 = ["caption", "onClick"];

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

// require PrototypeDate.js和PrototypeString.js
import React, { forwardRef, useEffect, useRef, useContext, useImperativeHandle } from 'react';
import { createPortal } from 'react-dom';
import Instance from './instance.js';
import Context from '../Context/instance.js';
var PickerDate = forwardRef(function (_ref, ref) {
  var portal = _ref.portal,
      data = _ref.data,
      _ref$params = _ref.params,
      params = _ref$params === void 0 ? {} : _ref$params,
      _ref$split = _ref.split,
      split = _ref$split === void 0 ? '-' : _ref$split,
      _ref$timeSplit = _ref.timeSplit,
      timeSplit = _ref$timeSplit === void 0 ? ':' : _ref$timeSplit,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'date' : _ref$type,
      _ref$show = _ref.show,
      show = _ref$show === void 0 ? false : _ref$show,
      value = _ref.value,
      selected = _ref.selected,
      _ref$maskAttribute = _ref.maskAttribute,
      maskAttribute = _ref$maskAttribute === void 0 ? {} : _ref$maskAttribute,
      _ref$submitAttribute = _ref.submitAttribute,
      submitAttribute = _ref$submitAttribute === void 0 ? {} : _ref$submitAttribute,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === void 0 ? {} : _ref$cancelAttribute,
      onError = _ref.onError,
      onScrollEnd = _ref.onScrollEnd,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  var refEl = useRef(null);
  useImperativeHandle(ref, function () {
    return refEl.current;
  });
  var instance = useRef(null); // context

  var context = useContext(Context) || {};

  var locale = context.locale || function (remark) {
    return remark || '';
  };

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

  useEffect(function () {
    if (instance.current) {
      if (show) {
        handleUpdate();
        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); // 更新总天数
    } // 是否显示标题


    if (e.headerTitle) {
      e.headerTitle.innerHTML = e.getActiveWeekText();
    } // Callback


    if (onScrollEnd) onScrollEnd(e);
  }

  function handleUpdate() {
    instance.current.updateParams({
      viewType: type,
      yyUnit: locale('', 'picker_unit_year'),
      QQUnit: locale('', 'picker_unit_quarter'),
      MMUnit: locale('', 'picker_unit_month'),
      ddUnit: locale('', 'picker_unit_date'),
      hhUnit: locale('', 'picker_unit_hour'),
      mmUnit: locale('', 'picker_unit_minute')
    });
    var def = getDefault();
    instance.current.setDefaults(def);
    instance.current.update(); // 是否显示标题

    if (instance.current.headerTitle) {
      instance.current.headerTitle.innerHTML = instance.current.getActiveWeekText();
    }
  }

  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 nowQuarter = now.quarter();
    var nowMonth = now.getMonth() + 1;
    var nowDate = now.getDate();
    var nowHour = now.getHours();
    var nowMinute = now.getMinutes();
    var defaultYear = nowYear;
    var defaultQuarter = nowQuarter;
    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 === 'year') {
      // 如果不是合法的日期格式
      if (!defaultValue || !defaultValue.isYear()) {
        if (onError) onError(e, {
          errMsg: locale('无效的日期格式', 'hint_invalid_date') + ", YYYY-MM-DD"
        });
      }
    } else if (type === 'quarter') {
      // 如果不是合法的日期格式
      if (!defaultValue || !defaultValue.isQuarter(split)) {
        if (onError) onError(e, {
          errMsg: locale('无效的日期格式', 'hint_invalid_date') + ", YYYY-MM-DD"
        });
      } else {
        var quarterValues = defaultValue.split(split);
        defaultYear = quarterValues[0];
        defaultQuarter = quarterValues[1];
      }
    } 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 === '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 === '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,
      quarter: defaultQuarter,
      month: defaultMonth,
      day: defaultDay,
      hour: defaultHour,
      minute: defaultMinute
    };
  }

  function getData() {
    // 自定义数据
    var yearsData = null;
    var quartersData = 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('', 'picker_unit_year') // 年

          };
        });
      }

      if (data.quarter) {
        quartersData = data.quarter.map(function (n) {
          return {
            id: '' + n,
            name: '' + n + locale('', 'picker_unit_quarter') // 季

          };
        });
      }

      if (data.month) {
        monthsData = data.month.map(function (n) {
          return {
            id: '' + n,
            name: '' + n + locale('', 'picker_unit_month') // 月

          };
        });
      }

      if (data.day) {
        daysData = data.day.map(function (n) {
          return {
            id: '' + n,
            name: '' + n + locale('', 'picker_unit_date') // 日

          };
        });
      }

      if (data.hour) {
        hoursData = data.hour.map(function (n) {
          return {
            id: '' + n,
            name: '' + n + locale('', 'picker_unit_hour') // 时

          };
        });
      }

      if (data.minute) {
        minutesData = data.minute.map(function (n) {
          return {
            id: '' + n,
            name: '' + n + locale('', 'picker_unit_minute') // 分

          };
        });
      }
    }

    return {
      yearsData: yearsData,
      quartersData: quartersData,
      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 Instance(_extends({
      mask: refEl.current
    }, params, {
      split: split,
      timeSplit: timeSplit,
      viewType: type,
      yearsData: data.yearsData,
      quartersData: data.quartersData,
      monthsData: data.monthsData,
      daysData: data.daysData,
      hoursData: data.hoursData,
      minutesData: data.minutesData,
      defaultYear: def.year,
      defaultQuarter: def.quarter,
      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('', 'picker_unit_year'),
      // 年
      QQUnit: locale('', 'picker_unit_quarter'),
      // 季
      MMUnit: locale('', 'picker_unit_month'),
      // 月
      ddUnit: locale('', 'picker_unit_date'),
      // 日
      hhUnit: locale('', 'picker_unit_hour'),
      // 时
      mmUnit: locale('', 'picker_unit_minute') // 分

    }));

    if (show && instance) {
      setTimeout(function () {
        instance.current.show();
      }, 10);
    }
  } // 过滤已经回调的属性


  function filterProps(props) {
    if (!props) return {};

    var caption = props.caption,
        onClick = props.onClick,
        otherProps = _objectWithoutPropertiesLoose(props, _excluded2);

    return _extends({}, otherProps);
  } // 剔除掉onClick事件, 因为在instance时已经回调了


  var otherMaskAttribute = filterProps(maskAttribute);
  var otherSubmitAttribute = filterProps(submitAttribute);
  var otherCancelAttribute = filterProps(cancelAttribute);
  return createPortal( /*#__PURE__*/React.createElement("div", _extends({
    ref: refEl
  }, otherMaskAttribute, {
    className: "mask picker-mask" + (otherMaskAttribute.className ? ' ' + otherMaskAttribute.className : '')
  }), /*#__PURE__*/React.createElement("div", _extends({}, others, {
    className: "picker" + (others.className ? ' ' + others.className : '')
  }), /*#__PURE__*/React.createElement("div", {
    className: "picker-header"
  }, /*#__PURE__*/React.createElement("a", _extends({}, otherCancelAttribute, {
    className: "picker-cancel" + (cancelAttribute.className ? ' ' + cancelAttribute.className : '')
  }), cancelAttribute.caption || locale('取消', 'cancel')), /*#__PURE__*/React.createElement("div", {
    className: "picker-header-title"
  }), /*#__PURE__*/React.createElement("a", _extends({}, otherSubmitAttribute, {
    className: "picker-submit" + (submitAttribute.className ? ' ' + submitAttribute.className : '')
  }), submitAttribute.caption || locale('完成', 'finish'))), /*#__PURE__*/React.createElement("div", {
    className: "picker-wrapper"
  }, /*#__PURE__*/React.createElement("div", {
    className: "picker-layer"
  }, /*#__PURE__*/React.createElement("div", {
    className: "picker-layer-frame"
  })), /*#__PURE__*/React.createElement("div", {
    className: "picker-slotbox"
  })))), portal || context.portal || document.getElementById('root') || document.body);
});
export default React.memo(PickerDate, function (prevProps, nextProps) {
  if (nextProps.show === prevProps.show) return true;
  return false;
});