"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 = void 0;

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

var _antd = require("antd");

var _uppercamelcase = _interopRequireDefault(require("uppercamelcase"));

var _UIApiContext = _interopRequireDefault(require("../UIApiContext"));

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

var _LogPanel = _interopRequireDefault(require("../LogPanel"));

var _ResultPanel = _interopRequireDefault(require("./ResultPanel"));

var _AddTemplateForm = _interopRequireDefault(require("./AddTemplateForm"));

var _AddBlockFormForUI = _interopRequireDefault(require("./AddBlockFormForUI"));

var _AddBlockForm = _interopRequireDefault(require("./AddBlockForm"));

var _BlockItem = require("../BlockList/BlockItem");

var _util = require("../util");

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

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

/**
 * 安装区块
 * @param api
 * @param params
 */
var addBlock = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(api, params) {
    var _ref2, _ref2$data, info;

    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return api.callRemote({
              type: 'org.umi.block.add',
              payload: params
            });

          case 2:
            _ref2 = _context.sent;
            _ref2$data = _ref2.data;
            info = _ref2$data === void 0 ? {
              message: ''
            } : _ref2$data;
            return _context.abrupt("return", info.message);

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

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

var cancelAddBlockTask = function cancelAddBlockTask(api) {
  return api.callRemote({
    type: 'org.umi.block.cancel'
  });
};

var Adder = function Adder(props) {
  var visible = props.visible,
      blockTarget = props.blockTarget,
      onAddBlockChange = props.onAddBlockChange,
      onHideModal = props.onHideModal,
      index = props.index,
      _props$block = props.block,
      block = _props$block === void 0 ? {
    url: ''
  } : _props$block,
      blockType = props.blockType;

  var _useContext = (0, _react.useContext)(_UIApiContext.default),
      api = _useContext.api;

  var callRemote = api.callRemote,
      intl = api.intl,
      _analyze = api._analyze;
  var gtag = _analyze.gtag;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      taskLoading = _useState2[0],
      setTaskLoading = _useState2[1]; // 防止重复提交


  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      fromCheck = _useState4[0],
      setFromCheck = _useState4[1];

  var _Form$useForm = _antd.Form.useForm(),
      _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
      form = _Form$useForm2[0]; // 展示哪个界面
  // log 日志  form 表单


  var _useState5 = (0, _react.useState)('form'),
      _useState6 = _slicedToArray(_useState5, 2),
      addStatus = _useState6[0],
      setAddStatus = _useState6[1]; // 预览界面需要消费的日志


  var _useState7 = (0, _react.useState)(undefined),
      _useState8 = _slicedToArray(_useState7, 2),
      succeededBlock = _useState8[0],
      setSucceededBlock = _useState8[1];

  var _useCallData = (0, _useCallData2.default)(function () {
    return callRemote({
      type: '@@project/getNpmClients'
    });
  }, [], {
    defaultData: ['npm']
  }),
      _useCallData$data = _useCallData.data,
      npmClients = _useCallData$data === void 0 ? [] : _useCallData$data;

  (0, _react.useEffect)(function () {
    if (api.detectNpmClients) {
      api.detectNpmClients().then(function (clients) {
        form.setFieldsValue({
          npmClient: clients.find(function (c) {
            return npmClients.includes(c);
          })
        });
      });
    }
  }, [npmClients]);
  (0, _react.useEffect)(function () {
    /**
     * 成功之后清理状态
     */
    api.listenRemote({
      type: 'org.umi.block.add-blocks-success',
      onMessage: function onMessage(msg) {
        setTaskLoading(false);
        onAddBlockChange(undefined); // 如果标签页不激活，不处理它

        if (document.visibilityState !== 'hidden') {
          // 设置预览界面
          setAddStatus('result');
          setSucceededBlock(msg.data);
        } else {
          setAddStatus('form');
        }

        gtag('event', 'add-blocks-success', {
          event_category: 'block',
          event_label: msg.data && msg.data.path ? msg.data.path : ''
        });
      }
    });
    /**
     * 失败之后清理状态
     * 应该保留日志，所以进行页面的切换
     */

    api.listenRemote({
      type: 'org.umi.block.add-blocks-fail',
      onMessage: function onMessage(msg) {
        setTaskLoading(false);
        onAddBlockChange(undefined); // 如果标签页不激活，不处理它

        if (document.visibilityState !== 'hidden') {
          _antd.message.error(intl({
            id: 'org.umi.ui.blocks.adder.failed'
          }));
        }

        gtag('event', 'add-blocks-fail', {
          event_category: 'block',
          event_label: msg.data && msg.data.path ? msg.data.path : ''
        });
      }
    });
    /**
     * 获取上次的安装的区块 url
     */

    callRemote({
      type: 'org.umi.block.get-adding-block-url'
    }).then(function (_ref3) {
      var data = _ref3.data;

      if (data) {
        // 如果有安装未完成的区块，设置显示页面为log
        // 并打开loading
        setAddStatus('log');
        setTaskLoading(true);
      }
    }); // detect language

    if (api.detectLanguage) {
      api.detectLanguage().then(function (language) {
        form.setFieldsValue({
          js: language === 'JavaScript'
        });
      });
    }
  }, []);
  (0, _react.useEffect)(function () {
    if (!block || !block.url) {
      return;
    } // 生成 defaultName


    var defaultName = block.url.split('/').pop();
    var initPath = blockType !== 'template' ? '/' : "/".concat(defaultName);

    var resetInitialValues = /*#__PURE__*/function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
        var noExitVar, initialValues;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return (0, _util.getNoExitVar)({
                  name: (0, _uppercamelcase.default)(defaultName),
                  path: blockTarget || initPath,
                  api: api,
                  need: !!blockTarget
                });

              case 2:
                noExitVar = _context2.sent;
                _context2.next = 5;
                return (0, _util.getNoExitPath)({
                  path: blockTarget || initPath,
                  api: api,
                  need: blockType === 'template'
                });

              case 5:
                _context2.t0 = _context2.sent;
                _context2.next = 8;
                return (0, _util.getNoExitRoute)({
                  path: "/".concat(defaultName.toLocaleLowerCase()),
                  api: api,
                  need: blockType === 'template'
                });

              case 8:
                _context2.t1 = _context2.sent;
                _context2.t2 = noExitVar;
                initialValues = {
                  path: _context2.t0,
                  routePath: _context2.t1,
                  name: _context2.t2
                };
                form.setFieldsValue(initialValues);

              case 12:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      return function resetInitialValues() {
        return _ref4.apply(this, arguments);
      };
    }();

    resetInitialValues();
  }, [block ? block.url : '', blockTarget || '']);
  (0, _react.useEffect)(function () {
    if (index !== null && index !== undefined) {
      form.setFieldsValue({
        index: index
      });
    }
  }, [index]);

  if (!block || !block.url) {
    return null;
  }
  /**
   * 计算初始值
   */


  var initialValues = {
    js: false,
    uni18n: localStorage.getItem('umi-ui-block-removeLocale') === 'true',
    npmClient: 'npm'
  };

  var renderOkText = function renderOkText(status, loading) {
    if (status === 'log' && !loading) {
      return intl({
        id: 'org.umi.ui.blocks.adder.stop'
      });
    }

    if (status === 'log') {
      return intl({
        id: 'org.umi.ui.blocks.adder.stop'
      });
    }

    return intl({
      id: 'org.umi.ui.blocks.adder.ok'
    });
  };

  return /*#__PURE__*/_react.default.createElement(_antd.Modal, {
    title: /*#__PURE__*/_react.default.createElement("div", {
      style: {
        display: 'flex'
      }
    }, intl({
      id: "org.umi.ui.blocks.adder.title.".concat(blockType)
    })),
    closable: true,
    visible: visible,
    destroyOnClose: true,
    onCancel: function onCancel() {
      onHideModal();

      if (!taskLoading) {
        setAddStatus('form');
      }
    },
    footer: addStatus === 'result' ? null : undefined,
    confirmLoading: fromCheck,
    bodyStyle: {
      height: '60vh',
      overflow: 'auto',
      transition: '.3s'
    },
    centered: true,
    okText: renderOkText(addStatus, taskLoading),
    onOk: function onOk() {
      if (addStatus === 'log' && !taskLoading) {
        onHideModal();
        setAddStatus('form');
        setSucceededBlock(undefined);
        return;
      }

      if (addStatus === 'log') {
        _antd.Modal.confirm({
          title: intl({
            id: 'org.umi.ui.blocks.adder.stop.title'
          }),
          content: intl({
            id: 'org.umi.ui.blocks.adder.stop.content'
          }),
          okType: 'danger',
          okText: intl({
            id: 'org.umi.ui.blocks.adder.stop.okText'
          }),
          cancelText: intl({
            id: 'org.umi.ui.blocks.adder.stop.cancelText'
          }),
          onOk: function () {
            var _onOk = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
              return regeneratorRuntime.wrap(function _callee3$(_context3) {
                while (1) {
                  switch (_context3.prev = _context3.next) {
                    case 0:
                      _context3.next = 2;
                      return cancelAddBlockTask(api);

                    case 2:
                      setTaskLoading(false);
                      onAddBlockChange(undefined);

                    case 4:
                    case "end":
                      return _context3.stop();
                  }
                }
              }, _callee3);
            }));

            function onOk() {
              return _onOk.apply(this, arguments);
            }

            return onOk;
          }()
        });

        return;
      } // loading 状态更新


      setTaskLoading(true);
      setFromCheck(true);
      form.validateFields().then( /*#__PURE__*/function () {
        var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(values) {
          var params;
          return regeneratorRuntime.wrap(function _callee4$(_context4) {
            while (1) {
              switch (_context4.prev = _context4.next) {
                case 0:
                  setAddStatus('log');
                  _context4.prev = 1;
                  _context4.t0 = _objectSpread;
                  _context4.t1 = {};
                  _context4.t2 = values;
                  _context4.t3 = block.url;
                  _context4.next = 8;
                  return (0, _BlockItem.getPathFromFilename)(api, values.path);

                case 8:
                  _context4.t4 = _context4.sent;
                  _context4.t5 = blockType === 'template' ? values.routePath : undefined;
                  _context4.t6 = blockType === 'template';
                  _context4.t7 = values.index && values.index.startsWith('l-') ? values.index : parseInt(values.index || '0', 10);
                  _context4.t8 = blockType === 'template' ? block.name : values.name;
                  _context4.t9 = {
                    url: _context4.t3,
                    path: _context4.t4,
                    routePath: _context4.t5,
                    page: _context4.t6,
                    index: _context4.t7,
                    name: _context4.t8
                  };
                  params = (0, _context4.t0)(_context4.t1, _context4.t2, _context4.t9);
                  addBlock(api, params);
                  localStorage.setItem('umi-ui-block-removeLocale', values.uni18n);
                  onAddBlockChange(block);
                  gtag('event', 'install-block', {
                    event_category: 'block',
                    event_label: params && params.path ? params.path : ''
                  });
                  _context4.next = 24;
                  break;

                case 21:
                  _context4.prev = 21;
                  _context4.t10 = _context4["catch"](1);

                  _antd.message.error(_context4.t10.message);

                case 24:
                case "end":
                  return _context4.stop();
              }
            }
          }, _callee4, null, [[1, 21]]);
        }));

        return function (_x3) {
          return _ref5.apply(this, arguments);
        };
      }()).catch(function () {
        return setTaskLoading(false);
      }).finally(function () {
        return setFromCheck(false);
      });
    }
  }, /*#__PURE__*/_react.default.createElement(_antd.Form, {
    hideRequiredMark: true,
    initialValues: initialValues,
    layout: "vertical",
    form: form,
    style: {
      display: addStatus !== 'form' && 'none'
    }
  }, blockType === 'template' && /*#__PURE__*/_react.default.createElement(_AddTemplateForm.default, {
    visible: visible,
    blockType: blockType
  }), blockType === 'block' && !api.isMini() && /*#__PURE__*/_react.default.createElement(_AddBlockForm.default, {
    form: form,
    visible: visible
  }), blockType === 'block' && api.isMini() && /*#__PURE__*/_react.default.createElement(_AddBlockFormForUI.default, {
    form: form,
    blockTarget: blockTarget
  }), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    name: "js",
    label: intl({
      id: 'org.umi.ui.blocks.adder.js'
    }),
    valuePropName: "checked",
    style: {
      display: 'none'
    }
  }, /*#__PURE__*/_react.default.createElement(_antd.Switch, {
    size: "small"
  })), blockType === 'template' && /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    name: "uni18n",
    label: intl({
      id: 'org.umi.ui.blocks.adder.uni18n'
    }),
    valuePropName: "checked"
  }, /*#__PURE__*/_react.default.createElement(_antd.Switch, {
    size: "small"
  })), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    name: "npmClient",
    label: intl({
      id: 'org.umi.ui.blocks.adder.npmClient'
    }),
    rules: [{
      required: true,
      message: intl({
        id: 'org.umi.ui.blocks.adder.npmClient.required'
      })
    }]
  }, /*#__PURE__*/_react.default.createElement(_antd.Select, null, npmClients.map(function (client) {
    return /*#__PURE__*/_react.default.createElement(_antd.Select.Option, {
      key: client,
      value: client
    }, client);
  }))), /*#__PURE__*/_react.default.createElement(_antd.Form.Item, {
    name: "index"
  }, /*#__PURE__*/_react.default.createElement("input", {
    type: "hidden"
  }))), addStatus === 'log' && /*#__PURE__*/_react.default.createElement(_LogPanel.default, {
    loading: taskLoading
  }), addStatus === 'result' && succeededBlock && /*#__PURE__*/_react.default.createElement(_ResultPanel.default, {
    onFinish: function onFinish() {
      onHideModal();
      setAddStatus('form');
      setSucceededBlock(undefined);
      api.hideMini();
    },
    name: succeededBlock.name || block.name,
    url: succeededBlock.previewUrl
  }));
};

var _default = Adder;
exports.default = _default;