"use strict";

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

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

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

var _antd = require("antd");

var _icons = require("@ant-design/icons");

var _qs = require("qs");

var _icon = require("./icon");

var _BlockList = _interopRequireDefault(require("./BlockList"));

var _GlobalSearch = _interopRequireDefault(require("./GlobalSearch"));

var _useCallData2 = _interopRequireDefault(require("./hooks/useCallData"));

var _BlocksViewerModule = _interopRequireDefault(require("./BlocksViewer.module.less"));

var _Adder = _interopRequireDefault(require("./Adder"));

var _AssetsMenu = _interopRequireDefault(require("./AssetsMenu"));

var _model = require("./model");

var _Container = _interopRequireDefault(require("./Container"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _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 _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(n); 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) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * get substr from url
 */
var getQueryConfig = function getQueryConfig() {
  return (0, _qs.parse)(window.location.search.substr(1));
};
/**
 *  更新 search
 * @param params
 */


var updateUrlQuery = function updateUrlQuery(params) {
  var defaultParas = getQueryConfig();
  window.history.pushState({}, '', "?".concat((0, _qs.stringify)(_objectSpread({}, defaultParas, {}, params))));
};

var clearCache = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(api) {
    var hide, _ref2, data;

    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            hide = _antd.message.loading('缓存清理中！');
            _context.next = 4;
            return api.callRemote({
              type: 'org.umi.block.clear'
            });

          case 4:
            _ref2 = _context.sent;
            data = _ref2.data;
            // 用户记忆的参数
            localStorage.removeItem('umi-ui-block-removeLocale');
            hide(); // 等动画播放完

            setTimeout(function () {
              _antd.message.success(data);
            }, 30);
            _context.next = 14;
            break;

          case 11:
            _context.prev = 11;
            _context.t0 = _context["catch"](0);

            _antd.message.error(_context.t0.message);

          case 14:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 11]]);
  }));

  return function clearCache(_x) {
    return _ref.apply(this, arguments);
  };
}();

var openUmiBlocks = function openUmiBlocks() {
  window.open('https://github.com/umijs/umi-blocks');
};
/**
 * 从 id 的 dom 滚动到 target 的 dom
 * @param id
 * @param target
 */


var scrollToById = function scrollToById(id, target) {
  var dom = document.getElementById(id);
  var targetDom = document.getElementById(target);

  if (dom && targetDom) {
    var axis = dom.getBoundingClientRect();
    targetDom.scrollTop = axis.top + axis.height / 2;
  }
};

exports.scrollToById = scrollToById;

/**
 * 渲染 数据源选择器
 * @param param0
 */
var renderActiveResourceTag = function renderActiveResourceTag(_ref3) {
  var type = _ref3.type,
      _ref3$matchedResource = _ref3.matchedResources,
      matchedResources = _ref3$matchedResource === void 0 ? [] : _ref3$matchedResource,
      _ref3$current = _ref3.current,
      current = _ref3$current === void 0 ? {
    id: ''
  } : _ref3$current,
      setActiveResource = _ref3.setActiveResource;

  if (matchedResources.length > 1) {
    return /*#__PURE__*/_react.default.createElement(_antd.Radio.Group, {
      value: current.id,
      size: "small",
      onChange: function onChange(e) {
        var resource = matchedResources.find(function (r) {
          return r.id === e.target.value;
        });
        setActiveResource(resource);
        updateUrlQuery({
          type: type,
          resource: resource.id
        });
      }
    }, matchedResources.map(function (r) {
      return /*#__PURE__*/_react.default.createElement(_antd.Radio.Button, {
        key: r.id,
        value: r.id
      }, r.name);
    }));
  }

  if (matchedResources.length === 1) {
    return /*#__PURE__*/_react.default.createElement("h3", {
      style: {
        marginTop: 8
      }
    }, matchedResources[0].name);
  }

  return null;
};

var BlocksViewer = function BlocksViewer(props) {
  var dispatch = props.dispatch,
      block = props.block,
      fetchDataLoading = props.loading;

  var _Container$useContain = _Container.default.useContainer(),
      api = _Container$useContain.api,
      type = _Container$useContain.type,
      setType = _Container$useContain.setType,
      activeResource = _Container$useContain.activeResource,
      setActiveResource = _Container$useContain.setActiveResource;

  var callRemote = api.callRemote,
      intl = api.intl;
  /**
   * 是不是umi
   */

  var isMini = api.isMini();
  /**
   * 用到的各种状态
   */

  var _useState = (0, _react.useState)(null),
      _useState2 = _slicedToArray(_useState, 2),
      willAddBlock = _useState2[0],
      setWillAddBlock = _useState2[1];

  var _useState3 = (0, _react.useState)(null),
      _useState4 = _slicedToArray(_useState3, 2),
      addingBlock = _useState4[0],
      setAddBlock = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      addModalVisible = _useState6[0],
      setAddModalVisible = _useState6[1];

  var _useState7 = (0, _react.useState)(null),
      _useState8 = _slicedToArray(_useState7, 2),
      blockParams = _useState8[0],
      setBlockParams = _useState8[1];

  var _useState9 = (0, _react.useState)(''),
      _useState10 = _slicedToArray(_useState9, 2),
      searchValue = _useState10[0],
      setSearchValue = _useState10[1];

  var _useState11 = (0, _react.useState)(''),
      _useState12 = _slicedToArray(_useState11, 2),
      selectedTag = _useState12[0],
      setSelectedTag = _useState12[1];
  /**
   * 获取 query 中的设置
   */


  (0, _react.useLayoutEffect)(function () {
    // 更新一下url，让他们同步一下
    if (type) {
      updateUrlQuery({
        type: type
      });
    }
  }, []); // 获取数据源

  var _useCallData = (0, _useCallData2.default)(function () {
    return callRemote({
      type: 'org.umi.block.resource'
    });
  }, [], {
    defaultData: []
  }),
      resources = _useCallData.data; // 当前的数据源列表


  var current = (0, _react.useMemo)(function () {
    return activeResource || resources.filter(function (item) {
      return item.blockType === type;
    })[0];
  }, [resources, activeResource, type]); // 计算选中的区块

  var blocks = (0, _react.useMemo)(function () {
    return current && block.blockData[current.id] ? block.blockData[current.id] : [];
  }, [block, current]); // 初始化 block dva model data

  (0, _react.useEffect)(function () {
    if (current && current.id) {
      dispatch({
        type: "".concat(_model.namespace, "/fetch"),
        payload: {
          resourceId: current.id
        }
      });
    }
  }, [current]);
  (0, _react.useEffect)(function () {
    /**
     * 获取上次的安装的区块 url
     * 成功之后会被清除
     */
    callRemote({
      type: 'org.umi.block.get-adding-block-url'
    }).then(function (_ref4) {
      var data = _ref4.data;

      if (data) {
        setAddBlock({
          url: data
        });
      }
    });
  }, []); // 如果区块不在屏幕范围内，滚动过去

  (0, _react.useEffect)(function () {
    if (willAddBlock) {
      // 我把每个 item 都加了一个 id，就是他的 url
      scrollToById(willAddBlock.url, 'block-list-view');
    }
  }, [fetchDataLoading]); // 区块右上角的区域 三个按钮

  (0, _react.useEffect)(function () {
    var buttonPadding = isMini ? '0 4px' : '0 8px';

    var handleSearchChange = function handleSearchChange(v) {
      setSearchValue(v.toLocaleLowerCase());
    };

    if (api.setActionPanel) {
      api.setActionPanel(function () {
        return [/*#__PURE__*/_react.default.createElement(_GlobalSearch.default, {
          key: "global-search",
          onChange: handleSearchChange,
          api: api
        }), /*#__PURE__*/_react.default.createElement(_antd.Tooltip, {
          title: intl({
            id: 'org.umi.ui.blocks.actions.reload'
          }),
          getPopupContainer: function getPopupContainer(node) {
            return node ? node.parentNode : document.body;
          },
          placement: "bottom"
        }, /*#__PURE__*/_react.default.createElement(_antd.Button, {
          size: isMini ? 'small' : 'default',
          key: "reload",
          style: {
            padding: buttonPadding
          },
          onClick: function onClick() {
            dispatch({
              type: "".concat(_model.namespace, "/fetch"),
              payload: {
                reload: true
              }
            });
          }
        }, /*#__PURE__*/_react.default.createElement(_icons.ReloadOutlined, null))), /*#__PURE__*/_react.default.createElement(_antd.Tooltip, {
          title: intl({
            id: 'org.umi.ui.blocks.actions.clear'
          }),
          getPopupContainer: function getPopupContainer(node) {
            return node ? node.parentNode : document.body;
          },
          placement: "bottom"
        }, /*#__PURE__*/_react.default.createElement(_antd.Button, {
          size: isMini ? 'small' : 'default',
          key: "clear",
          onClick: function onClick() {
            return clearCache(api);
          },
          style: {
            padding: buttonPadding
          }
        }, /*#__PURE__*/_react.default.createElement(_icon.Clear, null))), /*#__PURE__*/_react.default.createElement(_antd.Tooltip, {
          title: intl({
            id: 'org.umi.ui.blocks.actions.submit'
          }),
          getPopupContainer: function getPopupContainer(node) {
            return node ? node.parentNode : document.body;
          },
          placement: "bottom"
        }, /*#__PURE__*/_react.default.createElement(_antd.Button, {
          size: isMini ? 'small' : 'default',
          key: "clear",
          onClick: function onClick() {
            return openUmiBlocks();
          },
          style: {
            padding: buttonPadding
          }
        }, /*#__PURE__*/_react.default.createElement(_icons.PlusOutlined, null)))];
      });
    }
  }, []);
  var matchedResources = resources.filter(function (r) {
    return r.blockType === type;
  });
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
    className: _BlocksViewerModule.default.wrapper
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: _BlocksViewerModule.default.side
  }, /*#__PURE__*/_react.default.createElement(_AssetsMenu.default, {
    type: type,
    matchedResources: matchedResources,
    setActiveResource: setActiveResource,
    updateUrlQuery: updateUrlQuery,
    setSelectedTag: setSelectedTag,
    selectedTag: selectedTag,
    current: current,
    blocks: blocks,
    loading: fetchDataLoading
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: _BlocksViewerModule.default.main
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(_BlocksViewerModule.default.container, " ").concat(isMini && _BlocksViewerModule.default.min),
    id: "block-list-view"
  }, current ? /*#__PURE__*/_react.default.createElement("div", {
    className: _BlocksViewerModule.default.blockList
  }, matchedResources.length > 0 ? /*#__PURE__*/_react.default.createElement(_BlockList.default, {
    type: type,
    keyword: searchValue,
    addingBlock: willAddBlock || addingBlock,
    list: blocks,
    setSelectedTag: setSelectedTag,
    selectedTag: selectedTag,
    onShowModal: function onShowModal(currentBlock, option) {
      setAddModalVisible(true);
      setWillAddBlock(currentBlock);
      setBlockParams(option);
    },
    loading: fetchDataLoading
  }) : /*#__PURE__*/_react.default.createElement("div", null, "\u6CA1\u6709\u627E\u5230\u6570\u636E\u6E90")) : /*#__PURE__*/_react.default.createElement("div", {
    className: _BlocksViewerModule.default.loading
  }, /*#__PURE__*/_react.default.createElement(_antd.Spin, null))))), /*#__PURE__*/_react.default.createElement(_Adder.default, _extends({
    block: willAddBlock,
    blockType: type
  }, blockParams, {
    visible: addModalVisible,
    onAddBlockChange: function onAddBlockChange(addBlock) {
      return setAddBlock(addBlock);
    },
    onHideModal: function onHideModal() {
      setAddModalVisible(false);
      setWillAddBlock(undefined);
      setBlockParams(undefined);
    }
  })));
};

var _default = BlocksViewer;
exports.default = _default;