import { defineComponent, ref, watch } from 'vue'
import styles from './musicScore.module.less'
import qs from 'query-string'
import iconStart from '../image/icon-start.svg'
import { listenerMessage, postMessage } from '@/helpers/native-message'
import { Skeleton } from 'vant'
import { usePageVisibility } from '@vant/use'
import { useRoute } from 'vue-router'
import { browser } from '@/helpers/utils'

export default defineComponent({
  name: 'musicScore',
  props: {
    music: {
      type: Object,
      default: () => ({})
    },
    activeModel: {
      type: Boolean
    }
  },
  emits: ['setIframe'],
  setup(props, { emit }) {
    const browserInfo = browser()
    const route = useRoute()
    const isLoading = ref(false)
    const pageVisibility = usePageVisibility()
    /** 页面显示和隐藏 */
    watch(pageVisibility, value => {
      console.log('🚀 ~ value:', value)
      if (value == 'hidden') {
        isLoading.value = false
      }
    })
    const iframeRef = ref()
    const isLoaded = ref(false)
    const renderError = ref(false)
    const renderSuccess = ref(false)
    const Authorization = sessionStorage.getItem('Authorization') || ''
    const origin = /(localhost|192)/.test(location.host)
      ? 'https://test.colexiu.com'
      : location.origin
    const query = qs.stringify({
      t: +new Date(),
      id: props.music.content,
      Authorization: Authorization,
      isHideBack: 'true',
      limitModel: 'practice' // 只显示练习模式
    })

    const src = `${origin}/accompany/?` + query
    const checkView = () => {
      fetch(src)
        .then(() => {
          renderSuccess.value = true
          renderError.value = false
        })
        .catch(() => {
          renderError.value = true
        })
    }
    watch(props.music, () => {
      if (renderSuccess.value) return
      renderError.value = false
      if (props.music.display) {
        checkView()
      }
    })

    listenerMessage('webViewOnResume', () => {
      isLoading.value = false
    })

    return () => (
      <div class={styles.musicScore}>
        <iframe
          ref={iframeRef}
          onLoad={() => {
            emit('setIframe', iframeRef.value)
            isLoaded.value = true
          }}
          class={[styles.container, 'musicIframe']}
          frameborder="0"
          src={src}
        ></iframe>
        <div class={styles.skeletonWrap}>
          <Skeleton class={styles.skeleton} row={8} />
        </div>
      </div>
    )
  }
})
