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';

export function vaildMusicScoreUrl() {
  const url: string = window.location.hostname;
  let returnUrl = '';
  if (/localhost/.test(url)) {
    //本地环境
    returnUrl = 'https://test.kt.colexiu.com';
  } else if (/test/.test(url)) {
    // dev 环境
    returnUrl = 'https://test.kt.colexiu.com';
  } else if (/dev/.test(url)) {
    returnUrl = 'https://dev.kt.colexiu.com';
  } else {
    returnUrl = 'https://mec.colexiu.com';
  }
  return returnUrl;
}

export default defineComponent({
  name: 'tempo-item',
  props: {
    pageVisibility: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    activeModel: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      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',
              data: {
                code: props.item.content
              }
            },
            '*'
          );
        }
      }
    );

    const Authorization = storage.get(ACCESS_TOKEN);
    // const src = `${location.origin}/classroom-app/#/tempo-practice?dataJson=${props.dataJson}&Authorization=${Authorization}&modeType=courseware`;
    let src = `${vaildMusicScoreUrl()}/instrument/#/view-figner?Authorization=${Authorization}&code=${
      props.item.content
    }&type=listenMode&linkSource=class&isPreView=true`;
    if (/(localhost|192)/.test(location.host)) {
      src = `https://test.kt.colexiu.com/instrument/#/view-figner?Authorization=${Authorization}&code=${props.item.content}&type=listenMode&linkSource=class&isPreView=true`;
    }

    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>
    );
  }
});
