"use strict";

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

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

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

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

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

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

var _classnames = _interopRequireDefault(require("classnames"));

var _lodash = require("lodash");

var _axios = _interopRequireDefault(require("axios"));

var _rxjs = require("rxjs");

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

var _title = _interopRequireDefault(require("../title"));

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 REQUEST_INTERVAL = 1000 * 60 * 20;

/**
 * 天气查询
 * 文档：https://lbs.amap.com/api/webservice/guide/api/weatherinfo
 *
 * @param {obj} params
 * @returns
 */
function weatherInfo(params) {
  return (0, _axios["default"])({
    method: 'GET',
    url: '//restapi.amap.com/v3/weather/weatherInfo',
    params: params
  });
}
/**
 * 高德天气组件
 *
 * @class Weather
 * @extends {PureComponent<IProps, IState>}
 */


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

  function Weather(props) {
    var _this;

    _this = _PureComponent.call(this, props) || this;
    _this.subject$ = void 0;
    _this.timeout = void 0;
    _this.state = {
      lives: null
    };
    _this.subject$ = new _rxjs.Subject();

    _this.subject$.asObservable().pipe((0, _operators.switchMap)(function () {
      var prevLives = _this.state.lives;
      var _this$props = _this.props,
          params = _this$props.params,
          onChange = _this$props.onChange;
      var req = (0, _extends2["default"])({}, params);
      delete req.interval;

      var request = _this.getWeather((0, _extends2["default"])({}, req)).then(function (res) {
        var lives = res ? res[0] : {};

        _this.setState({
          lives: lives
        }, function () {
          if (onChange && !(0, _lodash.isEqual)(prevLives, lives)) onChange(lives);
          _this.timeout = setTimeout(function () {
            _this.subject$.next();
          }, params.interval || REQUEST_INTERVAL);
        });
      })["catch"](function (err) {
        console.log(err);
        setTimeout(function () {
          _this.subject$.next();
        }, params.interval || REQUEST_INTERVAL);
      });

      return (0, _rxjs.from)(request);
    })).subscribe();

    return _this;
  }

  var _proto = Weather.prototype;

  _proto.getWeather = /*#__PURE__*/function () {
    var _getWeather = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) {
      var response;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return weatherInfo(params);

            case 2:
              response = _context.sent;

              if (!(!response || !response.data.status)) {
                _context.next = 5;
                break;
              }

              return _context.abrupt("return", null);

            case 5:
              return _context.abrupt("return", response.data.lives || response.data.forecast);

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

    function getWeather(_x) {
      return _getWeather.apply(this, arguments);
    }

    return getWeather;
  }();

  _proto.componentDidMount = function componentDidMount() {
    this.subject$.next();
  };

  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    var params = this.props.params;

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

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

  _proto.render = function render() {
    var _this$props2 = this.props,
        className = _this$props2.className,
        textOptions = _this$props2.textOptions;
    var lives = this.state.lives;

    var _ref = lives || {},
        weather = _ref.weather,
        temperature = _ref.temperature;

    return /*#__PURE__*/_react["default"].createElement(_title["default"], (0, _extends2["default"])({}, textOptions || {}, {
      className: (0, _classnames["default"])(className, (0, _lodash.get)(textOptions, 'className'))
    }), "\u5929\u6C14\u72B6\u51B5\uFF1A", weather || '-', "\xA0\xA0\u5F53\u524D\u6C14\u6E29\uFF1A", temperature || '-', "\u2103");
  };

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


Weather.defaultProps = {
  className: null,
  params: {},
  onChange: function onChange() {},
  textOptions: {
    textStyle: {
      fontWeight: 400
    }
  }
};
var _default = Weather;
exports["default"] = _default;