import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { __awaiter, __rest } from "tslib";
import classNames from 'classnames';
import React, { createContext, createElement, forwardRef, Fragment, useEffect, useRef, useState, Children, cloneElement } from "react";
import { ScrollView, Text } from "@alifd/meet-react-component-one";
import Icon from '../icon';
import { useLocale } from '../locale';
import defaultLang from '../locale/lang/zh-cn';
import Picker from '../picker';
import { BaseSelectDrawer } from '../select-drawer';
import { getLeft, getScrollLeft, getWidth, isFunction, isValidArray, isStrictWechatMiniProgram, screenPixelRatio } from '../utils';
import { useGuid } from '../utils/hooks';
import View from '../view';
import TabItem from './item';
export var TabContext = /*#__PURE__*/createContext({
  activeKey: -1,
  fullWidth: true,
  shape: 'normal',
  activeLineType: 'normal',
  change: function change() {}
});

var getTabData = function getTabData(props) {
  var dataSource = props.dataSource,
      children = props.children;

  if (isValidArray(dataSource)) {
    return dataSource.map(function (item) {
      return Object.assign(Object.assign({}, item), {
        label: item.title,
        value: item.key
      });
    });
  } else if (children) {
    return Children.map(children, function (child) {
      var title = child.props.title;
      var key = child.key;
      return {
        label: title,
        value: key
      };
    });
  } else {
    return [];
  }
};

var getInitActiveKey = function getInitActiveKey(props) {
  if ('activeKey' in props && props.activeKey) {
    return props.activeKey;
  } else if (props.defaultActiveKey || props.defaultActiveKey === 0) {
    return props.defaultActiveKey;
  } else {
    return undefined;
  }
};

var timerMap = {};

var Tab = function Tab(props, ref) {
  var _classNames3;

  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      activeKey = props.activeKey,
      _props$defaultActiveK = props.defaultActiveKey,
      defaultActiveKey = _props$defaultActiveK === void 0 ? -1 : _props$defaultActiveK,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      _props$activeLineType = props.activeLineType,
      activeLineType = _props$activeLineType === void 0 ? 'normal' : _props$activeLineType,
      _props$shape = props.shape,
      shape = _props$shape === void 0 ? 'normal' : _props$shape,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? true : _props$fullWidth,
      renderTool = props.renderTool,
      _props$onChange = props.onChange,
      onChange = _props$onChange === void 0 ? function () {} : _props$onChange,
      _props$dataSource = props.dataSource,
      dataSource = _props$dataSource === void 0 ? [] : _props$dataSource,
      className = props.className,
      contentClassName = props.contentClassName,
      contentStyle = props.contentStyle,
      renderTab = props.renderTab,
      children = props.children,
      others = __rest(props, ["prefix", "activeKey", "defaultActiveKey", "size", "activeLineType", "shape", "fullWidth", "renderTool", "onChange", "dataSource", "className", "contentClassName", "contentStyle", "renderTab", "children"]);

  var locale = useLocale('Tab', others, defaultLang.Tab);

  var _useState = useState(getInitActiveKey(props)),
      _useState2 = _slicedToArray(_useState, 2),
      curActiveKey = _useState2[0],
      setActiveKey = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      drawerVisible = _useState4[0],
      setDrawerVisible = _useState4[1];

  var _useState5 = useState(getInitActiveKey(props)),
      _useState6 = _slicedToArray(_useState5, 2),
      internalTabKey = _useState6[0],
      setInternalActiveKey = _useState6[1];

  var curTabScrollId = useGuid('tab-scroll-');
  var curScrollContainerId = useGuid('tab-ctn-');
  var scrollRef = useRef();
  var activeTabRef = useRef();
  var isControlled = ('activeKey' in props);

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      isOverflow = _useState8[0],
      setOverflow = _useState8[1];

  var isExcessMode = !fullWidth && isOverflow;
  var clsPrefix = "".concat(prefix, "tab");
  var clses = {
    tab: classNames([clsPrefix, "".concat(clsPrefix, "--").concat(shape), className]),
    divider: classNames(_defineProperty({}, "".concat(clsPrefix, "-divider"), shape !== 'capsule')),
    container: classNames("".concat(clsPrefix, "-container"), _defineProperty({}, "".concat(clsPrefix, "-container--wechat"), isStrictWechatMiniProgram)),
    scrollContainer: classNames("".concat(clsPrefix, "-scroll-container"), (_classNames3 = {}, _defineProperty(_classNames3, "".concat(clsPrefix, "-scroll-container--fullwidth"), fullWidth), _defineProperty(_classNames3, "".concat(clsPrefix, "-scroll-container--wechat"), isStrictWechatMiniProgram), _classNames3)),
    tool: classNames("".concat(clsPrefix, "-tool"), "".concat(clsPrefix, "-tool--").concat(size)),
    toolIcon: classNames("".concat(clsPrefix, "-tool-icon"), "".concat(clsPrefix, "-tool-icon--").concat(size)),
    drawer: classNames("".concat(clsPrefix, "-drawer")),
    content: classNames("".concat(clsPrefix, "-content"), contentClassName)
  };

  var scrollTo = function scrollTo(offset) {
    if (!timerMap[curTabScrollId]) {
      timerMap[curTabScrollId] = setTimeout(function () {
        if (scrollRef && scrollRef.current && scrollRef.current.scrollTo) {
          scrollRef.current.scrollTo(Object.assign(Object.assign({}, offset), {
            duration: 150
          }));
          timerMap[curTabScrollId] = null;
        }
      }, 200);
    }
  };

  useEffect(function () {
    if (isControlled && curActiveKey && !props.activeKey) {
      setActiveKey(getInitActiveKey(props));
      return;
    }

    if (isControlled) {
      setActiveKey(props.activeKey);
    }
  });
  useEffect(function () {
    setTimeout(function () {
      (function () {
        return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
          var activeTabId, containerWidth, containerOffsetLeft, scrollLeft, activeTabWidth, activeTabOffsetLeft, totalWidth, centerMarkerPos, distance;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  activeTabId = activeTabRef.current && activeTabRef.current.id;
                  _context.next = 3;
                  return getWidth(curTabScrollId);

                case 3:
                  containerWidth = _context.sent;
                  _context.next = 6;
                  return getLeft(curTabScrollId);

                case 6:
                  containerOffsetLeft = _context.sent;
                  _context.next = 9;
                  return getScrollLeft(curTabScrollId);

                case 9:
                  scrollLeft = _context.sent;
                  _context.next = 12;
                  return getWidth(activeTabId);

                case 12:
                  activeTabWidth = _context.sent;
                  _context.next = 15;
                  return getLeft(activeTabId);

                case 15:
                  _context.t0 = _context.sent;
                  _context.t1 = containerOffsetLeft;
                  activeTabOffsetLeft = _context.t0 - _context.t1;
                  _context.next = 20;
                  return getWidth(curScrollContainerId);

                case 20:
                  totalWidth = _context.sent;
                  centerMarkerPos = containerWidth / 2;

                  if (!fullWidth) {
                    setOverflow(totalWidth > containerWidth);
                  }

                  if (scrollRef.current && activeTabRef.current) {
                    distance = Math.floor(Math.max(activeTabOffsetLeft - centerMarkerPos + scrollLeft + activeTabWidth / 2, 0));

                    if (scrollLeft !== distance) {
                      scrollTo({
                        x: distance / screenPixelRatio,
                        y: 0
                      });
                    }
                  }

                case 24:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
      })();
    }, 50);
  });
  var content;

  if (dataSource && dataSource.length > 0) {
    content = dataSource.map(function (item, index) {
      return /*#__PURE__*/React.createElement(TabItem, _extends({
        key: item.key || index,
        itemKey: item.key,
        renderContent: renderTab,
        ref: item.key === curActiveKey ? activeTabRef : null,
        prefix: prefix,
        size: size
      }, item));
    });
  } else {
    content = Children.map(children, function (child, index) {
      return cloneElement(child, {
        key: "mt_tab_".concat(index),
        itemKey: child.key || index,
        ref: "".concat(child.key) === "".concat(curActiveKey) ? activeTabRef : null,
        renderContent: child.renderContent || renderTab,
        prefix: prefix,
        size: size
      });
    });
  }

  var getTool = function getTool() {
    if (!isExcessMode) {
      return null;
    }

    var _children = /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(Text, null, locale.more), /*#__PURE__*/React.createElement(Icon, {
      className: clses.toolIcon,
      name: "arrow-down",
      size: "xxs"
    }));

    if (isFunction(renderTool)) {
      var renderedToolEl = renderTool();

      if (renderedToolEl) {
        _children = renderedToolEl;
      } else {
        _children = null;
      }
    }

    return _children ? /*#__PURE__*/React.createElement(View, {
      className: clses.tool,
      onClick: function onClick() {
        setDrawerVisible(true);
        setInternalActiveKey(curActiveKey);
      }
    }, _children) : null;
  };

  var handleChange = function handleChange(v) {
    if (!isControlled) {
      setActiveKey(v);
    }

    onChange(v);
  };

  var handleDrawerOk = function handleDrawerOk() {
    setDrawerVisible(false);
    handleChange(internalTabKey);
  };

  var handleDrawerCancel = function handleDrawerCancel() {
    setDrawerVisible(false);
    setInternalActiveKey(curActiveKey);
  };

  var getChildren = function getChildren(activeTabKey) {
    var ret = null;
    Children.forEach(children, function (child) {
      if (ret) {
        return;
      }

      var _key = child.key;

      if ("".concat(_key) === "".concat(activeTabKey)) {
        ret = child.props.children;
      }
    });
    return ret;
  };

  return /*#__PURE__*/React.createElement(TabContext.Provider, {
    value: {
      activeKey: curActiveKey,
      change: handleChange,
      shape: shape,
      fullWidth: fullWidth,
      activeLineType: activeLineType
    }
  }, /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(View, _extends({}, others, {
    className: clses.tab,
    ref: ref
  }), /*#__PURE__*/React.createElement(ScrollView, {
    ref: scrollRef,
    id: curTabScrollId,
    className: clses.container,
    contentContainerStyle: {
      flex: props.renderTool ? null : 1
    },
    horizontal: true,
    showsHorizontalScrollIndicator: false
  }, /*#__PURE__*/React.createElement(View, {
    id: curScrollContainerId,
    className: clses.scrollContainer
  }, content)), shape !== 'capsule' && /*#__PURE__*/React.createElement(View, {
    className: clses.divider
  }), getTool()), /*#__PURE__*/React.createElement(View, {
    className: clses.content,
    style: __rpx2vw__(contentStyle)
  }, getChildren(curActiveKey))), isExcessMode ? /*#__PURE__*/React.createElement(BaseSelectDrawer, {
    visible: drawerVisible,
    onOk: handleDrawerOk,
    onCancel: handleDrawerCancel
  }, /*#__PURE__*/React.createElement(ScrollView, {
    className: clses.drawer
  }, /*#__PURE__*/React.createElement(Picker, {
    cascade: true,
    data: getTabData(props),
    value: [internalTabKey],
    onChange: function onChange(v) {
      if (isValidArray(v)) {
        setInternalActiveKey(v[0]);
      }
    }
  }))) : null);
};

Tab.displayName = 'Tab';
export default /*#__PURE__*/forwardRef(Tab);