import { defineComponent, onMounted, onUnmounted, ref, watch } from 'vue';
import { NSkeleton } from 'naive-ui';
import styles from './musicScore.module.less';
import { usePageVisibility } from '@vant/use';
import { useUserStore } from '/src/store/modules/users';

export default defineComponent({
  name: 'musicScore',
  props: {
    music: {
      type: Object,
      default: () => ({})
    },
    activeModel: {
      type: Boolean
    },
    /** 当前是否为选中状态 */
    activeStatus: {
      type: Boolean
    }
  },
  emits: ['setIframe'],
  setup(props, { emit }) {
    const userStore = useUserStore();
    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 origin = /(localhost|192)/.test(location.host)
      ? 'https://test.lexiaoya.cn/instrument'
      : // 'http://localhost:3000/instrument.html'
        location.origin + '/instrument';
    const src = `${origin}?v=${+new Date()}&showGuide=true&platform=pc&zoom=1.2&modelType=practise&id=${
      props.music.content
    }&Authorization=${userStore.getToken}`;
    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();
        }
      }
    );

    // 去云教练完整版
    // const gotoAccomany = () => {
    //   if (isLoading.value) return;
    //   if (!browserInfo.ios) {
    //     isLoading.value = true;
    //   }
    //   // const parmas = qs.stringify({
    //   //   id: props.music.content
    //   // });
    //   // let src = `${location.origin}/orchestra-music-score/?` + parmas
    //   const src = `https://test.lexiaoya.cn/orchestra-music-score/?_t=1687590480955&id=11707&modelType=practice&modeType=json&Authorization=bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIl0sImNsaWVudFR5cGUiOiJCQUNLRU5EIiwidXNlcl9uYW1lIjoiMTgxNjI4NTU4MDAiLCJzY29wZSI6WyJhbGwiXSwidXNlcklkIjoiMTAwMDE0OSIsImF1dGhvcml0aWVzIjpbIjE4MTYyODU1ODAwIl0sImp0aSI6IjY0MzA2NjllLTE5NGItNDk3Yy1hMDQ5LWM4YWUxMGU0NDNiOCIsImNsaWVudF9pZCI6ImptZWR1LWJhY2tlbmQifQ.aeJ0o-lSfx1Ok-YptZuC-AUY6M7k3LK9rr0Bmx7sj81pPt2HDiDqeT2PuriYdJacxWnxboyhdG_lwU0QK-W-vON97c45NQpSEFLVpZ0m1xdIqwllwf20xhyj5YJwdOFUzxf1TNEfGsHZg66J7wEJQBSzlmQwcxmEE5lqLVD8o_3f2SBqnWCj9RqE4air7FUemllMnZiu8HsS-TKtLDaGa_XW8Yb_Zjzzz6r5UcYNI-C1uKPXg18o1dhHBJ8O-Pl0U8WivPRub_opvO2NSn5L9YtPt7Dd50UeSwaIOdMeCGdii1bg__h77Stek1_5IaZLYkoo2gvmUA-xk09TwCQBpA`;
    //   postMessage(
    //     {
    //       api: 'openAccompanyWebView',
    //       content: {
    //         url: src,
    //         orientation: 0,
    //         isHideTitle: true,
    //         statusBarTextColor: false,
    //         isOpenLight: true
    //       }
    //     },
    //     () => {
    //       if (browserInfo.ios) {
    //         isLoading.value = true;
    //       }
    //     }
    //   );
    // };

    watch(
      () => props.activeModel,
      () => {
        if (iframeRef.value.contentWindow && props.activeStatus) {
          // console.log(
          //   iframeRef.value.contentWindow,
          //   props.activeModel,
          //   'iframeRef'
          // );
          iframeRef.value.contentWindow.postMessage(
            {
              api: 'attendClassBarStatus',
              hideMenu: !props.activeModel
            },
            '*'
          );
        }
      }
    );

    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>
        {isLoaded.value && (
          <div class={styles.skeletonWrap}>
            <div>
              <NSkeleton text repeat={8} />
            </div>
          </div>
        )}
      </div>
    );
  }
});
