import { defineComponent, ref, nextTick, onMounted, watch } from 'vue'
import styles from './musicScore.module.less'
import qs from 'query-string'
import OEmpty from '@/components/o-empty'

export default defineComponent({
  name: 'musicScore',
  props: {
    music: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['setIframe'],
  setup(props, { emit }) {
    const iframeRef = ref()
    const renderError = ref(false)
    const renderSuccess = ref(false)
    const Authorization = sessionStorage.getItem('Authorization') || ''
    const origin = /(localhost|192)/.test(location.host)
      ? 'https://ponline.colexiu.com' //'http://localhost:3000' ////
      : location.origin
    const query = qs.stringify({
      id: props.music.content,
      modelType: 'practice',
      headerHeight: 32,
      Authorization: Authorization
    })
    let src = `${origin}/orchestra-music-score/?` + query
    const checkView = () => {
      fetch(src)
        .then(() => {
          renderSuccess.value = true
          renderError.value = false
        })
        .catch((err) => {
          renderError.value = true
        })
    }
    watch(props.music, () => {
      if (renderSuccess.value) return
      renderError.value = false
      if (props.music.display) {
        checkView()
      }
    })

    return () => (
      <div class={styles.musicScore}>
        {renderError.value ? (
          <div class={styles.errorModel}>
            <OEmpty type="network" tips="请检查网络环境" />
          </div>
        ) : (
          <iframe
            ref={iframeRef}
            onLoad={(e: Event) => {
              emit('setIframe', iframeRef.value)
            }}
            class={[styles.container, 'musicIframe']}
            frameborder="0"
            src={src}
          ></iframe>
        )}
      </div>
    )
  }
})
