import Taro, { useLoad, useReady } 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'
import { queryURLParams } from '@/plugin/share'

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

function PqCustom(props: PropsWithChildren<CustomPropsType>) {
  let {
    adpId,
    openEmbeddedMiniProgram,
    onError,
    onLoad,
    onClose
  } = wrapProps(props)
  const [show, setShow] = useState(true)
  const [adData, setAdData] = useState<any>({})

  useReady(() => {
    init()
    pqtId = generateUUID()
    getAdConfig()
  })

  function init() {
    if (
        typeof adpId !== 'string' ||
        typeof openEmbeddedMiniProgram !== 'function'
      ) {
      catchError('参数错误', 1031)
      return
    }
  }

  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
      if(code === 10001) {
        catchError('广告资源加载失败', 1022)
        return
      }

      if(code === 10002) {
        catchError('adpId 无效', 1021)
        return
      }

      if(code === 10003) {
        catchError('初始化失败', 1011)
        return
      }

      const { ownPlatformAlliance } = data || {}
      const { adType, platformCreativeInfo } = ownPlatformAlliance || {}
      const { landingPageAddress } = platformCreativeInfo

      if (!landingPageAddress) {
        catchError('数据异常', 1013)
        return
      }

      setAdData({
        adType,
        ...platformCreativeInfo
      })
    }).catch(() => {
      catchError('初始化失败', 1011)
    })
  }

  function videoPlay() {
    adActionReport(reportBusinessType.adPlay, 'adPlay')
  }
  
  function videoClick() {
    adActionReport(reportBusinessType.adClick, 'adClick')
    videoOpenMiniProgram()
    closeCustom()
  }

  function videoOpenMiniProgram() {
    const { landingPageAddress } = adData
    const query = queryURLParams(createAdActionReportData())

    adActionReport(reportBusinessType.adPlay, 'adOpen')
    openEmbeddedMiniProgram(
      'wx5ef216d1caf4a0ea',
      `/pages/ad-launch-page/index?path=${encodeURIComponent(landingPageAddress)}&${query}`
    )

    console.log(`/pages/ad-launch-page/index?path=${encodeURIComponent(landingPageAddress)}&${query}`)
  }

  function videoLoad() {
    adActionReport(reportBusinessType.adLoad, 'adLoad')
    onLoad()
  }

  function videoError() {
    catchError('广告加载失败', 1012)
  }

  function videoView() {
    adActionReport(reportBusinessType.adView, 'adView')
  }

  function videoTimeUpdate() {}

  function closeCustom() {
    adActionReport(reportBusinessType.adClose, 'adClose')
    onClose()
    setShow(false)
  }

  function clickMask() {
    closeCustom()
  }

  function adActionReport(eventId, businessType, extParams = {}) {
    const data = createAdActionReportData

    adActionLog([{
      businessType,
      eventId,
      ...data,
      ...extParams
    }])
  }

  function createAdActionReportData() {
    const {
      trafficCode, // 流量主code
      // 广告主
      advertiserCode,
      advertiserId,
      // 广告计划
      campaignCode,
      campaignId,
      // 广告
      adCode,
      adId,
      // 创意
      creativeCode,
      id,
      // 广告位
      positionId,
      // 竞价
      bidType = '',
      unitPrice = '', // 单价
      bidCreativeParam = {}, // {}
    } = adData

    return {
      adpCode: trafficCode,
      advertiserCode,
      advertiserId,
      campaignCode,
      campaignId,
      adCode,
      adId,
      creativeCode,
      id,
      positionId,
      bidType,
      unitPrice, // 单价
      bidCreativeParam: JSON.stringify(bidCreativeParam || {}), // {}
      adpId,
      pqtId
    }
  }

  function catchError(message, code) {
    onError({ message, code })
    setShow(false)
    adActionReport(reportBusinessType.adError, 'adError', {
      errorCode: code
    })
  }

  return (
    <>
      {show && <View className='pq-custom' onClick={clickMask}>
        <View className='custom-container'>
          <View className='icon'>
            广告
          </View>
          <View className='close-icon' onClick={closeCustom}>
          </View>
            <Custom
              adData={adData}
              onPlay={videoPlay}
              onClick={videoClick}
              onLoad={videoLoad}
              onView={videoView}
              onError={videoError}
              onTimeUpdate={videoTimeUpdate}
            />
        </View>
      </View>}
    </>
  )
}

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

  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}
        autoplay
        loop
        src={adData.materialAddress}
        poster={adData.materialCoverPic}
        onPlay={onPlay}
        onTimeUpdate={onTimeUpdate}
        onError={onError}
        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
