import { useState, useEffect, useRef } from 'react'
import Taro from '@tarojs/taro'
import withLayout from '@/layout'
import { ScrollView, Map } from '@tarojs/components'
import { fetch } from '@/utils/request'
import { API_ITEMS_DETAIL } from '@/constants/api'
import '@/assets/css/iconfont.css'
import './index.scss'

export default withLayout((props) => {
  const { router, city } = props
  const { id } = router.params

  const [DetailInfo, setDetailInfo] = useState({})
  const [loc, setLoc] = useState([])
  const [NavList, setNavList] = useState([])
  const [CurrentNavId, setCurrentNavId] = useState(0)
  const [List, setList] = useState([])
  const [OtherList, setOtherList] = useState([])
  const [markers, setMarkers] = useState([])
  const mapCtx = useRef()

  const CutNav = (inx) => {
    return () => {
      setCurrentNavId(inx)
    }
  }

  const locationTo = () => {
    if (loc.length) {
      Taro.openLocation({
        longitude: loc[0],
        latitude: loc[1],
        name: DetailInfo.buildingName,
        address: DetailInfo.address,
      })
    }
  }

  const handlePoi = (poi) => {
    const [longitude, latitude] = poi.location.split(',').map(x => x ? x - 0 : undefined)

    const marker = {
      id: 1,
      longitude,
      latitude,
      // iconPath: '',
      width: 18,
      height: 27,
      callout: {
        content: poi.name,
        color: '#333333',
        padding: 6,
        display: 'ALWAYS',
      }
    }

    const center = markers[0]
    setMarkers([center, marker])

    if (mapCtx.current) {
      // 缩放地图，显示所有 marker
      const points = [
        { longitude: center.longitude, latitude: center.latitude },
        { longitude: marker.longitude, latitude: marker.latitude }
      ]
      mapCtx.current.includePoints({ points, padding: [64] })
    }
  }

  // 获取地图 Context
  useEffect(() => {
    Taro.nextTick(() => {
      mapCtx.current = Taro.createMapContext('around-map')
    })
  }, [])

  useEffect(() => {
    // 获取楼盘信息
    fetch({ url: `${API_ITEMS_DETAIL}/${id}`, spin: true }).then((res) => {
      if (res?.coordinate) {
        // 地图中心
        const [longitude, latitude] = res.coordinate.split(',')
        setLoc([longitude - 0, latitude - 0])
        // 中心点标记
        setMarkers([{
          id: -1,
          longitude,
          latitude,
          width: 18,
          height: 27,
          callout: {
            content: res.buildingName,
            color: '#333333',
            padding: 6,
            display: 'ALWAYS',
          }
        }])
        setDetailInfo(res || {})
        if (res.mapJson) {
          const pois = JSON.parse(res.mapJson).map(poi => ({ ...poi, data: JSON.parse(poi.data) }))
          pois.map((item) => {
            let target = []
            if(item.key === 'Transport') {
              target = (res.buildingTransport || '').split(',').map((subItem) => {
                return { name: subItem }
              })
            } else if(item.key === 'Mall') {
              target = (res.buildingMall || '').split(',').map((subItem) => {
                return { name: subItem }
              })
            } else if(item.key === 'Edu') {
              target = (res.buildingEdu || '').split(',').map((subItem) => {
                return { name: subItem }
              })
            } else if(item.key === 'Hospital') {
              target = (res.buildingHospital || '').split(',').map((subItem) => {
                return { name: subItem }
              })
            } else if(item.key === 'Bank') {
              target = (res.buildingBank || '').split(',').map((subItem) => {
                return { name: subItem }
              })
            } else if(item.key === 'Restaurant') {
              target = (res.buildingRestaurant || '').split(',').map((subItem) => {
                return { name: subItem }
              })
            }
            item.data = item.data.concat(target)
          })
          console.log(`pois is`, pois)
          console.log(res)
          setNavList(pois)
        }

      } else {
        Taro.showToast({
          title: '当前楼盘未设置位置信息',
          icon: 'none',
        })
      }
    }).catch((err) => {
      console.error(err)
    })

  }, [id])

  useEffect(() => {
    if (NavList && NavList.length) {
      const { key, data } = NavList[CurrentNavId]
      setList(data)

      const tags = DetailInfo[key] || ''
      setOtherList(tags.split(',').filter(Boolean))
    }
  }, [NavList, CurrentNavId, DetailInfo])

  const TypeCalc = (key) => {
    switch (key) {
      case 'Transport':
        return '交通'
      case 'Mall':
        return '商业'
      case 'Edu':
        return '学校'
      case 'Hospital':
        return '医院'
      case 'Bank':
        return '银行'
      case 'Restaurant':
        return '餐饮'
      default:
        return ''
    }
  }

  return (
    <view className='Page buildingAround'>

      <view className='MapContainer'>
        <view>
          <Map
            id='around-map'
            showLocation
            longitude={loc[0]}
            latitude={loc[1]}
            markers={markers}
          />
        </view>
      </view>

      <view className='TabContainer'>
        <view>

          <view className='Title flex-h'>
            <view className='flex-item'>
              <text>{DetailInfo.buildingName}</text>
            </view>
            <view className='Go' onClick={locationTo}>
              <text>前往</text>
              <text className='iconfont icon-qianwang'></text>
            </view>
          </view>

          <view className='Address flex-h'>
            <text className='iconfont icon-dingwei'></text>
            <view className='flex-item'>
              <text>{DetailInfo.address}</text>
            </view>
          </view>

          <view className='Nav flex-h'>
            {
              NavList.map((item, inx) => (
                <view className={inx === CurrentNavId ? 'flex-item active' : 'flex-item'} key={item.key}>
                  <text onClick={CutNav(inx)}>{`${TypeCalc(item.key)}`}</text>
                </view>
              ))
            }
          </view>

          <view className='CutLine'></view>

          <view className='ListContainer'>
            <ScrollView scroll-y>
              <view className='ScrollContent'>
                <view className='List'>
                  {
                    List.map((item, index) => (
                      <view className='flex-h' key={`ListItem-${index}`} onClick={() => handlePoi(item)}>
                        <text>{index + 1}、</text>
                        <view className='flex-item'>
                          <text>{item.name}</text>
                        </view>
                        <text className='iconfont icon-dingwei'></text>
                        <text className='distance'>{`${item.distance || '-'}m`}</text>
                      </view>
                    ))
                  }
                </view>
                {
                  OtherList.length > 0 &&
                  <text>其他</text>
                }
                <view className='List'>
                  {
                    OtherList.map((item, index) => (
                      <view className='flex-h' key={`ListItem-${index}`}>
                        <view className='flex-item'>
                          <text>{index + 1}、南京地铁1号线</text>
                        </view>
                      </view>
                    ))
                  }
                </view>
              </view>
            </ScrollView>
          </view>

        </view>
      </view>

    </view>
  )
})
