import { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import withLayout from '@/layout'
import { Image, Map } from '@tarojs/components'
import { getItemList } from '@/services/item'
import { getImgURL } from '@/utils/image'
import '@/assets/css/iconfont.css'
import './index.scss'

export default withLayout((props) => {
  const { city } = props

  const [ShowInfo, setShowInfo] = useState(false)
  const [list, setList] = useState([])
  const [markers, setMarkers] = useState([])
  const mapCtx = useRef()
  const [current, setCurrent] = useState({})

  const changeCity = () => {
    Taro.navigateTo({ url: '/pages/index/location/index' })
  }

  const handleMarker = (e) => {
    const { markerId } = e.detail
    const building = list[markerId - 1];
    setCurrent(building || {});
    setShowInfo(true)
  }

  const gotoDetail = () => {
    if (current.buildingId) {
      Taro.navigateTo({ url: `/pages/index/buildingDetail/index?id=${current.buildingId}` })
    }
  }

  const locationTo = () => {
    if (current.buildingId) {
      const loc = current.coordinate.split(',')
      Taro.openLocation({
        longitude: loc[0] - 0,
        latitude: loc[1] - 0,
        name: current.buildingName,
        address: current.address,
        scale: 12,
      })
    }
  }

  useEffect(() => {
    Taro.nextTick(() => {
      mapCtx.current = Taro.createMapContext('map-buildings')
    })
  }, [])

  useEffect(() => {
    if (city?.id) {
      // 先移除页面的 markers
      if (mapCtx.current && markers.length) {
        mapCtx.current.removeMarkers({ markerIds: markers.map(x => x.id) })
        setMarkers([])
      }

      getItemList({
        cityId: city.id,
        pageSize: 100,
      }).then((res) => {
        const { records } = res
        setList((records || []).filter(x => x.coordinate))
      })
    }
  }, [city?.id])

  useEffect(() => {
    if (!list.length) return;

    const mks = list.map((item, index) => {
      const loc = item.coordinate.split(',')

      return {
        id: index + 1,
        longitude: loc[0] - 0,
        latitude: loc[1] - 0,
        iconPath: '',
        width: 18,
        height: 27,
        callout: {
          content: item.buildingName,
          color: '#333333',
          fontSize: 14,
          display: 'ALWAYS',
          padding: 6,
          borderRadius: 2,
          borderColor: 'rgba(0,0,0, .1)',
        }
      }
    })

    const points = mks.map(it => ({ longitude: it.longitude, latitude: it.latitude }))
    setMarkers(mks)

    const t = setInterval(() => {
      if (mapCtx.current) {
        mapCtx.current.includePoints({ points, padding: [32] })
        clearInterval(t)
      }
    }, 300)

    return () => clearInterval(t)
  }, [list])

  return (
    <view className='Page findHouseFromMap'>

      {/* 地图 */}
      <view className='MapContainer'>
        <Map
          id='map-buildings'
          show-location
          scale={12}
          longitude={city?.lng}
          latitude={city?.lat}
          markers={markers}
          onMarkertap={handleMarker}
          onCallouttap={handleMarker}
          onTap={() => setShowInfo(false)}
        />
      </view>

      {/* 定位 */}
      <view className='Location' onClick={changeCity}>
        <text className='iconfont icon-dingwei'></text>
        <text>{city.name}</text>
      </view>

      {/* 分享 */}
      <button className='Share' openType='share'>
        <text className='iconfont icon-fenxiang'></text>
        <text>分 享</text>
      </button>

      {/* 附近楼盘 */}
      <view className={ShowInfo ? 'AroundBuilding active' : 'AroundBuilding'}>
        <view className='Go' onClick={locationTo}>
          <text>立即</text>
          <text>前往</text>
        </view>
        <view className='InfoContainer'>
          {/* <text className='Title' onClick={CutInfo(true)}>附近楼盘</text> */}
          <view className='InfoContent'>
            {
              !!current.buildingName &&
              <view className='Img' onClick={gotoDetail}>
                <Image mode='scaleToFill' src={getImgURL(current?.buildingListImg?.length ? current.buildingListImg[0].url : null)} className='centerLabel'></Image>
                {
                  current?.panoramaList.length > 0 &&
                  <Image mode='heightFix' className='Tips Vr' src={require('@/assets/index-icon18.png')} />
                }
                {
                  current?.videoUrl !== null &&
                  <Image mode='heightFix' className='Tips Video' src={require('@/assets/index-icon19.png')} />
                }
              </view>
            }
            <view className='Name flex-h'>
              <view className='flex-item'>
                <text>{current.buildingName}</text>
              </view>
              <text>{current.price}</text>
            </view>
            <text className='Address'>{current.address}</text>
            <view className='Tag'>
              {
                (current.buildingTag || []).map((item, index) => (
                  <text key={`Tags-${index}`}>{item.tagName}</text>
                ))
              }
            </view>
            <view className='Views flex-h'>
              <view className='flex-item'>
                <text className='iconfont icon-fenxiang'></text>
                <text>{`${199 + (current.shareNum || 0)}次分享`}</text>
              </view>
              <view className='Icons'>
                {
                  (current.uvList?.records || []).slice(0, 3).map((item, index) => (
                    <view key={`uv-${index}`}>
                      <Image mode='scaleToFill' className='centerLabel' src={item.photoOravatar} />
                    </view>
                  ))
                }
              </view>
              <text>{(current.uvList?.records || []).length > 0 ? '...' : ''}{`${199 + (current.pvNum || 0)}人围观`}</text>
            </view>
          </view>
        </view>
      </view>

    </view>
  )
})
