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

require("antd/es/card/style");

var _card = _interopRequireDefault(require("antd/es/card"));

require("antd/es/switch/style");

var _switch = _interopRequireDefault(require("antd/es/switch"));

require("antd/es/notification/style");

var _notification2 = _interopRequireDefault(require("antd/es/notification"));

require("antd/es/tooltip/style");

var _tooltip = _interopRequireDefault(require("antd/es/tooltip"));

require("antd/es/button/style");

var _button = _interopRequireDefault(require("antd/es/button"));

require("antd/es/avatar/style");

var _avatar = _interopRequireDefault(require("antd/es/avatar"));

require("antd/es/anchor/style");

var _anchor = _interopRequireDefault(require("antd/es/anchor"));

require("antd/es/layout/style");

var _layout = _interopRequireDefault(require("antd/es/layout"));

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

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

var _lodash = require("lodash");

var _ajv = _interopRequireDefault(require("ajv"));

var _ui = require("@api7-dashboard/ui");

var _PluginDrawer = _interopRequireDefault(require("./PluginDrawer"));

var _service = require("./service");

var _transformer = require("./transformer");

var _data = require("./data");

var _CodeMirrorDrawer = _interopRequireDefault(require("./CodeMirrorDrawer"));

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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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

var PanelSectionStyle = {
  display: 'grid',
  gridTemplateColumns: 'repeat(3, 33.333333%)',
  gridRowGap: 15,
  gridColumnGap: 10,
  width: 'calc(100% - 20px)'
};
var Sider = _layout.default.Sider,
    Content = _layout.default.Content;

var PluginPageApp = function PluginPageApp(_ref) {
  var _ref$initialData = _ref.initialData,
      initialData = _ref$initialData === void 0 ? {} : _ref$initialData,
      readonly = _ref.readonly,
      _ref$onChange = _ref.onChange,
      _onChange = _ref$onChange === void 0 ? function () {} : _ref$onChange;

  var _useState = (0, _react.useState)(),
      _useState2 = _slicedToArray(_useState, 2),
      pluginName = _useState2[0],
      setPluginName = _useState2[1];

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

  var _useState5 = (0, _react.useState)([]),
      _useState6 = _slicedToArray(_useState5, 2),
      allPlugins = _useState6[0],
      setAllPlugins = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = _slicedToArray(_useState7, 2),
      codeMirrorCodes = _useState8[0],
      setCodeMirrorCodes = _useState8[1];

  (0, _react.useEffect)(function () {
    (0, _service.getList)(initialData).then(setAllPlugins);
  }, [initialData]);
  var ajv = new _ajv.default();
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("style", null, "\n        .ant-avatar > img {\n          object-fit: contain;\n        }\n        .ant-avatar {\n          background-color: transparent;\n        }\n        .ant-avatar.ant-avatar-icon {\n          font-size: 32px;\n        }\n      "), /*#__PURE__*/_react.default.createElement(_layout.default, null, /*#__PURE__*/_react.default.createElement(Sider, {
    theme: "light"
  }, /*#__PURE__*/_react.default.createElement(_anchor.default, {
    offsetTop: 150
  }, allPlugins.map(function (plugins) {
    var category = plugins[0].category;
    return /*#__PURE__*/_react.default.createElement(_anchor.default.Link, {
      href: "#plugin-category-".concat(category),
      title: category,
      key: category
    });
  }))), /*#__PURE__*/_react.default.createElement(Content, {
    style: {
      padding: '0 10px',
      backgroundColor: '#fff',
      minHeight: 1400
    }
  }, allPlugins.map(function (plugins) {
    var category = plugins[0].category;
    return /*#__PURE__*/_react.default.createElement(_ui.PanelSection, {
      title: category,
      key: category,
      style: PanelSectionStyle,
      id: "plugin-category-".concat(category)
    }, plugins.map(function (_ref2) {
      var _PLUGIN_MAPPER_SOURCE;

      var name = _ref2.name,
          enabled = _ref2.enabled,
          avatar = _ref2.avatar;
      return /*#__PURE__*/_react.default.createElement(_card.default, {
        key: name,
        title: [avatar && /*#__PURE__*/_react.default.createElement(_avatar.default, {
          icon: avatar,
          className: "plugin-avatar",
          style: {
            marginRight: 5
          }
        }), /*#__PURE__*/_react.default.createElement("a", {
          href: "https://github.com/apache/incubator-apisix/blob/master/doc/plugins/".concat(name, ".md"),
          style: {
            color: 'inherit'
          },
          target: "_blank"
        }, name)],
        style: {
          height: 66
        },
        extra: [/*#__PURE__*/_react.default.createElement(_tooltip.default, {
          title: "View Raw",
          key: "plugin-card-".concat(name, "-extra-tooltip")
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          shape: "circle",
          icon: /*#__PURE__*/_react.default.createElement(_icons.EyeFilled, null),
          size: "middle",
          onClick: function onClick() {
            setCodeMirrorCodes(initialData[name]);
          }
        })), /*#__PURE__*/_react.default.createElement(_tooltip.default, {
          title: "Setting",
          key: "plugin-card-".concat(name, "-extra-tooltip-2")
        }, /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: (_PLUGIN_MAPPER_SOURCE = _data.PLUGIN_MAPPER_SOURCE[name]) === null || _PLUGIN_MAPPER_SOURCE === void 0 ? void 0 : _PLUGIN_MAPPER_SOURCE.noConfiguration,
          shape: "circle",
          icon: /*#__PURE__*/_react.default.createElement(_icons.SettingFilled, null),
          style: {
            marginRight: 10,
            marginLeft: 10
          },
          size: "middle",
          onClick: function onClick() {
            (0, _service.fetchPluginSchema)(name).then(function (schemaData) {
              setSchema(schemaData);
              setTimeout(function () {
                setPluginName(name);
              }, 300);
            });
          }
        })), /*#__PURE__*/_react.default.createElement(_switch.default, {
          defaultChecked: enabled,
          disabled: readonly,
          onChange: function onChange(isChecked) {
            // NOTE: 当前生命周期为：若关闭插件，则移除数据状态；再启用时，该插件一定是没有状态的。
            if (isChecked) {
              var data = initialData[name] || {};
              (0, _service.fetchPluginSchema)(name).then(function (schemaData) {
                var validate = ajv.validate(schemaData, data);

                if (validate) {
                  _onChange(_objectSpread(_objectSpread({}, initialData), {}, _defineProperty({}, name, data)));
                } else {
                  _notification2.default.warning({
                    message: "\u8BF7\u914D\u7F6E\u63D2\u4EF6 ".concat(name)
                  });

                  setSchema(schemaData);
                  setTimeout(function () {
                    setPluginName(name);
                  }, 300);
                }
              });
            } else {
              _onChange((0, _lodash.omit)(_objectSpread({}, initialData), [name]));
            }
          },
          key: Math.random().toString(36).substring(7)
        })]
      });
    }));
  }))), /*#__PURE__*/_react.default.createElement(_PluginDrawer.default, {
    name: pluginName,
    initialData: pluginName ? (0, _transformer.transformPlugin)(pluginName, initialData[pluginName], 'response') : {},
    readonly: readonly,
    schema: schema,
    onClose: function onClose() {
      setPluginName(undefined);
    },
    onFinish: function onFinish(value) {
      if (!pluginName) {
        return;
      }

      _onChange(_objectSpread(_objectSpread({}, initialData), {}, _defineProperty({}, pluginName, (0, _transformer.transformPlugin)(pluginName, value, 'request'))));

      setPluginName(undefined);
    }
  }), /*#__PURE__*/_react.default.createElement(_CodeMirrorDrawer.default, {
    visiable: Boolean(codeMirrorCodes),
    data: codeMirrorCodes || {},
    onClose: function onClose() {
      return setCodeMirrorCodes(undefined);
    }
  }));
};

var _default = PluginPageApp;
exports.default = _default;