import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.scss'
import { AddressObjProps } from '../interface'
interface Props {
  value?: any
  onChange: (values) => void
  onCancel: () => void
  term?: string
  name?: string
}

interface State {
  map: any
  markersArray: Array<any> | []
  addressRes: AddressObjProps
}

export default class Index extends Component<Props, State> {
  state = {
    map: null,
    markersArray: [],
    addressRes: {
      location: [],
      address: ''
    }
  }

  componentWillMount() { }

  componentDidMount() {
    const { value } = this.props
    if (value && value.location.length) {
      this.setState({
        addressRes: value
      })
      this.buildMap(value.location[1], value.location[0])
    } else {
      this.getLocation().then((res: any) => {
        if (res) {
          this.buildMap(res[0], res[1])
        } else {
          this.buildMap()
        }
      })
    }
  }

  getLocation = () => {
    return new Promise((resolve, reject) => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          const { latitude, longitude } = position.coords
          console.log('position', position)
          resolve([latitude, longitude])
        }, (error: any) => {
          Taro.showToast({
            title: '获取位置出错，请检查定位权限设置',
            icon: 'none'
          })
          switch (error.code) {
            case error.PERMISSION_DENIED:
              console.log('定位失败,用户拒绝请求地理定位')
              break;
            case error.POSITION_UNAVAILABLE:
              console.log('定位失败,位置信息是不可用')
              break;
            case error.TIMEOUT:
              console.log('定位失败,请求获取用户位置超时')
              break;
            case error.UNKNOWN_ERROR:
              console.log('定位失败,定位系统失效')
              break;
          }
          reject()
        })
      } else {
        Taro.showToast({
          title: '获取位置出错，请检查定位权限设置',
          icon: 'none'
        })
        reject()
      }
    })
  }

  buildMap = (latitude = 39.916527, longitude = 116.397128) => {
    const { qq } = window as any
    const center = new qq.maps.LatLng(latitude, longitude);
    const map = new qq.maps.Map(document.getElementById('container'), {
      center,
      zoom: 13
    });
    //添加dom监听事件
    qq.maps.event.addDomListener(map, 'click', (event) => {
      this.addMarker(event.latLng)
    });
    this.setState({
      map
    })
    const marker = new qq.maps.Marker({
      map,
      position: center
    })
    this.setState({
      markersArray: [marker]
    })
  }

  addMarker = (location) => {
    const { map, markersArray } = this.state
    const { qq } = window as any
    const marker = new qq.maps.Marker({
      position: location,
      map
    });
    const { lat, lng } = location
    const newMarkerArray = markersArray.concat(marker)
    if (markersArray.length) {
      for (let i in (markersArray as any)) {
        markersArray[i].setMap(null);
      }
    }
    this.setState({
      markersArray: newMarkerArray
    })
    this.getAddress(lat, lng)
  }

  getAddress = (lat, lng) => {
    Taro.showLoading({
      title: '加载中...'
    })
    const _this = this
    Taro.request({
      url: `/tx/api/ws/geocoder/v1/?location=${lat},${lng}&key=RDEBZ-F5O3I-AD5GA-5675L-ATUCQ-4VBC6`,
      success: (res) => {
        // Taro.showToast({
        //   title: JSON.stringify(res)
        // })
      },
      fail: (err) => {
        Taro.showToast({
          title: '获取详细位置信息失败',
          icon: 'none'
        })
      },
      complete: (res: any) => {
        Taro.hideLoading()
        if (res.data.status === 0) {
          const { lat, lng } = res.data.result.location
          if (!res.data.result.address_reference) {
            Taro.showToast({
              title: '地址选择错误，请重试',
              icon: 'none'
            })
            return
          }
          const { address, address_reference: { landmark_l2 } } = res.data.result
          const addressInfo = landmark_l2 ? landmark_l2.title : ''
          const newAddress = `${address}${addressInfo}`
          _this.setState({
            addressRes: {
              location: [lng, lat],
              address: newAddress
            }
          })
        } else {
          Taro.showToast({
            title: '获取位置失败',
            icon: 'none'
          })
        }
      }
    })
  }

  onCancelHandler = () => {
    const { onCancel } = this.props
    onCancel()
  }

  handleClick = () => {
    const { addressRes } = this.state
    const { onChange, onCancel } = this.props
    onChange(addressRes)
    onCancel()
  }

  render() {
    const { addressRes } = this.state
    return (
      <View className='h5-map-container'>
        <View className='h5-map-view-container'>
          <View className='back-wrap' onClick={this.onCancelHandler}>
            <button className='back'>返回</button>
          </View>
          <View className='button-wrap' onClick={this.handleClick}>
            <button className='button'>确定</button>
          </View>
        </View>
        {addressRes.address && <View className='h5-address'>
          {addressRes.address}
        </View>}
        <View className='h5-map' id='container' >
        </View>
      </View>
    )
  }
}
