"use strict";

exports.__esModule = true;
exports.default = void 0;
var _tslib = require("tslib");
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _reactDom = require("react-dom");
var _meetReactComponentOne = require("@alifd/meet-react-component-one");
var _utils = require("../utils");
var _hooks = require("../utils/hooks");
var _view = _interopRequireDefault(require("../view"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
var isIOS10 = _utils.isIOS && /^10./.test(_utils.osVersion);
var isPassiveSupported = function () {
  var passiveSupported = false;
  try {
    var options = Object.defineProperty({}, 'passive', {
      get: function get() {
        passiveSupported = true;
      }
    });
    window.addEventListener('test', null, options);
  } catch (err) {}
  return passiveSupported;
};
var createScrollHandlers = function (fromOptions) {
  var options = fromOptions;
  var scrollY = -1;
  var lastY = 0;
  var startY = 0;
  var scrollDisabled = false;
  var isMoving = false;
  var cachedTransform = null;
  var isTransformRunning = false;
  var setTransform = function (nodeStyle, value) {
    cachedTransform = value;
    if (isTransformRunning) {
      return;
    }
    isTransformRunning = true;
    (0, _utils.nextTick)(function () {
      nodeStyle.transform = cachedTransform;
      nodeStyle.webkitTransform = cachedTransform;
      isTransformRunning = false;
    });
  };
  var cachedTransition = null;
  var isTransitionRunning = false;
  var setTransition = function (nodeStyle, value) {
    cachedTransition = value;
    if (isTransitionRunning) {
      return;
    }
    isTransitionRunning = true;
    (0, _utils.nextTick)(function () {
      nodeStyle.transition = cachedTransition;
      nodeStyle.webkitTransition = cachedTransition;
      isTransitionRunning = false;
    });
  };
  var scrollTo = function (_x, y, time) {
    if (time === void 0) {
      time = 0.3;
    }
    if (scrollY !== y) {
      scrollY = y;
      if (time) {
        setTransition(options.contentDOM.style, "cubic-bezier(0,0,0.2,1.15) " + time + "s");
      }
      setTransform(options.contentDOM.style, "translate3d(0," + -y + "px,0)");
      setTimeout(function () {
        options.scrollingComplete();
        if (options.contentDOM) {
          setTransition(options.contentDOM.style, '');
        }
      }, +time * 1000);
    }
  };
  var Velocity = function (minInterval, maxInterval) {
    if (minInterval === void 0) {
      minInterval = 30;
    }
    if (maxInterval === void 0) {
      maxInterval = 100;
    }
    var _time = 0;
    var _y = 0;
    var _velocity = 0;
    var recorder = {
      record: function record(y) {
        var now = +new Date();
        _velocity = (y - _y) / (now - _time);
        if (now - _time >= minInterval) {
          _velocity = now - _time <= maxInterval ? _velocity : 0;
          _y = y;
          _time = now;
        }
      },
      getVelocity: function getVelocity(y) {
        if (y !== _y) {
          recorder.record(y);
        }
        return _velocity;
      }
    };
    return recorder;
  }();
  var onFinish = function () {
    isMoving = false;
    var targetY = scrollY;
    var height = (options.items.length - 1) * options.itemHeight;
    var time = 0.3;
    var velocity = Velocity.getVelocity(targetY) * 4;
    if (velocity) {
      targetY = velocity * 40 + targetY;
      time = Math.abs(velocity) * 0.1;
    }
    if (targetY % options.itemHeight !== 0) {
      targetY = Math.round(targetY / options.itemHeight) * options.itemHeight;
    }
    if (targetY < 0) {
      targetY = 0;
    } else if (targetY > height) {
      targetY = height;
    }
    scrollTo(0, targetY, time < 0.3 ? 0.3 : time);
    options.onScrollChange();
  };
  var onStart = function (y) {
    if (scrollDisabled) {
      return;
    }
    isMoving = true;
    startY = y;
    lastY = scrollY;
  };
  var onMove = function (y) {
    if (scrollDisabled || !isMoving) {
      return;
    }
    scrollY = lastY - y + startY;
    Velocity.record(scrollY);
    options.onScrollChange();
    setTransform(options.contentDOM.style, "translate3d(0," + -scrollY + "px,0)");
  };
  return {
    setOptions: function setOptions(x) {
      return options = x;
    },
    touchstart: function touchstart(evt) {
      return onStart(evt.touches[0].pageY);
    },
    mousedown: function mousedown(evt) {
      return onStart(evt.pageY);
    },
    touchmove: function touchmove(evt) {
      evt.preventDefault();
      onMove(evt.touches[0].pageY);
    },
    mousemove: function mousemove(evt) {
      evt.preventDefault();
      onMove(evt.pageY);
    },
    touchend: function touchend() {
      return onFinish();
    },
    touchcancel: function touchcancel() {
      return onFinish();
    },
    mouseup: function mouseup() {
      return onFinish();
    },
    getValue: function getValue() {
      return scrollY;
    },
    scrollTo: scrollTo,
    setDisabled: function setDisabled(disabled) {
      if (disabled === void 0) {
        disabled = false;
      }
      scrollDisabled = disabled;
    }
  };
};
var PickerColumn = function (props, ref) {
  var _classNames;
  var _props$prefix = props.prefix,
    prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
    value = props.value,
    _props$data = props.data,
    data = _props$data === void 0 ? [] : _props$data,
    _props$onChange = props.onChange,
    onChange = _props$onChange === void 0 ? function () {} : _props$onChange,
    onScrollChange = props.onScrollChange,
    others = (0, _tslib.__rest)(props, ["prefix", "value", "data", "onChange", "onScrollChange"]);
  var forceUpdate = (0, _hooks.useForceUpdate)();
  var scrollHandlers = (0, _react.useRef)(null);
  var scrollRef = /*#__PURE__*/(0, _react.createRef)();
  var contentRef = /*#__PURE__*/(0, _react.createRef)();
  var itemRef = /*#__PURE__*/(0, _react.createRef)();
  var maskRef = /*#__PURE__*/(0, _react.createRef)();
  var itemHeight;
  var scrollValue;
  var selectByIndex = function (index, height, zscrollTo) {
    if (index < 0 || index >= data.length || !height) {
      return;
    }
    zscrollTo(index * height);
  };
  var select = function (v, height, scrollTo) {
    for (var i = 0; i < data.length; i++) {
      if (data[i].value === v) {
        selectByIndex(i, height, scrollTo);
        return;
      }
    }
    selectByIndex(0, height, scrollTo);
  };
  var computeChildIndex = function (top, height, length) {
    var index = Math.round(top / height);
    return Math.min(index, length - 1);
  };
  var doScrollingComplete = function (top, height, doValueChange) {
    var index = computeChildIndex(top, height, data.length);
    var child = data[index];
    if (child) {
      if (!child.disabled) {
        doValueChange(child.value);
      } else {
        (0, _utils.nextTick)(function () {
          select(value, itemHeight, function (t) {
            return scrollHandlers.current.scrollTo(0, t, 0.4);
          });
        });
      }
    } else if (console.warn) {
      console.warn('item not found', data, index);
    }
  };
  var fireValueChange = function (sValue) {
    if (sValue !== value) {
      onChange(sValue);
      (0, _utils.nextTick)(function () {
        return forceUpdate();
      });
    }
  };
  var scrollToWithoutAnimation = function (top) {
    if (scrollHandlers.current) {
      scrollHandlers.current.scrollTo(0, top, 0);
    }
  };
  var handleScrollChange = function () {
    var top = scrollHandlers.current.getValue();
    if (top >= 0) {
      var index = computeChildIndex(top, itemHeight, data.length);
      if (scrollValue !== index) {
        scrollValue = index;
        var child = data[index];
        if (child && onScrollChange) {
          onScrollChange(child.value);
        } else if (!child && console.warn) {
          console.warn('child not found', data, index);
        }
      }
    }
  };
  var handleScrollComplete = function () {
    var top = scrollHandlers.current.getValue();
    if (top >= 0) {
      doScrollingComplete(top, itemHeight, fireValueChange);
    }
  };
  (0, _react.useEffect)(function () {
    setTimeout(function () {
      var itemNode = itemRef.current;
      var maskNode = maskRef.current;
      var scrollNode = scrollRef.current;
      var contentNode = contentRef.current;
      if (!itemNode) {
        return undefined;
      }
      itemHeight = itemNode.getBoundingClientRect().height;
      maskNode.style.backgroundSize = "100% " + 3 * itemHeight + "px";
      if (!scrollHandlers.current) {
        scrollHandlers.current = createScrollHandlers({
          onScrollChange: handleScrollChange,
          scrollingComplete: handleScrollComplete,
          contentDOM: contentNode,
          items: data,
          itemHeight: itemHeight
        });
        var passiveSupported = isPassiveSupported();
        var willPreventDefault = passiveSupported ? {
          passive: false
        } : false;
        var willNotPreventDefault = passiveSupported ? {
          passive: true
        } : false;
        Object.keys(scrollHandlers.current).forEach(function (key) {
          if (key.indexOf('touch') === 0 || key.indexOf('mouse') === 0) {
            var pd = key.indexOf('move') >= 0 ? willPreventDefault : willNotPreventDefault;
            scrollNode.addEventListener(key, scrollHandlers.current[key], pd);
          }
        });
      } else {
        scrollHandlers.current.setOptions({
          onScrollChange: handleScrollChange,
          scrollingComplete: handleScrollComplete,
          contentDOM: contentNode,
          items: data,
          itemHeight: itemHeight
        });
      }
      select(value, itemHeight, scrollToWithoutAnimation);
      return function () {
        Object.keys(scrollHandlers).forEach(function (key) {
          if (key.indexOf('touch') === 0 || key.indexOf('mouse') === 0) {
            scrollNode.removeEventListener(key, scrollHandlers[key]);
          }
        });
      };
    }, 50);
  });
  var clsPrefix = prefix + "picker";
  return /*#__PURE__*/(0, _react.createElement)(_view.default, _extends({}, others, {
    className: clsPrefix + "-item",
    ref: ref
  }), /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: (0, _classnames.default)(clsPrefix + "-col", (_classNames = {}, _classNames[clsPrefix + "-col--ios10"] = isIOS10, _classNames)),
    ref: scrollRef
  }, /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: clsPrefix + "-mask",
    ref: maskRef
  }), /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: clsPrefix + "-indicator"
  }), /*#__PURE__*/(0, _react.createElement)(_view.default, {
    className: clsPrefix + "-content",
    ref: contentRef
  }, data.map(function (item, index) {
    var _classNames2;
    return /*#__PURE__*/(0, _react.createElement)(_view.default, {
      key: index,
      className: (0, _classnames.default)(clsPrefix + "-col-item", (_classNames2 = {}, _classNames2[clsPrefix + "-col-item--disabled"] = item.disabled, _classNames2[clsPrefix + "-col-item--selected"] = !item.disabled && item.value === value, _classNames2)),
      ref: index === 0 ? itemRef : null
    }, /*#__PURE__*/(0, _react.createElement)(_meetReactComponentOne.Text, {
      className: clsPrefix + "-col-item-text",
      numberOfLines: 1
    }, item.label));
  }))));
};
var _default = /*#__PURE__*/(0, _react.forwardRef)(PickerColumn);
exports.default = _default;