import { Button, Icon, Popup, Swipe, SwipeItem, Tab, Tabs } from 'vant'
import {
  defineComponent,
  onMounted,
  reactive,
  nextTick,
  onUnmounted,
  ref,
  watch,
  Transition
} 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 { postMessage } from '@/helpers/native-message'
import OHeader from '@/components/o-header'
import MusicScore from './component/musicScore'
import iconMenu from './image/icon-menu.svg'
import Points from './component/points'

export default defineComponent({
  name: 'CoursewarePlay',
  setup() {
    const handleInit = () => {
      postMessage({
        api: 'setRequestedOrientation',
        content: {
          orientation: 0
        }
      })
      postMessage({
        api: 'setBarStatus',
        content: {
          status: 0
        }
      })
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: 0
        }
      })

      // window.addEventListener('message', (res: any) => {
      //   // console.log(res)
      //   if (res?.data?.api) {
      //     const { api } = res.data
      //     if (api === 'touchstart') {
      //       isTouch.value = true
      //       console.log('🚀 ~ 父页面touchstart')
      //     }
      //     if (api === 'touchend') {
      //       isTouch.value = false
      //       console.log('🚀 ~ 父页面touchend')
      //     }
      //   }
      // })
    }

    const route = useRoute()
    const data = reactive({
      detail: null,
      active: '',
      knowledgePointList: [] as any,
      showHead: true,
      players: [] as any
    })
    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
          })
        }
        console.log('数据加载完成')
      } catch (error) {}
      nextTick(() => {
        console.log('开始加载视频')
        videoInit()
      })
    }
    const videoInit = () => {
      // console.log(document.querySelectorAll('.player'))
      data.players = Plyr.setup('.player', {
        debug: false,
        ratio: '16:9',
        clickToPlay: true,
        controls: ['play-large',  'play', 'progress', 'current-time','duration', 'mute', 'volume',  'restart']
      })
      data.players.forEach((p: Plyr) => {
        // console.log(p)
        p.on('play', () => {
          console.log('开始播放了')
          data.showHead = false
        })
        p.on('pause', () => {
          console.log('暂停了')
          data.showHead = true
        })
        p.on('controlsshown', () => {
          console.log('显示控件')
          data.showHead = true
        })
        p.on('controlshidden', () => {
          console.log('控件隐藏')
          data.showHead = false
        })
      })
      console.log('🚀 ~ player', data.players)
    }
    onMounted(() => {
      handleInit()
      getDetail()
    })
    // 返回
    const goback = () => {
      history.go(-1)
    }
    // 所有的切换
    const handleChange = () => {
      // console.log('切换了')
      const iframes = document.querySelectorAll('.musicIframe')
      Array.from(iframes).map((f: any) => {
        f.contentWindow.postMessage({ api: 'setPlayState' }, '*')
      })
      data.players.forEach((p: any) => {
        p.stop()
      })
    }
    onUnmounted(() => {
      postMessage({
        api: 'setRequestedOrientation',
        content: {
          orientation: 1
        }
      })
      postMessage({
        api: 'setBarStatus',
        content: {
          status: 1
        }
      })
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: 1
        }
      })
    })

    const popupData = reactive({
      open: false,
      active: ''
    })
    // 监听切换
    watch(
      () => popupData.active,
      () => {
        console.log(data.active, '监听切换')
        handleChange()
        const knowledge = data.knowledgePointList.find((n: any) => n.id === data.active)
        if (knowledge && knowledge?.materialList[knowledge.index]) {
          // 如果是曲谱,隐藏头部
          if (knowledge.materialList[knowledge.index]?.type === 'SONG') {
            data.showHead = false
            return
          }
        }
        data.showHead = true
      }
    )
    return () => (
      <div class={styles.coursewarePlay}>
        <Transition name='top'>
          {data.showHead && (
            <div class={styles.headerContainer}>
              <div class={styles.backBtn} onClick={() => goback()}>
                <Icon name={iconBack} />
                返回
              </div>
              <div class={styles.menu}>
                <Tabs
                  v-model:active={data.active}
                  ellipsis={false}
                  onChange={() => {
                    const knowledge = data.knowledgePointList.find((_: any) => _.id === data.active)
                    popupData.active = `${data.active}-${
                      knowledge?.materialList?.[knowledge.index]?.id
                    }`
                  }}
                >
                  {{
                    default: () => {
                      return data.knowledgePointList.map((n: any) => {
                        return <Tab title={n.name} name={n.id}></Tab>
                      })
                    }
                    // 'nav-right': () => <div style={{width: '40%'}} class={styles.menuLine}></div>
                  }}
                </Tabs>
              </div>
            </div>
          )}
        </Transition>
                  
        <Tabs class={styles.tabsContent} animated lazyRender={false} v-model:active={data.active}>
          {data.knowledgePointList.map((item: any) => {
            return (
              <Tab name={item.id}>
                <Swipe
                  style={{ height: '100vh' }}
                  showIndicators={false}
                  loop={false}
                  initialSwipe={item.index}
                  vertical
                  lazyRender={false}
                  onChange={(val: any) => {
                    item.index = val
                    popupData.active = `${item.id}-${item?.materialList?.[item.index]?.id}`
                  }}
                >
                  {Array.isArray(item?.materialList) &&
                    item.materialList.map((m: any) => {
                      if (popupData.active === '') {
                        popupData.active = `${item.id}-${m.id}`
                        console.log('🚀 ~ popupData', popupData)
                      }
                      return (
                        <SwipeItem>
                          {m.type === 'VIDEO' ? (
                            <div class={styles.videoItem}>
                              <video class="player" controls>
                                <source src={m.content} type="video/mp4" />
                              </video>
                            </div>
                          ) : m.type === 'IMG' ? (
                            <div class={styles.imgItem}>
                              <img src={m.content} />
                            </div>
                          ) : (
                            <div class={styles.songItem}>
                              <MusicScore music={m} />
                            </div>
                          )}
                        </SwipeItem>
                      )
                    })}
                </Swipe>
              </Tab>
            )
          })}
        </Tabs>
        <div class={styles.fullBtn} onClick={() => (popupData.open = true)}>
          <img src={iconMenu} />
          <span>列表</span>
        </div>
        <Popup
          class={styles.popup}
          overlayClass={styles.overlayClass}
          position="left"
          v-model:show={popupData.open}
        >
          <Points
            data={data.knowledgePointList}
            active={popupData.active}
            onHandleSelect={(res: any) => {
              data.active = res.id
              const knowledge = data.knowledgePointList.find((n: any) => n.id === res.id)
              // console.log(res,knowledge)
              knowledge && (knowledge.index = res.index)
              popupData.active = res.active
              popupData.open = false
            }}
          />
        </Popup>
      </div>
    )
  }
})
