import Taro, { useState } from '@tarojs/taro'
import { View } from '@tarojs/components'
import PoiAround from '@components/amap/PoiAround'
import Tab from './Tab'
import Pannel from './Pannel'
import './style.scss'

export default function Around(props) {
  const detail = props.building || {}
  const [lat, lng] = (detail.coordinate || '').split(',')
  const poiDatas = detail.mapJson ? JSON.parse(detail.mapJson) : []

  // 展示内容数组
  const dataList = poiDatas.map((item) => {
    const key = item.key
    const manualData = (detail[`building${key}`] || '').split(',')

    return {
      ...item,
      manualData,
      num: (item.data || []).length + manualData.length,
    }
  })

  // 所有的 markers
  const markersList = dataList.map((item) => {
    
    return (item.data || []).map((it) => {
      const [longitude, latitude] = it.location.split(',')

      return {
        id: it.id,
        latitude,
        longitude,
        name: it.name,
        address: it.address,
      }
    })
  })

  // 部分默认值
  const [curTab, setCurTab] = useState(0)
  const [markers, setMarkers] = useState(markersList[curTab])
  const [curAD, setCurAD] = useState()
  
  // tab 切换
  const handleTabChange = (index, tabItem) => {
    setCurTab(index)
    setMarkers(markersList[index])
  }

  // marker 点切换
  const handleMarkerTap = (marker) => {
    setCurAD(marker.id)
  }

  const goto = () => {
    if (typeof props.onAction === 'function') {
      props.onAction()
    }
  }
  
  return (
    <View className="around-box">
      <View className="around-header">
        <PoiAround style="width: 100vw; height: 500rpx;" markers={markers} longitude={lng} latitude={lat} onMarkerClick={handleMarkerTap}/>
      </View>
      <View className="around-body">
        <Tab dataset={dataList} onChange={handleTabChange} />
        <Pannel active={curAD} dataset={dataList[curTab]} />
        <View className="goto-map" onClick={goto}>立即前往</View>
        <View className="around-hr" />
      </View>
    </View>
  )
}
