import Taro, { useLoad, useReady, useUnload } from '@tarojs/taro'
import { PropsWithChildren, useState } from 'react'
import { View, Video, Image } from '@tarojs/components'
import useGetCustomClient from '@/hooks/useGetCustomClient'
import { wrapProps, generateUUID } from '@/plugin/share'
import './index.less'
import http from '@/http/index'
import { adSelfPredict } from '@/http/api/index'
import { adActionLog } from '@/logCenter/index'
import { reportBusinessType } from '@/plugin/share/const'

// 在一些场景下 loadedMetaFiredInOnce 被触发了很多次
let loadedMetaFiredInOnce = 0

function PqCustom(props: PropsWithChildren<CustomPropsType>) {
  let {
    adpId,
    autoplay,
    loop,
    muted,
    showMusk,
    zIndex,
    openEmbeddedMiniProgram,
    onPlay,
    onPause,
    onEnded,
    onTimeUpdate,
    onStop,
    onError,
    onLoad,
    onView,
    onClick,
    onClose
  } = wrapProps(props)
  const [show, setShow] = useState(true)
  const [adData, setAdData] = useState<any>({})

  useReady(() => {
    getAdConfig()

    adActionReport(reportBusinessType.buttonView, 'adView')
  })

  function getAdConfig() {
    http.post(`${adSelfPredict}?adpId=uh2321awe1`, {
      baseInfo: {},
      positionId: 1,
      phoneModel : '',
      careModelStatus : 1,
      videoId: 0
    }, {
      header: { 'content-type': 'application/json;' }
    }).then((res: RequestType) => {
      const { code, data } = res
      // TODO: onError、logUpload
      if(code !== 0) {
        onError()
        // logUpload()
        return
      }

      const { ownPlatformAlliance } = data || {}
      const { adType, platformCreativeInfo } = ownPlatformAlliance || {}
      setAdData({
        adType,
        ...platformCreativeInfo
      })

      console.log(data)
    }).catch(err => {
      console.log(err)
    })
  }

  function videoPlay() {
    onPlay()
  }

  function videoPause() {
    onPause()
  }

  function videoPlayEnded() {
    onEnded()
  }

  function videoTimeUpdate() {
    onTimeUpdate()
  }

  function videoStop() {
    onStop()
  }

  function videoClick() {
    closeCustom()
  }

  function closeCustom() {
    onClose()
    setShow(false)
  }

  function clickMask() {
    onClick()
    closeCustom()
  }

  function adActionReport(eventId, businessType) {
    const {
      adCode,
      adPosition,
      advertiserId,
      ownAdDetailId,
      ownAdPositionId,
      ownAdSystemType,
      planId,
    } = adData

    adActionLog([{
      adCode,
      adPosition,
      advertiserId,
      businessType,
      eventId,
      ownAdDetailId,
      ownAdPositionId,
      ownAdSystemType,
      pageSource: 'plugin',
      planId,
      pqtId: generateUUID(),
      videoId: '000'
    }])
  }

  return (
    <>
      {show && <View className='pq-custom' onClick={clickMask}>
        <View className='custom-container'>
          <View className='icon' style={{zIndex: (zIndex || 1) + 1}}>
            广告
          </View>
          <View className='close-icon'style={{zIndex: (zIndex || 1) + 1}} onClick={closeCustom}>
          </View>

          {/* <Navigator url={WEB_VIEW_URL}> */}
            <Custom
              autoplay={autoplay}
              loop={loop}
              muted={muted}
              adData={adData}
              onPlay={videoPlay}
              onTimeUpdate={videoTimeUpdate}
              onPause={videoPause}
              onEnded={videoPlayEnded}
              onStop={videoStop}

              onClick={videoClick}
              onLoad={onLoad}
              onView={onView}
              onError={onError}
            />
          {/* </Navigator> */}
        </View>
      </View>}
    </>
  )
}

function Custom({
  autoplay, loop, muted, adData,
  onPlay, onPause, onEnded, onTimeUpdate, onStop, // 播放事件
  onClick, onLoad, onView, onError
}) {
  const [style, setStyle] = useState({ width: '0px', height: 'px' })

  useReady(() => {
    loadedMetaFiredInOnce = 0
  })

  useGetCustomClient((customClient) => {
    let clientWidth = customClient.width
    let clientHeight = customClient.height

    setStyle({
      width: `${clientWidth}px`,
      height: `${clientHeight}px`
    })
  })

  function onLoadedMetaData() {
    if (loadedMetaFiredInOnce++ < 1) {
      // 上报load
      onLoad()
    }
  }

  return (
    <View className='custom' style={style}>
      <Video
        id='pq-custom'
        className='custom-video'
        objectFit='fill'
        controls={false}
        // video属性
        autoplay={autoplay}
        loop={loop}
        muted={muted}
        src={adData.materialAddress}
        poster={adData.materialCoverPic}
        // video事件
        onPlay={onPlay}
        onTimeUpdate={onTimeUpdate}
        onPause={onPause}
        onEnded={onEnded}
        onStop={onStop}
        onError={onError}

        // video交互
        onClick={onClick}
        onLoadedMetaData={onLoadedMetaData}
      />
      <View className='custom-bottom'>
        <Image src={adData.creativeLogoAddress} className='logo' />
        <View className='title'>{adData.creativeTitle}</View>
        <View className='button'>{adData.clickButtonText}</View>
      </View>
    </View>
  )
}

export default PqCustom
