import React, { Component } from 'react';
import { connect } from 'react-redux';
import DocumentTitle from 'react-document-title';
import wx from 'weixin-js-sdk';
import { appBrowser } from '../../../../utils/helper';

@connect(({ register }) => ({ register }))
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      flag: false,
      latitude: null,
      longitude: null,
    };
  }
  componentDidMount = () => {
    const this_ = this;
    if (appBrowser() === 'wechat') {
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          const { latitude, longitude } = res;
          console.log(latitude, longitude, '=======================');
          this_.setState({
            flag: true,
            latitude,
            longitude,
          });
        },
        fail: function(res) {
          console.log(res, '==================');
          this_.setState({
            flag: true,
          });
        },
      });
    } else {
      this_.setState({
        flag: true,
      });
    }
    window.addEventListener('message', this.selectLocation, false);
  };
  componentWillUnmount = () => {
    window.removeEventListener('message', this.selectLocation, false);
  };
  selectLocation = event => {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    var loc = event.data;
    if (loc && loc.module === 'locationPicker') {
      //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
      console.log('location', loc);
      this.props.dispatch({
        type: 'register/geocoder',
        payload: {
          location: loc.latlng,
          poiname: loc.poiname,
        },
      });
    }
  };
  render() {
    const { flag, latitude, longitude } = this.state;
    if (flag) {
      return (
        <DocumentTitle title="地址选择">
          <iframe
            title="地址选择"
            style={{ position: 'absolute' }}
            id="mapPage"
            width="100%"
            height="100%"
            framebborder={0}
            src={`https://apis.map.qq.com/tools/locpicker?search=1&type=1&policy=1&key=457BZ-TES6V-JS7P2-UJQAQ-IJSSO-RIFBA&referer=CABApp${
              latitude ? '&coordtype=1&coord=' + latitude + ',' + longitude : ''
            }`}
          ></iframe>
        </DocumentTitle>
      );
    } else {
      return <DocumentTitle title="地址选择"></DocumentTitle>;
    }
  }
}

export default Index;
