import {
  Button,
  closeToast,
  Icon,
  Popup,
  showToast,
  Slider,
  Swipe,
  SwipeItem,
  Tab,
  Tabs
} from 'vant'
import {
  defineComponent,
  onMounted,
  reactive,
  nextTick,
  onUnmounted,
  ref,
  watch,
  Transition,
  computed
} from 'vue'
import iconBack from './image/back.svg'
import styles from './index.module.less'
import Plyr from 'plyr'
import 'plyr/dist/plyr.css'
import request from '@/helpers/request'
import { state } from '@/state'
import { useRoute } from 'vue-router'
import { listenerMessage, postMessage } from '@/helpers/native-message'
import MusicScore from './component/musicScore'
import iconMenu from './image/icon-menu.svg'
import iconDian from './image/icon-dian.svg'
import iconPoint from './image/icon-point.svg'
import iconLoop from './image/icon-loop.svg'
import iconLoopActive from './image/icon-loop-active.svg'
import iconplay from './image/icon-play.svg'
import iconpause from './image/icon-pause.svg'
import Points from './component/points'
import { getSecondRPM } from '@/helpers/utils'
import { useRect } from '@vant/use'

export default defineComponent({
  name: 'CoursewarePlay',
  setup() {
    const handleInit = (type = 0) => {
      postMessage({
        api: 'setRequestedOrientation',
        content: {
          orientation: type
        }
      })
      postMessage({
        api: 'setBarStatus',
        content: {
          status: type
        }
      })
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: type
        }
      })
    }
    handleInit()
    onUnmounted(() => {
      handleInit(1)
      window.removeEventListener('message', iframeHandle)
    })

    const route = useRoute()
    const headeRef = ref()
    const data = reactive({
      detail: null,
      knowledgePointList: [] as any,
      itemList: [] as any,
      showHead: true
    })
    const activeData = reactive({
      nowTime: 0,
      model: true, // 遮罩
      videoBtns: true, // 视频
      currentTime: 0,
      duration: 0,
      timer: null as any,
      item: null as any
    })
    watch(() => activeData.model, () => {
      const videoItem = data.itemList.find(n => n.id === popupData.itemActive)
      // 阴影切换的时候,具体去切换某个视频的控件
      if (videoItem && videoItem.type === 'VIDEO'){
        videoItem.playModel = activeData.model
      }
    })
    const getItemList = () => {
      const list: any = []
      for (let i = 0; i < data.knowledgePointList.length; i++) {
        const item = data.knowledgePointList[i]
        for (let j = 0; j < item.materialList.length; j++) {
          const material = item.materialList[j]
          if (popupData.itemActive === '') {
            popupData.tabName = item.name
            popupData.tabActive = material.knowledgePointId
            popupData.itemActive = material.id
            popupData.itemName = material.name
            popupData.activeIndex = 0
          }
          let videoItem = {}
          if (material.type === 'VIDEO') {
            videoItem = {
              currentTime: 0,
              duration: 0,
              paused: true,
              loop: false,
              videoEle: null,
              timer: null,
              playModel: true
            }
          }
          list.push({
            ...material,
            ...videoItem,
            iframeRef: null
          })
        }
      }
      // console.log('🚀 ~ list', list)
      data.itemList = list
    }
    const getDetail = async () => {
      try {
        const res: any = await request.get(
          state.platformApi + `/lessonCoursewareDetail/detail/${route.query.id}`
        )
        if (Array.isArray(res?.data)) {
          data.detail = res.data
        }
        if (Array.isArray(res?.data?.knowledgePointList)) {
          data.knowledgePointList = res.data.knowledgePointList.map((n: any) => {
            n.index = 0
            return n
          })
          getItemList()
        }
      } catch (error) {}
    }
    // ifram事件处理
    const iframeHandle = (ev: MessageEvent) => {
      // console.log(ev.data)
      if (ev.data?.api === 'headerTogge') {
        activeData.model = ev.data.show
      }
    }
    onMounted(() => {
      getDetail()
      window.addEventListener('message', iframeHandle)
    })
    // 返回
    const goback = () => {
      // history.go(-1)
      postMessage({ api: 'back' })
    }

    const swipeRef = ref()
    const popupData = reactive({
      open: false,
      activeIndex: -1,
      tabActive: '',
      tabName: '',
      itemActive: '',
      itemName: ''
    })
    // 设置当前的激活状态
    const setActiveData = (val: any, oldVal: any) => {
      handleStopVideo()
      handleStopMusicScore()
    }
    watch(() => popupData.activeIndex, setActiveData)

    // 停止所有的播放
    const handleStopVideo = () => {
      data.itemList.forEach((m: any) => {
        m.videoEle?.pause()
      })
    }
    // 停止曲谱的播放
    const handleStopMusicScore = () => {
      data.itemList.forEach((m: any) => {
        m.iframeRef?.contentWindow?.postMessage({ api: 'setPlayState' }, '*')
      })
    }
    // 获取name
    const setAllName = () => {
      const item = data.itemList.find((n: any) => n.id == popupData.itemActive)
      const tab = data.knowledgePointList.find((n: any) => n.id == popupData.tabActive)
      if (item) {
        popupData.itemName = item.name
      }
      if (tab) {
        popupData.tabName = tab.name
      }
    }
    // 切换素材
    const toggleMaterial = () => {
      const index = data.itemList.findIndex((n: any) => n.id == popupData.itemActive)
      if (index > -1) {
        popupData.activeIndex = index
        swipeRef.value?.swipeTo(index)
        setAllName()
      }
    }
    // 轮播切换
    const handleSwipeChange = (val: any) => {
      popupData.activeIndex = val
      const item = data.itemList[val]
      if (item) {
        popupData.tabActive = item.knowledgePointId
        popupData.itemActive = item.id
        setAllName()
      }
    }
    // 上一个知识点, 下一个知识点
    const handlePreAndNext = (type: string) => {
      if (type === 'up') {
        swipeRef.value?.prev()
      } else {
        swipeRef.value?.next()
      }
    }

    // 去点名,签退
    const gotoRollCall = (pageTag: string) => {
      postMessage({
        api: 'open_app_page',
        content: {
          action: 'app',
          pageTag: pageTag,
          url: '',
          params: JSON.stringify({ courseId: route.query.courseId })
        }
      })
    }

    // 双击
    const handleDbClick = (item: any) => {
      // console.log(activeData.item)
      if (item && item.type === 'VIDEO') {
        const videoEle: HTMLVideoElement = document.querySelector(`[data-vid='${item.id}']`)!
        if (videoEle) {
          if (videoEle.paused) {
            closeToast()
            videoEle.play()
          } else {
            showToast('已暂停')
            videoEle.pause()
          }
        }
        item.timer = setTimeout(() => {
          activeData.model = false
        }, 3000)
        console.dir(videoEle)
      }
    }

    // 调整播放进度
    const handleChangeSlider = (val: any, m: any) => {
      if (m?.videoEle) {
        m.videoEle.currentTime = val
      }
    }

    return () => (
      <div class={styles.coursewarePlay}>
        <Swipe
          style={{ height: '100vh' }}
          ref={swipeRef}
          showIndicators={false}
          loop={false}
          vertical
          lazyRender={true}
          onChange={handleSwipeChange}
        >
          {data.itemList.map((m: any, mIndex: number) => {
            return (
              <SwipeItem>
                <>
                  <div
                    class={styles.itemDiv}
                    onClick={() => {
                      clearTimeout(activeData.timer)
                      clearTimeout(m.timer)
                      if (Date.now() - activeData.nowTime < 300) {
                        handleDbClick(m)
                        return
                      }
                      activeData.nowTime = Date.now()
                      activeData.timer = setTimeout(() => {
                        activeData.model = !activeData.model
                      }, 300)
                    }}
                  >
                    {m.type === 'VIDEO' ? (
                      <>
                        <video
                          preload="auto"
                          class="player"
                          data-vid={m.id}
                          src={m.content}
                          loop={m.loop}
                          onLoadedmetadata={(e: Event) => {
                            const videoEle = e.target as unknown as HTMLVideoElement
                            videoEle.currentTime = 0.5
                            m.currentTime = videoEle.currentTime
                            m.duration = videoEle.duration
                            m.videoEle = videoEle
                          }}
                          onTimeupdate={(e: Event) => {
                            const videoEle = e.target as unknown as HTMLVideoElement
                            m.currentTime = videoEle.currentTime
                          }}
                          onPlay={() => {
                            m.paused = false
                          }}
                          onPause={() => {
                            clearTimeout(m.timer)
                            m.paused = true
                          }}
                        >
                          <source src={m.content} type="video/mp4" />
                        </video>
                        <Transition name="bottom">
                          {m.playModel && (
                            <div class={styles.bottomFixedContainer}>
                              <div class={styles.time}>
                                <span>{getSecondRPM(m.currentTime)}</span>
                                <span>{getSecondRPM(m.duration)}</span>
                              </div>
                              <div class={styles.slider}>
                                <Slider
                                  buttonSize={16}
                                  step={0.01}
                                  v-model:modelValue={m.currentTime}
                                  onUpdate:modelValue={(val: any) => handleChangeSlider(val, m)}
                                  min={0}
                                  max={m.duration}
                                />
                              </div>

                              <div class={styles.actions}>
                                <div>
                                  {m.paused ? (
                                    <Icon
                                      name={iconplay}
                                      onClick={(e: Event) => {
                                        e.stopPropagation()
                                        clearTimeout(m.timer)
                                        console.log('点击播放', m.videoEle)
                                        m.videoEle?.play()
                                        m.paused = false
                                        m.timer = setTimeout(() => {
                                          activeData.model = false
                                        }, 3000)
                                      }}
                                    />
                                  ) : (
                                    <Icon
                                      name={iconpause}
                                      onClick={(e: Event) => {
                                        e.stopPropagation()
                                        console.log('点击暂停')
                                        m.videoEle?.pause()
                                        m.paused = true
                                      }}
                                    />
                                  )}
                                  {m.loop ? (
                                    <Icon
                                      name={iconLoopActive}
                                      onClick={(e: Event) => {
                                        e.stopPropagation()
                                        m.loop = false
                                      }}
                                    />
                                  ) : (
                                    <Icon
                                      name={iconLoop}
                                      onClick={(e: Event) => {
                                        e.stopPropagation()
                                        m.loop = true
                                      }}
                                    />
                                  )}
                                </div>
                                <div>{popupData.itemName}</div>
                              </div>
                            </div>
                          )}
                        </Transition>
                      </>
                    ) : m.type === 'IMG' ? (
                      <img src={m.content} />
                    ) : (
                      <MusicScore
                        data-vid={m.id}
                        music={m}
                        onSetIframe={(el: any) => {
                          m.iframeRef = el
                        }}
                      />
                    )}
                    {/* <Transition name="van-fade">
                      {activeData.model && <div class={styles.playModel}></div>}
                    </Transition> */}
                  </div>
                </>
              </SwipeItem>
            )
          })}
        </Swipe>

        <Transition name="top">
          {activeData.model && (
            <div class={styles.headerContainer} ref={headeRef}>
              <div class={styles.backBtn} onClick={() => goback()}>
                <Icon name={iconBack} />
                返回
              </div>
              <div class={styles.menu}>{popupData.tabName}</div>
            </div>
          )}
        </Transition>

        <Transition name="right">
          {activeData.model && (
            <div class={styles.rightFixedBtns}>
              <div class={styles.fullBtn} onClick={() => (popupData.open = true)}>
                <img src={iconMenu} />
                <span>知识点</span>
              </div>
              {route.query.courseId && (
                <>
                  <div
                    class={[styles.fullBtn, styles.point]}
                    onClick={() => gotoRollCall('student_roll_call')}
                  >
                    <img src={iconDian} />
                    <span>点名</span>
                  </div>
                  <div class={styles.fullBtn} onClick={() => gotoRollCall('sign_out')}>
                    <img src={iconPoint} />
                    <span>签退</span>
                  </div>
                </>
              )}
            </div>
          )}
        </Transition>

        <Transition name="left">
          {activeData.model && (
            <div class={styles.leftFixedBtns}>
              <div class={[styles.fullBtn, styles.prePoint]} onClick={() => handlePreAndNext('up')}>
                <span style={{ textAlign: 'center' }}>
                  上一
                  <br />
                  知识点
                </span>
              </div>
              <div class={styles.fullBtn} onClick={() => handlePreAndNext('down')}>
                <span style={{ textAlign: 'center' }}>
                  下一
                  <br />
                  知识点
                </span>
              </div>
            </div>
          )}
        </Transition>

        <Popup
          class={styles.popup}
          overlayClass={styles.overlayClass}
          position="right"
          round
          v-model:show={popupData.open}
        >
          <Points
            data={data.knowledgePointList}
            tabActive={popupData.tabActive}
            itemActive={popupData.itemActive}
            onHandleSelect={(res: any) => {
              // console.log(res)
              popupData.tabActive = res.tabActive
              popupData.itemActive = res.itemActive
              popupData.open = false
              toggleMaterial()
            }}
          />
        </Popup>
      </div>
    )
  }
})
