import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getOnlineWeather } from './../../../services/commonServices';

class Weather extends Component {

  constructor(props) {
    super(props);
    this.state = {
      weatherInfo: ''
    };
  }

  componentDidMount() {
    this.getWeatherInfo();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.address !== prevProps.address){
      this.getWeatherInfo();
    }
  }

  getWeatherInfo = () => {
    const { address } = this.props;
    getOnlineWeather(address).then((res) => {
      this.parseData(res.data);
    });
  }

  parseData = (data = {}) => {
    const { forecast = [] } = data;
    const current = forecast[0];
    if (current){
      const fengli = current.fengli.replace('<![CDATA\[', '').replace(']]>', '');
      const high = current.high.replace('高温', '').trim();
      const low = current.low.replace('低温', '').trim();
      const weatherInfo = `${current.type} ${low}~${high} ${current.fengxiang} ${fengli}`;
      this.setState({
        weatherInfo
      });
    }
  }

  render() {
    const { weatherInfo } = this.state;
    const { address } = this.props;
    return (
      <div className="header-weather">
        <span className="adress">{address}</span>
        <span>{weatherInfo}</span>
      </div>
    );
  }
}

Weather.propTypes = {
  address: PropTypes.string
};

export default Weather;
