
import { useCallback, useEffect, useMemo, useState } from 'react'
import Taro from '@tarojs/taro'
import { Map, CoverView } from '@tarojs/components'
import '@/assets/css/iconfont.css'
import './index.scss'

const poiTypes = [
  { label: '交通', value: 'Transport', class: 'iconfont icon-jiaotong' },
  { label: '商业', value: 'Mall', class: 'iconfont icon-shangye' },
  { label: '学校', value: 'Edu', class: 'iconfont icon-xuexiao' },
  { label: '医院', value: 'Hospital', class: 'iconfont icon-yiyuan' },
  { label: '银行', value: 'Bank', class: 'iconfont icon-yinhang' },
  { label: '餐饮', value: 'Restaurant', class: 'iconfont icon-canyin' },
]

export default function Periphery (props) {
  const { Info } = props

  const [pois, setPois] = useState([])
  const [markers, setMarkers] = useState([])

  const loc = useMemo(() => (Info?.coordinate ? Info.coordinate.split(',') : []), [Info?.coordinate])

  const countLen = useCallback((type) => {
    if (!Info) return 0;
    const tagLen = (Info[`building${type}`] || '').split(',').filter(Boolean).length
    const poiLen = pois.filter((poi) => poi.key === type).map((it) => (it.data ? it.data.length : 0)).reduce((acc, i) => (acc + i), 0)

    return tagLen + poiLen
  }, [Info, pois])

  const handleClick = () => {
    Taro.navigateTo({url: `/pages/index/buildingAround/index?id=${Info.buildingId}`})
  }

  useEffect(() => {
    // 地图 marker
    if (Info?.coordinate) {
      const mks = []
      // 项目位置
      mks.push({
        id: -1,
        longitude: loc[0],
        latitude: loc[1],
        iconPath: '',
        width: 18,
        height: 27,
        callout: {
          content: Info.buildingName,
          color: '#333333',
          padding: 6,
          display: 'ALWAYS',
        }
      })
      // pois
      if (Info?.mapJson) {
        const poiArr = JSON.parse(Info.mapJson).map((it) => ({ ...it, data: JSON.parse(it.data) }))
        setPois(poiArr)
      }
  
      setMarkers(mks)
    }
  }, [Info, loc])

  if (!Info?.coordinate) {
    return null
  }

  return (
    <view className='components Periphery'>

      <view className='Title flex-h'>
        <view className='flex-item'>
          <text>位置及周边配套</text>
        </view>
      </view>

      <view className='Map'>
        <view>
          <Map
            id='poi-around'
            // show-location
            scale={12}
            markers={markers}
            longitude={loc[0]}
            latitude={loc[1]}
            // enable-enableScroll
            // enable-zoom
          />
        </view>
      </view>

      <view className='List flex-h' onClick={handleClick}>
        {
          poiTypes.map((item) => (
            <view className='flex-item' key={item.value}>
              <text className={item.class}></text>
              <text>{item.label}</text>
              <text>({countLen(item.value)})</text>
            </view>
          ))
        }
      </view>

    </view>
  )
}
