import { defineComponent, ref, watch } from 'vue';
import styles from './index.module.less';
import qs from 'query-string';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { Skeleton } from 'vant';

export default defineComponent({
  name: 'tempo-item',
  props: {
    pageVisibility: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    dataJson: {
      type: String,
      default: ''
    }
  },
  emits: ['setIframe'],
  setup(props, { emit }) {
    const iframeRef = ref();
    const isLoading = ref(false);
    const isLoaded = ref(false);

    /** 页面显示和隐藏 */
    watch(
      () => props.pageVisibility,
      value => {
        if (value == 'hidden') {
          isLoading.value = false;
        }
        if (value == 'hidden' && props.show) {
          iframeRef.value?.contentWindow?.postMessage(
            { api: 'setPlayState' },
            '*'
          );
        }
      }
    );
    // 是否显示当前曲谱
    watch(
      () => props.show,
      val => {
        if (!val) {
          iframeRef.value?.contentWindow?.postMessage(
            { api: 'setPlayState' },
            '*'
          );
        }
      }
    );

    const Authorization = storage.get(ACCESS_TOKEN);
    const src = `${location.origin}/classroom-app/#/tempo-practice?dataJson=${props.dataJson}&Authorization=${Authorization}&modeType=courseware`;
    return () => (
      <div class={styles.tempoItem}>
        <iframe
          ref={iframeRef}
          onLoad={(e: Event) => {
            emit('setIframe', iframeRef.value);
            isLoaded.value = true;
          }}
          class={[styles.container]}
          frameborder="0"
          src={src}></iframe>
      </div>
    );
  }
});
