"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _reactSortablejs = require("react-sortablejs");

var _classnames = _interopRequireDefault(require("classnames"));

var _dialog = _interopRequireDefault(require("../dialog"));

var _renderItem = _interopRequireDefault(require("./render-item"));

var _bsGlobal = require("../../utils/bs-global");

var _requestApi = require("./request-api");

var _checkbox = _interopRequireDefault(require("../checkbox"));

var _toast = _interopRequireDefault(require("../toast"));

require("./index.css");

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var preCls = 'titaui-quick-entrance-dialog';
var QuickEntranceDialog = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _props$visible = props.visible,
      visible = _props$visible === void 0 ? false : _props$visible,
      handleOkQuickMenu = props.handleOkQuickMenu;

  var _useState = (0, _react.useState)(visible),
      _useState2 = _slicedToArray(_useState, 2),
      dialogVisible = _useState2[0],
      setDialogVisible = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      entrancelist = _useState4[0],
      setEntranceList = _useState4[1];

  var QuickEntranceDialogRef = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      showDialog: showDialog,
      hideDialog: hideDialog
    };
  });
  var newNavigation = (0, _bsGlobal.getBSGlobal)('newNavigation');
  var FilterNavigation = newNavigation.filter(function (item) {
    if (item.appId === 119 || item.appId === 1) {
      return;
    }

    return item;
  });
  (0, _react.useEffect)(function () {
    var quickMenu = newNavigation.find(function (item) {
      return item.appId === 1;
    });

    if (quickMenu) {
      var quickMenuChildren = quickMenu === null || quickMenu === void 0 ? void 0 : quickMenu.children;
      var quickEntranceArr = [];

      if (quickMenuChildren.length > 0) {
        quickMenuChildren.forEach(function (item) {
          quickEntranceArr.push({
            id: item.id,
            title: item.title,
            appId: item.appId
          });
        });
      }

      setEntranceList(quickMenuChildren);
    }
  }, [dialogVisible]);

  var handleOnOk = function handleOnOk() {
    var menuIdArr = [];
    entrancelist.forEach(function (item) {
      menuIdArr.push(item.id);
    });
    var menuIds = menuIdArr.join(',');
    (0, _requestApi.setHomeQuick)(menuIds).then(function (res) {
      if (res.Code === 1) {
        var newQuickMenu = getNewQuickMenu(menuIdArr);
        updateNewNavigation(newQuickMenu);
        handleOkQuickMenu && handleOkQuickMenu(newQuickMenu);
      }
    });

    if (window.titaTracker) {
      window.titaTracker('action').record({
        actionName: '快捷入口设置',
        actionGroup: '新菜单设置',
        productName: '系统菜单'
      });
    }

    hideDialog();
  };

  var updateNewNavigation = function updateNewNavigation(newQuickMenu) {
    //更新BSGlobal上的newNavigation
    var newNavigation = window.BSGlobal.newNavigation.filter(function (item) {
      if (item.code === 'quick') {
        item.children = newQuickMenu;
      }

      return item;
    });
    window.BSGlobal.newNavigation = newNavigation;
  };

  var getNewQuickMenu = function getNewQuickMenu(menuIdArr) {
    //得到新的快捷菜单数组。
    var childArr = [];
    var newQuickMenu = [];
    newNavigation.forEach(function (element) {
      if (element.children.length > 0 && element.code !== 'quick') {
        childArr = [].concat(_toConsumableArray(childArr), _toConsumableArray(element.children));
      }
    });
    menuIdArr.forEach(function (id) {
      var findInChildArrItem = childArr.find(function (item) {
        return item.id === id;
      });

      if (findInChildArrItem) {
        newQuickMenu.push(findInChildArrItem);
      }
    });
    return newQuickMenu;
  };

  var handleOnCancel = function handleOnCancel() {
    hideDialog();
  };

  var handleOnClose = function handleOnClose() {
    hideDialog();
  };

  var handleClickDelete = function handleClickDelete(id) {
    var newEntrancelist = _toConsumableArray(entrancelist);

    if (newEntrancelist.length < 2) {
      _toast["default"].Warning("请至少选择一个");

      return;
    }

    var filterNewEntranceList = newEntrancelist.filter(function (item) {
      if (item.id === id) {
        return;
      }

      return item;
    });
    setEntranceList(filterNewEntranceList);
  };

  var hideDialog = function hideDialog() {
    setDialogVisible(false);
  };

  var showDialog = function showDialog() {
    setDialogVisible(true);
  }; // 开始拖拽


  var onItemDragMove = function onItemDragMove(evt) {
    evt.stopPropagation();
    evt.dragged && evt.dragged.classList.add('drag-boder');
    return true;
  };

  var onItemDragEnd = function onItemDragEnd(evt) {
    evt.stopPropagation();
    evt.item && evt.item.classList.remove('drag-boder');
    return true;
  };

  var isCheckedById = function isCheckedById(id, title) {
    var index = entrancelist.findIndex(function (item) {
      return item.id === id;
    });

    if (index !== -1) {
      return true;
    } else {
      return false;
    }
  };

  var handleClickMenuTwoItem = function handleClickMenuTwoItem(item) {
    //点击二级菜单选项，更新已选数据
    var findItem = entrancelist.find(function (i) {
      return i.id === item.id;
    });
    var isChecked = true;

    if (findItem) {
      isChecked = false;
    }

    var newEntrancelist = _toConsumableArray(entrancelist);

    var checkedIndex = newEntrancelist.findIndex(function (i) {
      return i.id === item.id;
    });

    if (isChecked) {
      if (checkedIndex !== -1) {
        setEntranceList(newEntrancelist);
        return;
      }

      newEntrancelist.push({
        id: item.id,
        title: item.title
      });
      setEntranceList(newEntrancelist);
    } else {
      var filterNewEntrancelist = newEntrancelist.filter(function (i) {
        if (i.id === item.id) {
          return;
        }

        return i;
      });
      setEntranceList(filterNewEntrancelist);
    }
  };

  return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    wrapClassName: "".concat(preCls, "__wrap"),
    noFooterLine: true,
    visible: dialogVisible,
    onOk: handleOnOk,
    onCancel: handleOnCancel,
    onClose: handleOnClose,
    ref: QuickEntranceDialogRef
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__title")
  }, "\u8BBE\u7F6E\u5FEB\u6377\u5165\u53E3"), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content__left")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content__left-wrapper")
  }, FilterNavigation.map(function (item) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(preCls, "__content__left__item")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(preCls, "__content__left__item__menu-one")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: (0, _classnames["default"])("".concat(preCls, "__content__left__item__menu-one__icon"), "app-center__app-item-icon--".concat(item.iconName))
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(preCls, "__content__left__item__menu-one__title")
    }, item.title)), item.children.length > 0 && item.children.map(function (i) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(preCls, "__content__left__item__menu-two"),
        onClick: function onClick() {
          return handleClickMenuTwoItem(i);
        }
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(preCls, "__content__left__item__menu-two__title")
      }, i.title), /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(preCls, "__content__left__item__menu-two__checkbox")
      }, /*#__PURE__*/_react["default"].createElement(_checkbox["default"], {
        checked: function checked() {
          return isCheckedById(i.id, i.title);
        }
      })));
    }));
  }))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content__right")
  }, /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content__right-yixuan")
  }, "\u5DF2\u9009"), /*#__PURE__*/_react["default"].createElement(_reactSortablejs.ReactSortable, {
    list: entrancelist,
    setList: setEntranceList,
    animation: 200,
    delayOnTouchStart: true,
    delay: 2,
    onEnd: onItemDragEnd,
    onMove: onItemDragMove
  }, entrancelist.length > 0 && entrancelist.map(function (item) {
    return /*#__PURE__*/_react["default"].createElement(_react.Fragment, {
      key: item.id
    }, /*#__PURE__*/_react["default"].createElement(_renderItem["default"], {
      id: item.id,
      title: item.title,
      handleClickDelete: handleClickDelete
    }));
  }))))))));
});
var _default = QuickEntranceDialog;
exports["default"] = _default;