"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports["default"] = void 0;

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));

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

var _rxjs = require("rxjs");

var _lodash = require("lodash");

var _operators = require("rxjs/operators");

var _Utils = require("../Utils");

var _excluded = ["component", "children", "filters", "query", "variables"];

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

var Query = /*#__PURE__*/function (_PureComponent) {
  (0, _inheritsLoose2["default"])(Query, _PureComponent);

  function Query(props) {
    var _this;

    _this = _PureComponent.call(this, props) || this;
    _this.subject$ = void 0;
    _this.timeout = void 0;

    _this.refetch = function (nextVariables) {
      if (nextVariables === void 0) {
        nextVariables = {};
      }

      var savedVariables = _this.state.savedVariables;
      var flag = _this.props.flag;
      var mergedVariables = (0, _extends2["default"])({}, savedVariables, nextVariables);
      if (flag) _this.subject$.next(mergedVariables);
    };

    _this.state = {
      data: null,
      loading: false,
      error: null,
      savedVariables: props.variables
    };
    _this.subject$ = new _rxjs.Subject();

    _this.subject$.asObservable().pipe((0, _operators.switchMap)(function (variables) {
      // console.log('variables: ', variables);
      var _this$props = _this.props,
          query = _this$props.query,
          onCompleted = _this$props.onCompleted,
          onError = _this$props.onError,
          interval = _this$props.interval,
          flag = _this$props.flag;

      var cb = function cb() {
        if (interval && flag) {
          _this.timeout = setTimeout(function () {
            _this.subject$.next(variables);
          }, interval);
        }
      };

      _this.setState({
        savedVariables: variables,
        loading: true
      });

      var handleSuccess = function handleSuccess(data, callback) {
        if (callback === void 0) {
          callback = function callback() {};
        }

        if ((0, _lodash.isFunction)(onCompleted)) {
          onCompleted(data);
        }

        _this.setState({
          data: data,
          error: null,
          loading: false
        }, callback);
      };

      var handleError = function handleError(err, callback) {
        if (callback === void 0) {
          callback = function callback() {};
        }

        if ((0, _lodash.isFunction)(onError)) {
          onError(err);
        }

        _this.setState({
          error: err,
          loading: false
        }, callback);
      };

      var request = query((0, _extends2["default"])({}, variables)).then(function (res) {
        handleSuccess(res, cb);
      })["catch"](function (err) {
        handleError(err, cb);
      });
      return (0, _rxjs.from)(request);
    })).subscribe();

    return _this;
  }

  var _proto = Query.prototype;

  _proto.componentDidMount = function componentDidMount() {
    var _this$props2 = this.props,
        _this$props2$variable = _this$props2.variables,
        variables = _this$props2$variable === void 0 ? {} : _this$props2$variable,
        children = _this$props2.children,
        flag = _this$props2.flag; // let tmp = [], components: any[] = [];
    // const childrenTmp = isFunction(children) ? children() : children;
    // if (isArray(childrenTmp)) {
    //   // @ts-ignore
    //   tmp = childrenTmp.filter((child) => isValidElement(child)).map(({ type, props }, index) => {
    //     const { bizId } = get(props, 'requestParams', {});
    //     const { category, displayName } = type;
    //     const uuid = `${category}-${displayName}-${index}`;
    //     type.uuid = uuid;
    //     return {
    //       uuid: index, // uuidv4(),
    //       bizId,
    //       componentIds: [uuid],
    //     };
    //   });
    // } else if (isValidElement(childrenTmp)) {
    //   const { type, props } = childrenTmp;
    //   const { bizId } = get(props, 'requestParams', {});
    //   // @ts-ignore
    //   const { category, displayName } = type;
    //   const uuid = `${category}-${displayName}-${uuidv4()}`;
    //   // @ts-ignore
    //   type.uuid = uuid;
    //   tmp = [{
    //     uuid: uuidv4(),
    //     bizId,
    //     componentIds: [uuid],
    //   }];
    // }
    // for (let i = 0; i < tmp.length; i++) {
    //   const el = tmp[i];
    //   const target = components.find((item) => item.bizId === el.bizId);
    //   if (!target) {
    //     components.push({
    //       ...el,
    //       componentIds: el.componentIds
    //     });
    //   } else {
    //     target.componentIds.push(...el.componentIds)
    //   }
    // }

    if (flag) this.subject$.next(variables); // this.subject$.next({
    //   requestParamJsonStr: JSON.stringify(variables),
    //   components,
    // });
  };

  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    var _this$props3 = this.props,
        variables = _this$props3.variables,
        flag = _this$props3.flag;

    if (!(0, _lodash.isEqual)(prevProps.variables, variables) && flag) {
      this.subject$.next(variables);
    }
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    clearTimeout(this.timeout);
    this.subject$.unsubscribe();
  };

  _proto.render = function render() {
    var _this$props4 = this.props,
        Component = _this$props4.component,
        children = _this$props4.children,
        filters = _this$props4.filters,
        query = _this$props4.query,
        variables = _this$props4.variables,
        others = (0, _objectWithoutPropertiesLoose2["default"])(_this$props4, _excluded);
    var _this$state = this.state,
        data = _this$state.data,
        loading = _this$state.loading,
        error = _this$state.error,
        savedVariables = _this$state.savedVariables;
    var filteredData = (0, _lodash.isArray)(filters) ? (0, _Utils.Compose)(filters)(data) : data;
    var tmp = (0, _lodash.isFunction)(children) ? children({
      data: filteredData,
      loading: loading,
      error: error,
      variables: savedVariables,
      refetch: this.refetch
    }) : children; // console.log('response: ', filteredData);

    if ((0, _lodash.isArray)(tmp)) {
      tmp = _react.Children.map(tmp, function (child, i) {
        // console.log(i, child);
        var props = child.props; // const { uuid } = type;

        var viewProps = (0, _lodash.get)(props, 'requestParams.props', []); // const params = get(filteredData, key, {});

        var params = {};
        viewProps.forEach(function (_ref) {
          var key = _ref.key,
              value = _ref.value;
          params[key] = value ? (0, _lodash.get)(filteredData, value) : filteredData;
        }); // console.log('params', params);

        return /*#__PURE__*/(0, _react.isValidElement)(child) ? /*#__PURE__*/(0, _react.cloneElement)(child, params) : child;
      });
    } else if ( /*#__PURE__*/(0, _react.isValidElement)(tmp)) {
      var _tmp = tmp,
          props = _tmp.props;
      var viewProps = (0, _lodash.get)(props, 'requestParams.props', []); // const params = get(filteredData, key, {});

      var params = {};
      viewProps.forEach(function (_ref2) {
        var key = _ref2.key,
            value = _ref2.value;
        params[key] = value ? (0, _lodash.get)(filteredData, value) : filteredData;
      }); // console.log('params', params);

      tmp = /*#__PURE__*/(0, _react.cloneElement)(tmp, params);
    }

    if (Component === null) {
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, tmp);
    }

    return /*#__PURE__*/_react["default"].createElement(Component, others, /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, tmp));
  };

  return Query;
}(_react.PureComponent); // @ts-ignore


Query.defaultProps = {
  component: null,
  variables: {},
  flag: true
};
var _default = Query;
exports["default"] = _default;