import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import styles from "./index.module.less"
import { musicSheetAddMix } from '../../../api'
import { useMessage } from 'naive-ui'

export default defineComponent({
  name: 'musiceBeatTime',
  props: {
    id: {
      type: String
    }
  },
  emits: ['close'],
  setup(props, {emit}) {
    const message = useMessage()
    onMounted(() => {
      window.addEventListener('message', handleBeatRes)
    })

    onUnmounted(() => {
      window.removeEventListener('message', handleBeatRes)
    })
    function handleBeatRes(res: MessageEvent) {
      const data = res.data
      if (data?.api === 'webApi_beatTimes') {
        iframeShow.value = false
        handleBeatTimes(data)
      }
    }
    async function handleBeatTimes(data:any){
      try {
        const { beatTime, singBeatTime, mingBeatTime} = JSON.parse(data.data)
        await musicSheetAddMix({
          id: props.id,
          playTimeList: beatTime,
          singTimeList: singBeatTime,
          solmizationTimeList: mingBeatTime
        })
        message.success('节拍器生成成功')
        emit("close")
      }catch (err){
        console.log('🚀 ~ 音频合成失败', err)
        message.error('节拍器生成失败')
        emit("close")
      }
    }
    const iframeShow = ref(true)
    const userStore = useUserStore()
    const token = userStore.getToken
    const apiUrls = {
      'dev': 'https://dev.kt.colexiu.com',
      'test': 'https://test.lexiaoya.cn',
      'online': 'https://mec.colexiu.com'
    }
    const environment = location.origin.includes('//dev') ? 'dev' : location.origin.includes('//test') ? 'test' : location.origin.includes('//mec.colexiu') ? 'online' : 'dev'
    const apiUrl = apiUrls[environment]
    const prefix = /(localhost|192)/.test(location.host) ? 'https://dev.kt.colexiu.com/' : apiUrl
    let src = prefix + `/instrument/?_t=${Date.now()}&id=${props.id}&Authorization=${token}&isCbs=true&isbeatTimes=true&musicRenderType=staff`
    //let src = "http://192.168.3.122:3000/instrument.html" + `?_t=${Date.now()}&id=${props.id}&Authorization=${token}&isCbs=true&isbeatTimes=true&musicRenderType=staff`
    return () => (
      <div class={styles.musiceBeatTime}>
        <div class={styles.tit}>节拍器音频生成中...</div>
        {
          iframeShow.value && <iframe class={styles.iframe} width={'667px'} height={'375px'} frameborder="0" src={src}></iframe>
        }
      </div>
    )
  }
})
