import Taro, { Component } from '@tarojs/taro'
import { View, Map } from '@tarojs/components'
import { arrToObj } from '@utils'
var QQMapWX = require('@js/qqmap-wx-jssdk.js')
var qqmapsdk
import './indexDtlMap.scss'

class Index extends Component {
  onShareAppMessage() {
    const { id, name } = this.$router.params
    return {
      title: `${name}-楼盘详情-洪楼Plus`,
      path: `/pagesHouse/indexDtl?id=${id}`,
    }
  }
  onShareTimeline () {
    return {
      title: '让买房，更省心！',
    }
  }

  constructor (props) {
    super(props)
    const {id: curId} = this.$router.params
    this.state = {
      curId,
      curObj: {},
      aroundArr: [],
      posIndex: 0,
    }
  }

  config = {
    navigationBarTitleText: '周边配套',
    // navigationStyle: 'custom'
  }

  componentWillMount () {
    const { name } = this.$router.params
    Taro.setNavigationBarTitle({
      title: name + '-周边配套' || '周边配套'
    })
    this.getDtl()
    qqmapsdk = new QQMapWX({
      key: '5WFBZ-LCZ3J-D5AFM-KNUUL-BTT46-45BWB'
    })
  }

  getDtl = () => {
    const { curId } = this.state
    Taro.api.house.admestatedetail({id: curId}).then(obj => {
      const curObj = obj || {}
      this.setState({
        curObj,
        aroundArr: []
      }, () => {
        Taro.api.house.apiestateperipherydata({estate_id: curId}).then(eObj => {
          if (eObj.periphery) {
            this.setState({
              aroundArr: JSON.parse(eObj.periphery)
            })
          } else {
            let aroundTags = ['地铁', '公交', '小学', '中学', '医院']
            this.getAroundInfo(aroundTags)
          }
        })
        // let aroundTags = ['餐饮', '购物', '公园', '银行']
      })
    })
  }

  getAroundInfo (aroundTags) {
    const { curObj, curId } = this.state
    let aroundInfoTemp = []
    aroundTags.forEach((keyword, keywordIndex) => {
      aroundInfoTemp.push(
        new Promise((resolve, reject) => {
          let keywordParams = {
            keyword,
            address_format: 'short',
            page_size: '10',
            location: {
              latitude: curObj.latitude,
              longitude: curObj.longitude
            },
            success: function (res) {
              const cData = res.data || []
              qqmapsdk.calculateDistance({
                mode: keywordIndex === 0 || keywordIndex === 1 ? 'walking' : 'driving',
                from: {
                  latitude: curObj.latitude,
                  longitude: curObj.longitude
                },
                to: cData,
                success: (distance) => {
                  if (distance.status === 0) {
                    const elements = distance.result.elements || []
                    let list = []
                    elements.map((eItem, eI) => {
                      let num = 2000
                      if (keywordIndex === 0) num = 1000
                      if (keywordIndex === 1) num = 800
                      if (keywordIndex === 4) num = 3000
                      if (eItem.distance < num) {
                        list.push({
                          ...cData[eI],
                          distance: eItem.distance,
                          duration: eItem.duration,
                        })
                      }
                    })
                    return resolve({keyword, list})
                  }
                },
                fail: function (res) {
                  return reject(res)
                }
              })
            },
            fail: function (res) {
              return reject(res)
            }
          }
          // if (keywordIndex === 2) keywordParams.filter = 'category=小学,中学'
          qqmapsdk.search(keywordParams)    
        })
      )
    })
    Promise.all(aroundInfoTemp).then(res => {
      const curRes = res || []
      let aroundArr = []
      curRes.map(item =>{
        if (item.list.length > 0) {
          aroundArr.push({...item})
        }
      })
      this.setState({
        aroundArr
      })
      Taro.api.house.apiestateperipheryadd({
        estate_id: curId,
        periphery: JSON.stringify(aroundArr)
      }).then(eObj => {
        // console.log(eObj)
      })
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  renderOptionsInfo () {
    const icon = require('@img/images/icon_ex_house.png')
    const { aroundArr } = this.state
    return (
      <View className="scoped-footer">
        {
          aroundArr.map((one, oneIndex) => {
            return (
            <View key={oneIndex} className="sf-op" onClick={this.posSelect.bind(this, oneIndex)}>
              <Image src={icon} className="img"/>
              <View className="t">{one.keyword}</View>
            </View>
            )
          })
        }
      </View>
    )
  }
  posSelect (posIndex) {
    this.setState({
      posIndex
    })
  }

  renderPos () {
    const { curObj, aroundArr } = this.state
    let markers = []
    const { posIndex } = this.state
    let newAround = aroundArr.length > 0 && aroundArr[posIndex].list || []
    // console.log(aroundArr)
    newAround.forEach(item => {
      markers.push({
        longitude: String(item.location.lng),
        latitude: String(item.location.lat),
        iconPath: 'http://icon.honglounews.com/icon_ex1.png',
        width: '20px',
        height: '20px',
        zIndex: 999,
        label: {
          content: item.title,
          color: '#333',
          fontSize: 12,
          // // anchorX: -(0.5 * (5 * 24))/2,
          anchorY: -50,
          textAlign: 'center',
          bgColor: '#fff',
          padding: 5,
          borderRadius: 5,
          borderColor: '#f2f2f2',
          borderWidth: 1,
        }
      })
    })
    markers.push({
      longitude: curObj.longitude,
      latitude: curObj.latitude,
      iconPath: 'http://icon.honglounews.com/icon_ex2.png',
      width: '30px',
      height: '30px',
      zIndex: 9999,
      label: {
        content: curObj.estate_name,
        color: '#333',
        fontSize: 12,
        // // anchorX: -(0.5 * (5 * 24))/2,
        anchorY: -56,
        textAlign: 'center',
        bgColor: '#fff',
        padding: 5,
        borderRadius: 5,
        borderColor: '#f2f2f2',
        borderWidth: 1,
      }
    })
    return (
      <View className="scoped-list-map">
        <Map
          className="m"
          longitude={curObj.longitude}
          latitude={curObj.latitude}
          scale="14"
          markers={markers}
          show-compass={true}
        />
      </View>
    )
  }

  render () {
    const { aroundArr } = this.state
    return (
      <View className="l-box">
        {
          aroundArr.length > 0
          &&
          this.renderPos()
        }
        {this.renderOptionsInfo()}
      </View>
    )
  }
}

export default Index
