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

class Index extends Component {
  onShareAppMessage() {
    const { id, name } = this.$router.params
    return {
      title: `${name}-的周边配套`,
      path: `/pagesHouse/indexDtlAround?id=${id}&name=${name}`,
    }
  }
  onShareTimeline () {
    return {
      title: '让买房，更省心！',
    }
  }

  constructor (props) {
    super(props)
    const {id: curId} = this.$router.params
    this.state = {
      curId,
      curObj: {},
      aroundArr: [],
      posIndex: 0,
      isPosMoreShow: true,
      markers: [],
      markerLabelIndex: -1,
      markersNameArr: ['地铁', '公交', '公园', '医院', '购物']
    }
  }

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

  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, markersNameArr } = 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)
            }, () => {
              this.navChange(0)
            })
          } else {
            let aroundTags = markersNameArr
            this.getAroundInfo(aroundTags)
          }
        })
        // let aroundTags = ['餐饮', '购物', '公园', '银行']
      })
    })
  }


  renderTop () {
    const { name } = this.$router.params
    const bg = require('@img/images/bg_house.jpg')
    return (
      <View className="scoped-bg-top">
        <View className="sbt-wrap" onClick={this.urlDtlLink.bind(this)}>
          <View className="t">{name}</View>
          <Image src={bg} className="bg"></Image>
        </View>
      </View>
    )
  }
  urlDtlLink () {
    const { id } = this.$router.params
    Taro.navigateTo({url: '/pagesHouse/indexDtl?id=' + id})
  }




  getMarker () {
    let markers = []
    const { posIndex, aroundArr, curObj, markerLabelIndex } = this.state
    let newAround = aroundArr.length > 0 ? aroundArr[posIndex].list : []
    markers.push({
      longitude: curObj.longitude,
      latitude: curObj.latitude,
      iconPath: 'http://icon.honglounews.com/g_map_pos.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,
      }
    })
    newAround.forEach((item, curIndex) => {
      let iconPath = 'http://icon.honglounews.com/icon_ex2.png'
      if (posIndex === 0) iconPath = 'http://icon.honglounews.com/g_map_0.png'
      if (posIndex === 1) iconPath = 'http://icon.honglounews.com/g_map_1.png'
      if (posIndex === 2) iconPath = 'http://icon.honglounews.com/g_map_2.png'
      if (posIndex === 3) iconPath = 'http://icon.honglounews.com/g_map_3.png'
      if (posIndex === 4) iconPath = 'http://icon.honglounews.com/g_map_4.png'
      if (posIndex === 5) iconPath = 'http://icon.honglounews.com/g_map_5.png'
      let obj = {
        longitude: String(item.location.lng),
        latitude: String(item.location.lat),
        iconPath,
        width: '28px',
        height: '28px',
        zIndex: 999,
      }
      if (curIndex === markerLabelIndex)
      obj.label = {
        content: item.title,
        color: '#333',
        fontSize: 12,
        anchorX: -(0.5 * (5 * 28))/2,
        anchorY: -56,
        textAlign: 'center',
        bgColor: '#fff',
        padding: 5,
        borderRadius: 5,
        borderColor: '#f2f2f2',
        borderWidth: 1,
      }
      markers.push(obj)
    })
    this.setState({
      markers
    })
  }

  getAroundInfo (aroundTags) {
    const { curObj, curId, markersNameArr } = this.state
    let aroundInfoTemp = []
    aroundTags.forEach((keyword, keywordIndex) => {
      aroundInfoTemp.push(
        new Promise((resolve, reject) => {
          let keywordParams = {
            keyword,
            address_format: 'short',
            page_size: '30',
            location: {
              latitude: curObj.latitude,
              longitude: curObj.longitude
            },
            success: function (res) {
              let cData = res.data || []
              qqmapsdk.calculateDistance({
                mode: '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 = 3000
                      // if (keywordIndex === 0) num = 1000
                      // if (keywordIndex === 1) num = 1000
                      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, index) =>{
        if (item.list.length > 0) {
          aroundArr.push({...item})
        } else {
          aroundArr.push({
            keyword: markersNameArr[index],
            list: []
          })
        }
      })
      let csl = curObj.school_list || {}
      const schoolList = [...csl.duikou, ...csl.guihua]
      const schoolArr = schoolList.map(slItem => {
        return {
          title: slItem.school_name,
          address: slItem.address,
          location: {
            lat: Number(slItem.latitude),
            lng: Number(slItem.longitude),
          }
        }
      })
      aroundArr.unshift({
        keyword: '学校',
        list: schoolArr
      })
      this.setState({
        aroundArr
      }, () => {
        this.navChange(0)
        // this.getMarker()
      })
      Taro.api.house.apiestateperipheryadd({
        estate_id: curId,
        periphery: JSON.stringify(aroundArr)
      }).then(eObj => {
        // console.log(eObj)
      })
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  posMoreHandle (str) {
    this.setState({
      isPosMoreShow: str === 'down' ? false : true
    })
  }

  renderOptionsInfo () {
    const { aroundArr, posIndex, isPosMoreShow } = this.state
    const icon0 = require('./img/map/school0.png')
    const icon0c = require('./img/map/school1.png')
    const icon1 = require('./img/map/subway0.png')
    const icon1c = require('./img/map/subway1.png')
    const icon2 = require('./img/map/bus0.png')
    const icon2c = require('./img/map/bus1.png')
    const icon3 = require('./img/map/park0.png')
    const icon3c = require('./img/map/park1.png')
    const icon4 = require('./img/map/hospital0.png')
    const icon4c = require('./img/map/hospital1.png')
    const icon5 = require('./img/map/shop0.png')
    const icon5c = require('./img/map/shop1.png')
    const iconDown = require('./img/map/down.png')
    const iconUp = require('./img/map/up.png')
    const lebelPos = require('./img/map/label_pos.png')
    const curMoreList = aroundArr[posIndex] && aroundArr[posIndex].list.length > 0 ? aroundArr[posIndex].list : []
    return (
      <View className="scoped-options">
        {
          isPosMoreShow
          ? <Image src={iconDown} className="so-icon-updown" onClick={this.posMoreHandle.bind(this, 'down')}/>
          : <Image src={iconUp} className="so-icon-updown" onClick={this.posMoreHandle.bind(this, 'up')}/>
        }
        <View className="so-wrap">
          {
            aroundArr.map((one, oneIndex) => {
              let str = icon0
              if (oneIndex === 0) str = oneIndex === posIndex ? icon0c : icon0
              if (oneIndex === 1) str = oneIndex === posIndex ? icon1c : icon1
              if (oneIndex === 2) str = oneIndex === posIndex ? icon2c : icon2
              if (oneIndex === 3) str = oneIndex === posIndex ? icon3c : icon3
              if (oneIndex === 4) str = oneIndex === posIndex ? icon4c : icon4
              if (oneIndex === 5) str = oneIndex === posIndex ? icon5c : icon5
              return (
                <View className="so-item" key={oneIndex}>
                  <View className={oneIndex === posIndex ? 'so-title cur' : 'so-title'} onClick={this.navChange.bind(this, oneIndex)}>
                    <Image src={str} className="img"/>
                    <View className="t">{one.keyword}</View>
                  </View>
                </View>
              )
            })
          }
        </View>
        {
          isPosMoreShow
          &&
          <View className="so-content">
            {
              curMoreList.map((two, twoIndex) => {
                return (
                  <View className="so-p" key={twoIndex} onClick={this.posLabelHandle.bind(this, twoIndex)}>
                    <View className="p1">{two.title}</View>
                    <View className="p2">{two.address} </View>
                    {
                      posIndex > 0
                      &&
                      <View className="r1"><Image src={lebelPos} className="i"/>{two._distance}米</View>
                    }
                    {
                      posIndex > 2
                      &&
                      <View className="r2">开车约:{(two.duration / 60).toFixed(0)}分钟</View>
                    }
                  </View>
                )
              })
            }
            {
              curMoreList.length === 0
              &&
              <ListMore isOther={true} />
            }
          </View>
        }
      </View>
    )
  }
  posLabelHandle (index) {
    this.setState({
      markerLabelIndex: index
    }, () => {
      this.getMarker()
    })
  }
  previewImageHandle (cur, arr) {
    const current = `${cur}_plus`
    const urls = arr.map(item => {
      return `${item.img_url}_plus`
    })
    Taro.previewImage({
      current,
      urls
    })
  }

  navChange (posIndex) {
    this.setState({
      posIndex,
      markerLabelIndex: -1,
    }, () => {
      this.getMarker()
    })
  }

  renderPos () {
    const { curObj, isPosMoreShow, markers } = this.state
    return (
      <View className="scoped-list-map">
        <Map
          className={isPosMoreShow ? 'm t2' : '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">
        {this.renderTop()}
        {
          aroundArr.length > 0
          &&
          this.renderPos()
        }
        {this.renderOptionsInfo()}
      </View>
    )
  }
}

export default Index
