import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
import styles from './index.module.less';
import { useUserStore } from '/src/store/modules/users';
import { NButton, NSpace, NSpin } from 'naive-ui';
import { iframeDislableKeyboard } from '/src/utils';

export default defineComponent({
  name: 'source-rhythm',
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const iframeRef = ref();
    const loading = ref(true);
    let src = `${origin}/classroom-app/#/tempo-practice?v=${Date.now()}&Authorization=${
      userStore.getToken
    }&platform=modal`;
    if (/(localhost)/.test(location.host)) {
      src = `https://test.kt.colexiu.com/classroom-app/#/tempo-practice?v=${Date.now()}&Authorization=${
        userStore.getToken
      }&platform=modal`;
    }

    // emit('confirm');
    const onSubmit = () => {
      iframeRef.value?.contentWindow?.postMessage(
        { api: 'getTempoSetting' },
        '*'
      );
    };

    const iframeHandle = (ev: MessageEvent) => {
      if (ev.data?.api === 'getTempoSetting') {
        const data = ev.data.data ? JSON.parse(ev.data.data) : {};
        emit('confirm', {
          dataJson: JSON.stringify(data.setting),
          coverImg: 'https://oss.dayaedu.com/ktqy/171013700931689a322a6.png'
        });
      }
    };
    onMounted(() => {
      window.addEventListener('message', iframeHandle);
    });

    onUnmounted(() => {
      window.removeEventListener('message', iframeHandle);
    });

    return () => (
      <div class={styles.sourceRhythm}>
        <NSpin show={loading.value}>
          <iframe
            ref={iframeRef}
            onLoad={(val: any) => {
              // emit('setIframe', iframeRef.value);
              // isLoaded.value = true;
              loading.value = false;
              iframeDislableKeyboard(val.target);
            }}
            class={[styles.container, 'musicIframe']}
            frameborder="0"
            src={src}></iframe>

          <NSpace class={styles.btnGroup} justify="center">
            <NButton round onClick={() => emit('close')}>
              取消
            </NButton>
            <NButton round type="primary" onClick={onSubmit}>
              确认添加
            </NButton>
          </NSpace>
        </NSpin>
      </div>
    );
  }
});
