import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { Video } from '@tarojs/components'
import { getImgURL } from '@/utils/image'
import Banner from '../Banner'
import './index.scss'

const getImage = item => getImgURL(item.image || item.coverImg || item.url || item.img)

export default function BuildingDetailBanner (props) {
  const { Info } = props
  const { buildingImg, panoramaList, videoUrl, videoImage } = Info || {}
  const videoPoster = videoImage ? videoImage[0].url : undefined

  const showPicBtn = buildingImg && buildingImg.length > 0
  const showVRBtn = panoramaList && panoramaList.length > 0
  const shwoVideoBtn = !!videoUrl

  // JS 中 true + true = 2
  // const showBtns = (showPicBtn + showVRBtn + shwoVideoBtn) > 1

  const [NavList, setNavList] = useState([])
  const [CurrentNavId, setCurrentNavId] = useState(3)

  useEffect(() => {
    let Arr = []
    if (showVRBtn) {
      Arr.push({ name: 'VR', id: 1 })
    }
    if (shwoVideoBtn) {
      Arr.push({ name: '视频', id: 2 })
    }
    if (showPicBtn) {
      Arr.push({ name: '图片', id: 3 })
    }
    setNavList(Arr)
  }, [])

  const CutNavId = (id) => {
    return () => {
      setCurrentNavId(id)
    }
  }

  const handlePreview = (item, all) => {
    const img = getImage(item)
    if (!img) return

    Taro.previewImage({
      current: img,
      urls: all.map(getImage),
    })
  }

  const handleVR = (item) => {
    const url = (item || {}).panoramaLink
    if (!url) return

    Taro.navigateTo({
      url: `/pages/index/webview/index?url=${encodeURIComponent(url)}`
    })
  }

  return (
    <view className='components buildingDetailBanner'>

      {/* 切换 */}
      {
        !!NavList.length &&
        <view className={NavList.length === 3 ? 'CutPoint Three' : NavList.length === 2 ? 'CutPoint Two' : 'CutPoint'}>
          <view>
            {
              NavList.map((item, index) => (
                <text key={`NavItem-${index}`} className={CurrentNavId === item.id ? 'active' : ''} onClick={CutNavId(item.id)}>{item.name}</text>
              ))
            }
          </view>
        </view>
      }

      {/* VR */}
      {
        CurrentNavId === 1 && (
          <view className='Vr'>
            <Banner List={panoramaList} onClick={handleVR} />
          </view>
        )
      }

      {/* 视频 */}
      {
        CurrentNavId === 2 &&
        <view className='Video'>
          <Video
            controls
            showMuteBtn
            src={videoUrl}
            poster={getImgURL(videoPoster)}
            style={{ height: '600rpx', width: '750rpx' }}
          />
        </view>
      }

      {/* 图片 */}
      {
        CurrentNavId === 3 &&
        <view className='Picture'>
          <Banner List={buildingImg} onClick={handlePreview} />
        </view>
      }

    </view>
  )
}
