import _regeneratorRuntime from "@babel/runtime/regenerator";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate 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; }

import React, { forwardRef, useRef, useImperativeHandle, useEffect, useState, Fragment } from 'react';
import Tabbar from './../Tabbar';
import DropdownDialog from './DropdownDialog';
var Dropdown = forwardRef(function (_ref, ref) {
  var top = _ref.top,
      portal = _ref.portal,
      disabled = _ref.disabled,
      onChange = _ref.onChange,
      listRoot = _ref.listRoot,
      list = _ref.list,
      _ref$tabbarProps = _ref.tabbarProps,
      tabbarProps = _ref$tabbarProps === void 0 ? {} : _ref$tabbarProps,
      _ref$dialogProps = _ref.dialogProps,
      dialogProps = _ref$dialogProps === void 0 ? {} : _ref$dialogProps,
      _ref$menutiledProps = _ref.menutiledProps,
      menutiledProps = _ref$menutiledProps === void 0 ? {} : _ref$menutiledProps;
  var tabbarRef = useRef(null);
  useImperativeHandle(ref, function () {
    return tabbarRef.current;
  });

  var _useState = useState(-1),
      activeIndex = _useState[0],
      setActiveIndex = _useState[1];

  var _useState2 = useState([]),
      selected = _useState2[0],
      setSelected = _useState2[1];

  var _useState3 = useState(false),
      menusMultiple = _useState3[0],
      setMenusMultiple = _useState3[1];

  var _useState4 = useState([]),
      menus = _useState4[0],
      setMenus = _useState4[1];

  var _useState5 = useState(0),
      offsetTop = _useState5[0],
      setOffsetTop = _useState5[1];

  var _useState6 = useState(false),
      show = _useState6[0],
      setShow = _useState6[1]; // 改造tab数据


  var tabs = [];

  if (Array.isArray(list) && list.length) {
    for (var _iterator = _createForOfIteratorHelperLoose(list), _step; !(_step = _iterator()).done;) {
      var item = _step.value;
      tabs.push(_extends({}, item, {
        ricon: /*#__PURE__*/React.createElement("span", {
          className: "icon tab-icon shape-triangle-down"
        })
      }));
    }
  } // 初始化遮罩距离顶部间距


  function getMaskTop() {
    return new Promise(function (resolve) {
      // 计算距离头部
      var maskTop = top;

      if (!maskTop) {
        setTimeout(function () {
          var rect = tabbarRef.current.getBoundingClientRect(); // maskTop = tabbarRef.current.offsetTop + 40;

          maskTop = rect.top + (tabbarRef.current.clientHeight || 40);
          resolve(maskTop);
        }, 100);
      } else {
        resolve(maskTop);
      }
    });
  }

  useEffect(function () {
    function fetchData() {
      return _fetchData.apply(this, arguments);
    }

    function _fetchData() {
      _fetchData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var maskTop;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return getMaskTop();

              case 2:
                maskTop = _context.sent;
                setOffsetTop(maskTop);

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));
      return _fetchData.apply(this, arguments);
    }

    fetchData();
  }, []); // eslint-disable-line
  // 点击Tabbar, 选中此项, 并显示或者隐藏Dialog

  function handleClickTab(e, value, options, index) {
    var ids = tabs[index].id.split(',');
    var names = tabs[index].name.split(',');
    selected = [];

    for (var _iterator2 = _createForOfIteratorHelperLoose(ids.entries()), _step2; !(_step2 = _iterator2()).done;) {
      var _step2$value = _step2.value,
          _index = _step2$value[0],
          id = _step2$value[1];
      selected.push({
        id: id,
        name: names[_index]
      });
    }

    setSelected(selected);
    setMenusMultiple(list[index].multiple);
    setMenus(list[index].data);

    if (activeIndex >= 0) {
      // 隐藏弹框
      setActiveIndex(-1);
      setShow(false);
    } else {
      // 显示弹框
      setActiveIndex(index);
      setShow(true);
    }
  } // 点击遮罩隐藏


  function handleClickMask(e) {
    setActiveIndex(-1);
    setShow(false);

    if (dialogProps && dialogProps.maskAttribute && dialogProps.maskAttribute.onClick) {
      dialogProps.maskAttribute.onClick(e);
    }
  } // 选中项是否是根节点


  function selectedIsRoot(selected) {
    if (!listRoot || !listRoot.length) return false;
    if (!selected || !selected.length) return true;

    if (selected.length === 1) {
      if (menusMultiple) {
        return selected[0].isroot === '1';
      }

      for (var _iterator3 = _createForOfIteratorHelperLoose(listRoot), _step3; !(_step3 = _iterator3()).done;) {
        var tab = _step3.value;
        if (tab.id === selected[0].id) return true;
      }
    }

    return false;
  } // 选中项


  function handleSelected(e, value, selected, data) {
    // 判断是否是根节点
    var isRoot = selectedIsRoot(selected);

    if (!selected || !selected.length) {} else {
      // 单选展开
      if (selected[0].children && selected[0].children.length > 0) return; // 选中id和name

      var id = [];
      var name = [];

      for (var _iterator4 = _createForOfIteratorHelperLoose(selected), _step4; !(_step4 = _iterator4()).done;) {
        var selectedItem = _step4.value;
        id.push(selectedItem.id);
        name.push(selectedItem.name);
      }

      id = id.join(',');
      name = name.join(','); // 设置选中的id和name

      tabs[activeIndex].id = id;
      tabs[activeIndex].name = name;
    } // 删除增加的ricon属性


    for (var _iterator5 = _createForOfIteratorHelperLoose(tabs), _step5; !(_step5 = _iterator5()).done;) {
      var tab = _step5.value;
      delete tab.ricon;
    } // 如果选中根节点


    if (isRoot) {
      tabs[activeIndex].name = listRoot[activeIndex].name;
      tabs[activeIndex].id = listRoot[activeIndex].id;
    }

    setActiveIndex(-1);
    setShow(false); // 触发onChange事件

    setSelected(selected);
    var names = [];

    if (tabs && tabs.length) {
      names = tabs.map(function (tab) {
        return tab.name;
      });
      names = names.join(',');
    }

    if (onChange) onChange(e, names, tabs);
  }

  return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(Tabbar, _extends({
    disabled: disabled,
    ref: tabbarRef,
    exceptOnClickActive: false,
    list: tabs,
    onChange: handleClickTab,
    activeIndex: activeIndex,
    className: "tabbar-dropdown tabbar-tiled border-b"
  }, tabbarProps)), /*#__PURE__*/React.createElement(DropdownDialog, {
    show: show,
    dialogProps: _extends({}, dialogProps || {}, {
      portal: portal,
      maskAttribute: _extends({}, dialogProps && dialogProps.maskAttribute ? dialogProps.maskAttribute : {}, {
        onClick: handleClickMask,
        style: _extends({
          top: offsetTop + 'px'
        }, dialogProps && dialogProps.maskAttribute && dialogProps.maskAttribute.style ? dialogProps.maskAttribute.style : {})
      })
    }),
    multiple: menusMultiple,
    list: menus,
    selected: selected,
    onChange: handleSelected,
    menutiledProps: menutiledProps
  }));
});
export default Dropdown;