import React from 'react';
import PropTypes from 'prop-types';
import { Search, FormBuilder, Connect } from 'amos-framework';
import imageStatic from '@gm/graphmod-assets';
import SelectModal from './SelectModal';

const BasicForm = FormBuilder.BasicForm;
const enhanceForm = Connect.enhanceForm;

/**
 * 输入地址，或者从地图选择地址
 * @class InputPoi
 * @extends {BasicForm}
 */
@enhanceForm
class InputPoi extends BasicForm {

  constructor(props) {
    super(props);
    this.state = {
      posVisible: false,
      longitude: '',
      latitude: '',
      value: props.value || ''
    };
  }

  componentDidMount() {
    this.getValue(this.props.value || this.props.defaultValue || '');
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.value !== prevProps.value) {
      // this.setState({
      //   value: nextProps.value
      // });
      this.getValue(this.props.value || '');
    }
  }

  getValue = (value = '') => {
    const list = value.split('@address@');
    const otherValue = list[1];
    let data = {};
    if (otherValue) {
      data = JSON.parse(otherValue);
    }
    this.setState({
      value: list[0],
      ...data || {}
    });
  }

  onChange = () => {
    const { onChange, url } = this.props;
    const { longitude, latitude, value } = this.state;
    const str = JSON.stringify({ longitude, latitude });
    if (onChange) {
      this.props.onChange(url ? `${value || ''}@address@${str}` : value);
    }
  }

  toggle = () => {
    this.setState(prevState => ({
      posVisible: !prevState.posVisible
    }));
  };

  cancel = () => {
    this.setState({
      posVisible: false
    });
  }

  handleChange = (e, value) => {
    this.setState({
      value
    }, this.onChange);
  }

  handLanLonChange = (data) => {
    this.setState({
      ...data
    }, this.onChange);
  }

  render() {
    const cls = this.getClassNames('param-inputpoi');
    const { value, posVisible, longitude, latitude } = this.state;
    const { url } = this.props;
    return (
      <div className={cls}>
        <Search
          {...this.props}
          icon={longitude && latitude ? imageStatic.common.poiChoice : imageStatic.common.poi}
          onIconClick={this.toggle}
          value={value}
          onChange={this.handleChange}
        />
        <SelectModal longitude={longitude} latitude={latitude} onChange={this.handLanLonChange} visible={posVisible} url={url} onCancel={this.cancel} />
      </div>
    );
  }
}

InputPoi.propTypes = {};

export default InputPoi;
