'use strict';

exports.__esModule = true;

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 _instance = require('./../Context/instance.js');

var _instance2 = _interopRequireDefault(_instance);

var _Tree = require('./../Tree');

var _Tree2 = _interopRequireDefault(_Tree);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // require PrototypeArray.js


var slotClass = 'menutiled-slot';
var slotSubClass = 'menutiled-slot-sub';
var tagClass = 'menutiled-tag';
var tagFontClass = 'menutiled-tag-font';
var iconMoreClass = 'menutiled-icon-more';
var iconSelectClass = 'menutiled-icon-checked';
var activeClass = 'active';

var MenuTiled = (0, _react.forwardRef)(function (_ref, ref) {
  var selected = _ref.selected,
      onChange = _ref.onChange,
      _ref$multiple = _ref.multiple,
      multiple = _ref$multiple === undefined ? false : _ref$multiple,
      list = _ref.list,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === undefined ? {} : _ref$cancelAttribute,
      others = _objectWithoutProperties(_ref, ['selected', 'onChange', 'multiple', 'list', 'cancelAttribute']);

  // context
  var context = (0, _react.useContext)(_instance2.default) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };

  var _useState = (0, _react.useState)(null),
      viewGroups = _useState[0],
      setViewGroups = _useState[1]; // 分组显示数据


  var _useState2 = (0, _react.useState)(list),
      data = _useState2[0],
      setData = _useState2[1]; // 将list转换成标准格式

  // 格式化列表数据


  function fmtList() {
    if (!list || !list.length) return [];
    var listStr = JSON.stringify(list);
    var newList = Object.clone(list);
    if (!multiple) {
      // 单选需要children
      if (listStr.indexOf('"children"') === -1) {
        return newList.deepTree();
      }
    } else if (multiple) {
      // 多选需要拉平数据, 并对根节点(id为空)做根处理
      if (listStr.indexOf('"children"') !== -1 || listStr.indexOf('"parentid"') === -1) {
        // 有children或者没有parentid, 需要拉平数据
        // 因为树只支持拉平数据, 并且必须层级分明, 所以要对id为空的根节点做根处理
        var flattenTree = newList.flattenTree();
        // 提取根节点共同的parentid, 为根节点(例如: 全部)的id
        var rootParentId = getRootParentId(flattenTree);
        // 对id为空的根节点(例如: 全部)做根处理
        updateTreeRoot(flattenTree, rootParentId);

        // 更新选中的根节点
        data = flattenTree;
        if (selected && selected.length) updateTreeSelectedRoot();
        return flattenTree;
      }
      if (listStr.indexOf('"parentid"') !== -1) {
        // 已经拉平的数据需要对id为空的数据做根处理
        // 提取根节点共同的parentid, 为根节点(例如: 全部)的id
        var _rootParentId = getRootParentId(list);
        // 对id为空的根节点(例如: 全部)做根处理
        updateTreeRoot(list, _rootParentId);

        // 更新选中的根节点
        if (selected && selected.length) updateTreeSelectedRoot();
        return list;
      }
    }
    return list;
  }
  (0, _react.useEffect)(function () {
    data = fmtList(); // eslint-disable-line
    setData(data);
    if (!multiple) setViewGroups([data]);
  }, [list]);

  /*
   *  单选
   */
  // 点击选项
  function click(e) {
    if (e.target.classList.contains(tagClass)) {
      // 点击项
      // 选中点击行
      // const row = Number(e.target.getAttribute('data-index') || 0);
      var id = e.target.getAttribute('data-id');
      var item = data.getDeepTreeNode(id);
      // 删除后面的层级
      var hierarchy = Number(e.target.getAttribute('data-hierarchy') || 0);
      var newViewGroups = Object.clone(viewGroups);
      newViewGroups.splice(hierarchy + 1);
      // 如果有子级, 添加子级
      if (item.children && item.children.length) {
        // 添加子级
        if (!newViewGroups[hierarchy + 1]) newViewGroups[hierarchy + 1] = [];
        newViewGroups[hierarchy + 1] = item.children;
      } else if (onChange) {
        // 叶子节点点击触发
        onChange(e, item.name, [item], data);
      }
      setViewGroups(newViewGroups);
    }
  }

  // 判断是否选中
  function isSelected(id) {
    if (!Array.isArray(selected) || !selected || !selected.length) return false;
    for (var _iterator = selected, _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;

      if (item.id === id) return true;
    }
    return false;
  }

  /*
   *  多选
   */
  var refTree = (0, _react.useRef)(null);

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

  (0, _react.useEffect)(function () {
    if (!multipleSelected || !multipleSelected.length) {
      return;
    }
    if (refTree && refTree.current && refTree.current.instance && refTree.current.instance.current) {
      var instance = refTree.current.instance;
      instance.current.removeAllSelected();
      for (var _iterator2 = multipleSelected, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
        var _ref3;

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

        var item = _ref3;

        instance.current.addSelected(item);
      }
    }
  }, [multipleSelected]);
  // 多选, 提取根节点共同的parentid, 为根节点(例如: 全部)的id
  function getRootParentId(flattenTree) {
    var rootParentId = '-1';
    var root = flattenTree.getFlattenTreeRoots();
    for (var _iterator3 = root, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
      var _ref4;

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

      var rootItem = _ref4;

      if (rootItem.id && rootItem.id !== '-1') {
        rootParentId = rootItem.parentid;
        break;
      }
    }
    return rootParentId;
  }
  // 多选, 对id为空的根节点(例如: 全部)做根处理, 补充id、parentid、isroot
  function updateTreeRoot(flattenTree, rootParentId) {
    for (var _iterator4 = flattenTree, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
      var _ref5;

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

      var item = _ref5;

      if (!item.id) {
        item.parentid = '-2';
        item.id = rootParentId;
        item.isroot = '1';
        if (rootParentId) delete item.isLeaf;
      }
    }
  }
  // 多选时, list数据被转换: id为空的根节点被补充id和parentid=-2还有isroot=1, 所以selected也需要处理, 才能让树选中
  function updateTreeSelectedRoot() {
    for (var _iterator5 = selected, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
      var _ref6;

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

      var selectedItem = _ref6;

      if (!selectedItem.id) {
        // 根节点处理
        var rootParentId = getRootParentId(data);
        selectedItem.parentid = '-2';
        selectedItem.id = rootParentId;
        selectedItem.isroot = '1';
      }
      if (selectedItem.id && !selectedItem.parentid) {
        // 非根节点补充parentid
        for (var _iterator6 = data, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
          var _ref7;

          if (_isArray6) {
            if (_i6 >= _iterator6.length) break;
            _ref7 = _iterator6[_i6++];
          } else {
            _i6 = _iterator6.next();
            if (_i6.done) break;
            _ref7 = _i6.value;
          }

          var item = _ref7;

          if (selectedItem.id === item.id) {
            selectedItem.parentid = item.parentid;
          }
        }
      }
    }
    setMultipleSelected(selected);
  }
  // 多选, 点击选中节点
  function changeTree(e, value, options) {
    setMultipleSelected(options);
  }
  // 多选, 点击确定
  function submit(e) {
    var val = [];
    if (multipleSelected && multipleSelected.length) {
      for (var _iterator7 = multipleSelected, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
        var _ref8;

        if (_isArray7) {
          if (_i7 >= _iterator7.length) break;
          _ref8 = _iterator7[_i7++];
        } else {
          _i7 = _iterator7.next();
          if (_i7.done) break;
          _ref8 = _i7.value;
        }

        var item = _ref8;

        val.push(item.name);
      }
    }
    if (onChange) onChange(e, val.join(','), multipleSelected, data);
  }
  function cancel(e) {
    if (selected && selected.length) {
      updateTreeSelectedRoot();
    }
    if (cancelAttribute && cancelAttribute.onClick) cancelAttribute.onClick(e);
  }
  return _react2.default.createElement(
    'div',
    _extends({ ref: ref }, others, { className: 'menutiled' + (others.className ? ' ' + others.className : '') + (multiple ? ' multiple' : ''), onClick: click }),
    _react2.default.createElement(
      'div',
      { className: 'menutiled-wrapper' },
      !multiple && (viewGroups || []).map(function (group, groupIndex) {
        return _react2.default.createElement(
          'div',
          { key: groupIndex, className: '' + (groupIndex ? slotSubClass : slotClass) },
          group.map(function (option, optionIndex) {
            return _react2.default.createElement(
              'div',
              { key: optionIndex, 'data-index': optionIndex, 'data-hierarchy': groupIndex, 'data-id': option.id, className: 'menutiled-tag' + (isSelected(option.id) ? ' ' + activeClass : '') },
              _react2.default.createElement(
                'p',
                { className: tagFontClass },
                option.name
              ),
              option.children && option.children.length > 0 ? _react2.default.createElement('i', { className: iconMoreClass }) : _react2.default.createElement('i', { className: iconSelectClass })
            );
          })
        );
      }),
      multiple && data && data.length > 0 && _react2.default.createElement(_Tree2.default, {
        ref: refTree,
        list: data,
        arrowAutoShow: true,
        selected: multipleSelected,
        selectedAutoClear: true,
        multiple: true,
        checkbox: true,
        onChange: changeTree
      })
    ),
    _react2.default.createElement(
      'div',
      { className: 'menutiled-handler' },
      _react2.default.createElement(
        'span',
        { className: 'menutiled-cancel', onClick: cancel },
        locale('取消', 'cancel')
      ),
      _react2.default.createElement(
        'span',
        { className: 'menutiled-submit', onClick: submit },
        locale('确定', 'ok')
      )
    )
  );
});

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