'use strict';

exports.__esModule = true;

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

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 _Tabbar = require('./../Tabbar');

var _Tabbar2 = _interopRequireDefault(_Tabbar);

var _DropdownDialog = require('./DropdownDialog');

var _DropdownDialog2 = _interopRequireDefault(_DropdownDialog);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

var Dropdown = (0, _react.forwardRef)(function (_ref, ref) {
  var top = _ref.top,
      disabled = _ref.disabled,
      onChange = _ref.onChange,
      listRoot = _ref.listRoot,
      list = _ref.list,
      _ref$tabbarProps = _ref.tabbarProps,
      tabbarProps = _ref$tabbarProps === undefined ? {} : _ref$tabbarProps,
      _ref$dialogProps = _ref.dialogProps,
      dialogProps = _ref$dialogProps === undefined ? {} : _ref$dialogProps,
      _ref$menutiledProps = _ref.menutiledProps,
      menutiledProps = _ref$menutiledProps === undefined ? {} : _ref$menutiledProps;

  var refElTabbar = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return refElTabbar.current;
  });

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

  var _useState2 = (0, _react.useState)([]),
      tabs = _useState2[0],
      setTabs = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      selected = _useState3[0],
      setSelected = _useState3[1];

  var _useState4 = (0, _react.useState)(false),
      menusMultiple = _useState4[0],
      setMenusMultiple = _useState4[1];

  var _useState5 = (0, _react.useState)([]),
      menus = _useState5[0],
      setMenus = _useState5[1];

  var _useState6 = (0, _react.useState)(0),
      offsetTop = _useState6[0],
      setOffsetTop = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      show = _useState7[0],
      setShow = _useState7[1];

  function refresh() {
    if (!list) return;
    // Tabbar 和 MenuTiled
    var newTabs = [];
    for (var _iterator = list, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
      var _ref2;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref2 = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref2 = _i.value;
      }

      var item = _ref2;

      newTabs.push(_extends({}, item, {
        ricon: _react2.default.createElement('span', { className: 'icon tab-icon shape-triangle-down' })
      }));
    };
    setTabs(newTabs);
  }

  function getMaskTop() {
    return new Promise(function (resolve) {
      // 计算距离头部
      var maskTop = top;
      if (!maskTop) {
        setTimeout(function () {
          maskTop = refElTabbar.current.offsetTop + 40;
          resolve(maskTop);
        }, 100);
      } else {
        resolve(maskTop);
      }
    });
  }

  (0, _react.useEffect)(function () {
    var fetchData = function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
        var maskTop;
        return _regenerator2.default.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);
                // 更新数据
                refresh();

              case 5:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

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

    fetchData();
  }, []); // eslint-disable-line

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

  function onClickTab(e, item, index) {
    var ids = tabs[index].id.split(',');
    var names = tabs[index].name.split(',');
    selected = [];
    for (var _iterator2 = ids.entries(), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
      var _ref5;

      if (_isArray2) {
        if (_i2 >= _iterator2.length) break;
        _ref5 = _iterator2[_i2++];
      } else {
        _i2 = _iterator2.next();
        if (_i2.done) break;
        _ref5 = _i2.value;
      }

      var _ref4 = _ref5;
      var _index = _ref4[0];
      var id = _ref4[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 onClickMask(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 = listRoot, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
        var _ref6;

        if (_isArray3) {
          if (_i3 >= _iterator3.length) break;
          _ref6 = _iterator3[_i3++];
        } else {
          _i3 = _iterator3.next();
          if (_i3.done) break;
          _ref6 = _i3.value;
        }

        var tab = _ref6;

        if (tab.id === selected[0].id) return true;
      }
    }
    return false;
  }
  function onSelected(e, value, selected, data) {
    var newTabs = Object.clone(tabs);
    // 判断是否是根节点
    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 = selected, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
        var _ref7;

        if (_isArray4) {
          if (_i4 >= _iterator4.length) break;
          _ref7 = _iterator4[_i4++];
        } else {
          _i4 = _iterator4.next();
          if (_i4.done) break;
          _ref7 = _i4.value;
        }

        var selectedItem = _ref7;

        id.push(selectedItem.id);
        name.push(selectedItem.name);
      }
      id = id.join(',');
      name = name.join(',');
      // 设置选中的id和name
      newTabs[activeIndex].id = id;
      newTabs[activeIndex].name = name;
    }

    // 删除增加的ricon属性
    for (var _iterator5 = newTabs, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
      var _ref8;

      if (_isArray5) {
        if (_i5 >= _iterator5.length) break;
        _ref8 = _iterator5[_i5++];
      } else {
        _i5 = _iterator5.next();
        if (_i5.done) break;
        _ref8 = _i5.value;
      }

      var tab = _ref8;

      delete tab.ricon;
    }
    // 如果选中根节点
    if (isRoot) {
      newTabs[activeIndex].name = listRoot[activeIndex].name;
      newTabs[activeIndex].id = listRoot[activeIndex].id;
    }
    setActiveIndex(-1);
    setShow(false);
    // 触发onChange事件
    setSelected(selected);
    if (onChange) onChange(e, newTabs);
  }
  return _react2.default.createElement(
    _react.Fragment,
    null,
    _react2.default.createElement(_Tabbar2.default, _extends({
      disabled: disabled,
      ref: refElTabbar,
      exceptOnClickActive: false,
      list: tabs,
      onClick: onClickTab,
      activeIndex: activeIndex,
      className: 'tabbar-dropdown tabbar-tiled border-b'
    }, tabbarProps)),
    _react2.default.createElement(_DropdownDialog2.default, {
      show: show,
      dialogProps: _extends({}, dialogProps || {}, {
        maskAttribute: _extends({}, dialogProps && dialogProps.maskAttribute ? dialogProps.maskAttribute : {}, {
          onClick: onClickMask,
          style: _extends({
            top: offsetTop + 'px'
          }, dialogProps && dialogProps.maskAttribute && dialogProps.maskAttribute.style ? dialogProps.maskAttribute.style : {})
        })
      }),
      multiple: menusMultiple,
      list: menus,
      selected: selected,
      onChange: onSelected,
      menutiledProps: menutiledProps
    })
  );
});

exports.default = Dropdown;
module.exports = exports['default'];