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

var _Dialog2 = _interopRequireDefault(_Dialog);

var _MenuTiled = require('./../MenuTiled');

var _MenuTiled2 = _interopRequireDefault(_MenuTiled);

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)([]),
      menus = _useState4[0],
      setMenus = _useState4[1];

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

  var _useState6 = (0, _react.useState)(false),
      show = _useState6[0],
      setShow = _useState6[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({
        id: item.id,
        name: item.name,
        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) {
    setSelected([tabs[index]]);
    setMenus(list[index].data);
    if (activeIndex >= 0) {
      // 隐藏弹框
      setActiveIndex(-1);
      setShow(false);
    } else {
      // 显示弹框
      setActiveIndex(index);
      setShow(true);
    }
  }
  function onClickMask() {
    setActiveIndex(-1);
    setShow(false);
  }
  // 构建新数据
  function buildList(newTabs) {
    var newList = Object.clone(list);
    newTabs.forEach(function (item, index) {
      newList[index].id = item.id;
      newList[index].name = listRoot && listRoot[index] && listRoot[index].id === item.id ? listRoot[index].name : item.name;
    });
    return newList;
  }
  function onSelected(e, value, selected, data) {
    if (!selected || !selected.length) return;
    var item = selected[0];
    if (item.children && item.children.length > 0) return;
    var newTabs = Object.clone(tabs);
    // 如果选中的标题是全部,则显示原始标题,例如:点击分类,选择全部,则应当显示分类
    if (item.id === list[activeIndex].id) {
      newTabs[activeIndex].id = list[activeIndex].id;
      newTabs[activeIndex].name = list[activeIndex].name;
      // 设置选中的标题显示在tabbar上
    } else {
      newTabs[activeIndex].id = item.id;
      newTabs[activeIndex].name = item.name;
    }
    setActiveIndex(-1);
    setShow(false);
    // 触发onChange事件
    if (onChange) onChange(e, buildList(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(
      _Dialog2.default,
      _extends({
        maskAttribute: { onClick: onClickMask, style: { top: offsetTop + 'px' } },
        animation: 'slideDown',
        style: { width: '100%' },
        show: show
      }, dialogProps),
      _react2.default.createElement(_MenuTiled2.default, _extends({
        list: menus,
        selected: selected,
        onChange: onSelected
      }, menutiledProps))
    )
  );
});

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