var _excluded = ["selected", "onChange", "multiple", "list", "cancelAttribute"];

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; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

// require PrototypeArray.js
import React, { useRef, useEffect, useState, useContext, forwardRef } from 'react';
import Context from './../Context/instance.js';
import Tree from './../Tree';
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 = forwardRef(function (_ref, ref) {
  var selected = _ref.selected,
      onChange = _ref.onChange,
      _ref$multiple = _ref.multiple,
      multiple = _ref$multiple === void 0 ? false : _ref$multiple,
      list = _ref.list,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === void 0 ? {} : _ref$cancelAttribute,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  // context
  var context = useContext(Context) || {};

  var locale = context.locale || function (remark) {
    return remark || '';
  };

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


  var _useState2 = 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;
  }

  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 = _createForOfIteratorHelperLoose(selected), _step; !(_step = _iterator()).done;) {
      var item = _step.value;
      if (item.id === id) return true;
    }

    return false;
  }
  /*
   *  多选
   */


  var refTree = useRef(null);

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

  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 = _createForOfIteratorHelperLoose(multipleSelected), _step2; !(_step2 = _iterator2()).done;) {
        var item = _step2.value;
        instance.current.addSelected(item);
      }
    }
  }, [multipleSelected]); // 多选, 提取根节点共同的parentid, 为根节点(例如: 全部)的id, 默认为'-404'

  function getRootParentId(flattenTree) {
    var rootParentId = '-404';
    var root = flattenTree.getFlattenTreeRoots();

    for (var _iterator3 = _createForOfIteratorHelperLoose(root), _step3; !(_step3 = _iterator3()).done;) {
      var rootItem = _step3.value;

      if (rootItem.id && rootItem.id !== '-404') {
        rootParentId = rootItem.parentid;
        break;
      }
    }

    return rootParentId;
  } // 多选, 对id为空的根节点(例如: 全部)做根处理, 补充id、parentid、isroot


  function updateTreeRoot(flattenTree, rootParentId) {
    for (var _iterator4 = _createForOfIteratorHelperLoose(flattenTree), _step4; !(_step4 = _iterator4()).done;) {
      var item = _step4.value;

      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 = _createForOfIteratorHelperLoose(selected), _step5; !(_step5 = _iterator5()).done;) {
      var selectedItem = _step5.value;

      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 = _createForOfIteratorHelperLoose(data), _step6; !(_step6 = _iterator6()).done;) {
          var item = _step6.value;

          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 = _createForOfIteratorHelperLoose(multipleSelected), _step7; !(_step7 = _iterator7()).done;) {
        var item = _step7.value;
        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 /*#__PURE__*/React.createElement("div", _extends({
    ref: ref
  }, others, {
    className: "menutiled" + (others.className ? ' ' + others.className : '') + (multiple ? ' multiple' : ''),
    onClick: click
  }), /*#__PURE__*/React.createElement("div", {
    className: "menutiled-wrapper"
  }, !multiple && (viewGroups || []).map(function (group, groupIndex) {
    return /*#__PURE__*/React.createElement("div", {
      key: groupIndex,
      className: "" + (groupIndex ? slotSubClass : slotClass)
    }, group.map(function (option, optionIndex) {
      return /*#__PURE__*/React.createElement("div", {
        key: optionIndex,
        "data-index": optionIndex,
        "data-hierarchy": groupIndex,
        "data-id": option.id,
        className: "menutiled-tag" + (isSelected(option.id) ? ' ' + activeClass : '')
      }, /*#__PURE__*/React.createElement("p", {
        className: tagFontClass
      }, option.name), option.children && option.children.length > 0 ? /*#__PURE__*/React.createElement("i", {
        className: iconMoreClass
      }) : /*#__PURE__*/React.createElement("i", {
        className: iconSelectClass
      }));
    }));
  }), multiple && data && data.length > 0 && /*#__PURE__*/React.createElement(Tree, {
    ref: refTree,
    list: data,
    arrowAutoShow: true,
    selected: multipleSelected,
    selectedAutoClear: true,
    multiple: true,
    checkbox: true,
    onChange: changeTree
  })), /*#__PURE__*/React.createElement("div", {
    className: "menutiled-handler"
  }, /*#__PURE__*/React.createElement("span", {
    className: "menutiled-cancel",
    onClick: cancel
  }, locale('取消', 'cancel')), /*#__PURE__*/React.createElement("span", {
    className: "menutiled-submit",
    onClick: submit
  }, locale('确定', 'ok'))));
});
export default MenuTiled;