import _regeneratorRuntime from "@babel/runtime/regenerator";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import React, { useEffect } from "react";
import { fetch } from '@fishx/rest';
import { connect } from "../../../redux";
import { set, get } from "dot-prop-immutable";
import { i18n } from '@fishx/i18n';
import { message } from '@whalecloud/fdx';
import { getActiveElement } from "../../../selectors";
import CommonCodeDrawer from "./CommonCodeDrawer";
var exampleUrl = {
  url: "/api/manage/recipientList.json"
};
var defaultRemote = {
  url: 'https://mock.iwhalecloud.com/mock/2880/api/options',
  method: 'GET',
  params: {}
};

var defaultDependencyRemote = _objectSpread(_objectSpread({}, defaultRemote), {}, {
  url: 'https://mock.iwhalecloud.com/mock/2880/api/options?value=${value}'
});

var OptionSettings = function OptionSettings(props) {
  var updateElement = props.updateElement,
      element = props.element,
      sourceKey = props.sourceKey;
  var isDependency = sourceKey.indexOf('dependency') > -1;
  var _element$data = element.data;
  _element$data = _element$data === void 0 ? {} : _element$data;
  var _element$data$formIte = _element$data.formItemSettings,
      formItemSettings = _element$data$formIte === void 0 ? {} : _element$data$formIte;
  var _formItemSettings$rem = formItemSettings.remote,
      remote = _formItemSettings$rem === void 0 ? exampleUrl : _formItemSettings$rem;
  var autoInitialize = formItemSettings.autoInitialize,
      remoteMode = formItemSettings.remoteMode;

  if (isDependency) {
    var _source$2;

    var _element$data$formSet = element.data.formSettings;
    _element$data$formSet = _element$data$formSet === void 0 ? {} : _element$data$formSet;
    var _element$data$formSet2 = _element$data$formSet.dependency;
    _element$data$formSet2 = _element$data$formSet2 === void 0 ? {} : _element$data$formSet2;
    var _element$data$formSet3 = _element$data$formSet2.source,
        source = _element$data$formSet3 === void 0 ? {} : _element$data$formSet3;
    var key = sourceKey.substring(sourceKey.lastIndexOf('.') + 1);
    var _source$ = source["".concat(key, "_metadata")];
    _source$ = _source$ === void 0 ? {} : _source$;

    var _source$$remote = _source$.remote,
        _remote = _source$$remote === void 0 ? false : _source$$remote;

    var ifRemote = (_source$2 = source["".concat(key, "_metadata")]) === null || _source$2 === void 0 ? void 0 : _source$2.remoteMode;

    if (ifRemote) {
      var _source$3;

      var remoteParam = (_source$3 = source["".concat(key, "_metadata")]) === null || _source$3 === void 0 ? void 0 : _source$3.remote;
      remote = remoteParam || defaultDependencyRemote;
    }

    if (!remote.url) {
      remote = defaultDependencyRemote;
    }
  }

  var valueKey = sourceKey;
  var valueKeyMetaData = !isDependency ? sourceKey : "".concat(sourceKey, "_metadata");
  useEffect(function () {
    var code;

    if (isDependency) {
      code = get(element, "".concat(valueKeyMetaData, ".remote")) || defaultDependencyRemote; // code = get(element, sourceKey) || defaultDependencyRemote;
    } else {
      code = get(element, 'data.formItemSettings.remote');
    }

    onCreate(code);
  }, [remoteMode]);

  var handleOtherRelates = function handleOtherRelates(element, isDependency) {
    if (isDependency) {
      var _element$data$formSet4 = element.data.formSettings.dependency.source,
          relates = _element$data$formSet4.relates,
          inputs = _element$data$formSet4.inputs,
          output = _element$data$formSet4.output,
          defaultOutput = _element$data$formSet4.defaultOutput;
      var _key = 'data.formSettings.dependency.source';
      var obj = {
        relates: relates,
        inputs: inputs
      };
      Object.keys(obj).forEach(function (mapKey) {
        if (!obj[mapKey]) {
          element = set(element, "".concat(_key, ".").concat(mapKey), []);
        }
      });
    }

    return element;
  };

  var onCreate = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(code) {
      var _code$url, url, _code$method, method, _code$params, params, newElement, _yield$fetch, data, optionsValue, _newElement, _newElement2;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _code$url = code.url, url = _code$url === void 0 ? '' : _code$url, _code$method = code.method, method = _code$method === void 0 ? 'GET' : _code$method, _code$params = code.params, params = _code$params === void 0 ? {} : _code$params;

              if (!autoInitialize) {
                _context.next = 23;
                break;
              }

              if (!(isDependency && url.indexOf('${value}') > -1)) {
                _context.next = 10;
                break;
              }

              // 远程数据源包含动态传参，需要根据目标值动态请求数据,直接将请求url 参数传入，交给组件处理
              newElement = set(element, valueKey, code);
              newElement = set(newElement, "".concat(valueKeyMetaData, ".remote"), code);
              newElement = handleOtherRelates(newElement, isDependency);
              updateElement({
                element: newElement
              });
              message.success(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_SUCCESS'));
              _context.next = 21;
              break;

            case 10:
              _context.prev = 10;
              _context.next = 13;
              return fetch(url, {
                method: method,
                data: _objectSpread({}, params)
              });

            case 13:
              _yield$fetch = _context.sent;
              data = _yield$fetch.data;

              if (data) {
                optionsValue = _toConsumableArray(data);
                _newElement = set(element, isDependency ? valueKey : "".concat(valueKey, ".options"), optionsValue);
                _newElement = set(_newElement, "".concat(valueKeyMetaData, ".remote"), code);
                updateElement({
                  element: _newElement
                });
                message.success(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_SUCCESS'));
              } else {
                message.error(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_FAIL'));
              }

              _context.next = 21;
              break;

            case 18:
              _context.prev = 18;
              _context.t0 = _context["catch"](10);
              message.error(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_FAIL'));

            case 21:
              _context.next = 28;
              break;

            case 23:
              _newElement2 = set(element, "".concat(valueKeyMetaData, ".remote"), code);
              isDependency && (_newElement2 = set(_newElement2, "".concat(valueKeyMetaData, ".remoteMode"), true));
              _newElement2 = handleOtherRelates(_newElement2, isDependency);
              updateElement({
                element: _newElement2
              });
              message.warn(i18n('PAGEBUIDER_MSG_OPTIONS_REMOTE_WARN'));

            case 28:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[10, 18]]);
    }));

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

  var CodeDrawerProps = {
    value: remote ? JSON.stringify(remote, null, '\t') : JSON.stringify({}, null, '\t'),
    onClose: onCreate,
    title: "".concat(i18n('PAGEBUIDER_TITLE_REMOTE'), "(JSON)"),
    buttonText: i18n('PAGEBUIDER_TITLE_REMOTE')
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    style: {
      textAlign: 'center'
    }
  }, /*#__PURE__*/React.createElement(CommonCodeDrawer, CodeDrawerProps)));
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state) {
  return {
    element: getActiveElement(state)
  };
}, mapDispatchToProps)(OptionSettings);
//# sourceMappingURL=RemoteOptionSettings.js.map