import { Button, Popup, Progress, Toast } from 'vant'
import { defineComponent } from 'vue'
import state from '/src/pages/detail/state'
import classnames from 'classnames'
import qs from 'query-string'
import appstate from '/src/state'
// import closeIcon from './icons/close.svg'
import closeIcon2 from './icons/close2.svg'
import ErjiIcon from './icons/erji.png'
import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
import TickPlayer from '/src/components/tick/player'
import TuningPopup from '/src/pages/detail/tuning-popup'
import {
  getBoundingBoxByverticalNote,
  getNoteBySlursStart,
  getNoteByMeasuresSlursStart,
  getParentNote,
} from '/src/pages/detail/helpers'
import detailState from '/src/pages/detail/state'
import {
  postMessage,
  listenerMessage,
  removeListenerMessage,
  IPostMessage,
  CallBack,
} from '/src/helpers/native-message'
import SettingState from '/src/pages/detail/setting-state'
import { getLeveByScore, getLeveByScoreMeasure } from './helper'
import styles from './index.module.less'
import { browser, getRequestHostname } from '/src/helpers/utils'
import CheckDelayPopup from '../CheckDelayPopup'
import Headphone, { HeadphoneData } from '../Headphone'
import PhoneTip from '../PhoneTip'

const browserInfo = browser()

/** 初始化评测音频 */
export const evaluatCreateMusicPlayer = () => {
  return new Promise((resolve) => {
    // 初始化曲谱音频 和效音音频
    postMessage(
      {
        api: 'createMusicPlayer',
        content: {
          musicSrc: runtime.songs.background || runtime.songs.music, // 曲谱音频url
          tuneSrc: 'https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3', //效音音频url
        },
      },
      () => {
        if (browserInfo.ios) {
          resolve(true)
        }
      }
    )
    // 安卓不需要
    if (!browserInfo.ios) {
      resolve(true)
    }
  })
}

let player: any = null

let backtime = 0

let synced = false

/**
 * 木管(长笛 萨克斯 单簧管)乐器一级的2、3、6测评要放原音音频
 * 铜管乐器一级的1a，1b，5，6测评要放原音音频
 */
const getMusicMode = (): RuntimeUtils.IMode => {
  const muguan = [2, 4, 5, 6]
  const tongguan = [12, 13, 14, 15, 17]
  if (
    muguan.includes(state.subjectId) &&
    (state.activeDetail?.examSongName || '').search(/[^\u0000-\u00FF](1-2|1-3|1-6)/gi) > -1
  ) {
    return 'music'
  }
  if (
    tongguan.includes(state.subjectId) &&
    (state.activeDetail?.examSongName || '').search(/[^\u0000-\u00FF](1-1-1|1-1-2|1-5|1-6)/gi) > -1
  ) {
    return 'music'
  }
  if (state.subjectId == 23 || state.subjectId == 113) {
    return 'music'
  }
  return 'background'
}

export const resetPlayer = () => {
  if (player) {
    player.stop()
    RuntimeUtils.clearIntervalTimeline()
  }
}

/** 监听评测弹窗是否隐藏保存演奏按钮 */
const hideComplexButton = (callback: CallBack, listen?: boolean) => {
  if (listen) {
    listenerMessage('hideComplexButton', callback)
  } else {
    removeListenerMessage('hideComplexButton', callback)
  }
}

// 隐藏存演奏按钮
const handleComplexButton = (res?: IPostMessage) => {
  console.log('监听是否隐藏上传云端按钮', res)
  if (res?.content) {
    const { header, body } = res.content
    detailState.isHideEvaluatReportSaveBtn = true
  }
}

export default defineComponent({
  name: 'evaluating',
  data() {
    return {
      oldMode: state.mode,
      evaluating: false,
      erjiShow: false,
      res: null as any,
      player: new TickPlayer(),
      starting: false,
      timeInfos: this.formatTimes(),
      // isStrike: state.subjectId === 23,
      activeMode: getMusicMode(),
      startloading: false,
      endloading: false,
      erjiRes: false,
      erjiClicked: false,
      checkStatus: false,
      alertStatus: false,
      shareStatus: false,
      // trend: -1,
      frequency: -1,
      shareLoadedPngData: null as null | string,
      isSaveVideo: SettingState.sett.camera && SettingState.eva.save,
      tuningStatus: false,
      /** 延迟数据 */
      delayData: {
        /** 是否强制检测 */
        isForce: true,
        /** 弹窗 */
        open: false,
        /** 延迟次数 */
        count: 0,
        /** 延迟时间 */
        time: 0,
        /** 耳机状态 */
        erji: false,
        /** 检测状态 */
        checkStatus: 'init' as 'init' | 'ing' | 'error',
        step: 1,
      },
    }
  },
  computed: {
    playUrl(): string {
      return runtime.songs.background || (runtime.songs.music as string)
    },
  },
  methods: {
    startPlay() {
      console.log('连接服务成功,开始播放', new Date().getTime() - runtime.clickTime)
      synced = false
      if (!SettingState.eva.mute) {
        RuntimeUtils.changeAllMode()
      } else {
        RuntimeUtils.changeMode(getMusicMode())
      }
      // RuntimeUtils.changeSpeed(90)
      RuntimeUtils.setPlayState()
    },
    async setPlayer() {
      // alert('start:' + this.startloading + ',end:' + this.endloading + ',res:' + !this.res)
      if (this.endloading || this.startloading) {
        return
      }
      this.startloading = true
      runtime.clickTime = new Date().getTime()
      RuntimeUtils.resetPlayStatus()
      runtime.evaluatingTips = false
      if (state.isPauseRecording) {
        this.evaluating = false
        this.startloading = false
        this.startPlay()
        return
      }
      state.evaluatings = {}
      if (this.starting === true) {
        return
      }
      RuntimeUtils.setCurrentTime(0)
      this.starting = true
      const hint = Toast({
        duration: 0,
        message: '服务连接中...',
        type: 'loading',
      })
      try {
        await this.connect()
        hint.close()
        this.startPlay()
        setTimeout(() => {
          Toast.clear()
        })
      } catch (error) {
        this.clearStartStatus()
        Toast.clear()
      }
      this.startloading = false
      // setTimeout(() => {
      //   // Toast.clear()
      // })
    },
    connect() {
      const behaviorId = sessionStorage.getItem('behaviorId') || undefined
      return new Promise((resolve, reject) => {
        const rate = runtime.speed / state.baseSpeed //1
        const content = {
          musicXmlInfos: this.timeInfos,
          id: this.$route.params.id,
          subjectId: state.subjectId,
          detailId: state.activeDetail?.id,
          examSongId: state.activeDetail?.examSongId,
          xmlUrl: state.activeDetail?.xmlUrl,
          partIndex: state.partIndex,
          behaviorId,
          platform: 'WEB',
          clientId: 'student',
          speed: runtime.speed,
          heardLevel: SettingState.eva.difficulty,
          beatLength: Math.round((RuntimeUtils.getFixTime(state.times[0].beatSpeed) * 1000) / rate),
        }
        const apiPath = getRequestHostname()
        if (apiPath === '/api-student') {
          content.clientId = 'student'
        } else if (apiPath === '/api-teacher') {
          content.clientId = 'teacher'
        } else {
          content.clientId = 'education'
        }
        if (browserInfo.android) {
          content.platform = 'ANDROID'
        }
        if (browserInfo.ios) {
          content.platform = 'IOS'
        }
        postMessage(
          {
            api: 'startEvaluating',
            content: content,
          },
          (data) => {
            if (data?.content?.reson) {
              reject(data)
              this.cancelEvaluating(data)
            } else {
              resolve(data)
              RuntimeUtils.setCaptureMode()
            }
          }
        )
      })
    },
    // 开始通知录制是监听播放行为触发
    async start() {
      if (this.evaluating || state.activeTick > -1) {
        return
      }
      if (state.isPauseRecording) {
        postMessage(
          {
            api: 'resumeRecording',
          },
          () => {
            this.evaluating = true
            state.isPauseRecording = false
            RuntimeUtils.setCaptureMode()
          }
        )
        return
      }
      console.log('开始录音', new Date().getTime())
      postMessage(
        {
          api: 'startRecording',
        },
        () => {
          console.log('开始录音回调时间', new Date().getTime())
          backtime = new Date().getTime()
          this.evaluating = true
          console.log('midiUrl', detailState.activeDetail?.midiUrl)
          if (detailState.activeDetail?.midiUrl) {
            setTimeout(() => {
              this.sendOffsetTime(0)
            }, 220)
          }
        }
      )
    },
    sendOffsetTime(offsetTime: number) {
      postMessage(
        {
          api: 'proxyServiceMessage',
          content: {
            header: {
              commond: 'audioPlayStart',
              type: 'SOUND_COMPARE',
            },
            body: {
              offsetTime,
            },
          },
        },
        () => {
          backtime = 0
        }
      )
    },
    timeupdate() {
      console.log('播放事件被触发', this.playUrl, this.evaluating, !synced)
      if (this.playUrl && !synced) {
        const nowTime = new Date().getTime()
        console.log('第一次播放时间', nowTime)
        synced = true
        const time = runtime.audiosInstance?.audios[this.playUrl].currentTime
        console.log('已播放时长: ', time * 1000)
        console.log('不减掉已播放时间: ', nowTime - backtime)
        const delayTime = nowTime - backtime - time * 1000
        console.log('真正播放延迟', delayTime)
        // 蓝牙耳机延迟一点发送消息确保在录音后面
        setTimeout(() => {
          this.sendOffsetTime(delayTime)
        }, 220)
        // postMessage({
        //   api: 'proxyMessage',
        //   content: {
        //     offsetTime: delayTime
        //   }
        // })
      }
    },
    stop() {
      // alert('stop' + this.endloading)
      if (this.endloading) {
        return
      }
      this.endloading = true
      this.starting = false
      resetPlayer()
      player?.dispose()
      player = null
      RuntimeUtils.resetPlayStatus()
      RuntimeUtils.clearIntervalTimeline()
      RuntimeUtils.setCurrentTime(0)
      Toast({
        duration: 0,
        message: '评分中...',
        type: 'loading',
      })
      const route = (this as any).$route
      postMessage(
        {
          api: 'endEvaluating',
          content: {
            musicScoreId: route.params.id,
          },
        },
        (evt) => {
          this.evaluating = false
          RuntimeUtils.setCaptureMode()
        }
      )
    },
    close() {
      runtime.evaluatingStatus = false
      this.retest()
    },
    cancel(hint?: string) {
      resetPlayer()
      RuntimeUtils.resetPlayStatus()
      RuntimeUtils.clearIntervalTimeline()
      RuntimeUtils.event.emit(
        'updatePlayTimeSuccess',
        {
          totalPlayTimeOfCurrentDate: this.res?.totalPlayTimeOfCurrentDate,
        },
        {
          form: 'evaluation',
        }
      )
      this.res = null
      player?.dispose()
      player = null
      this.starting = false
      this.evaluating = false
      // 断开后退出评测模式
      runtime.evaluatingStatus = false
      setTimeout(() => {
        Toast.clear()
        if (hint) {
          Toast(hint)
        }
      })
      RuntimeUtils.clearIntervalTimeline()
    },
    retest(hint?: string) {
      RuntimeUtils.resetPlayStatus()
      RuntimeUtils.event.emit(
        'updatePlayTimeSuccess',
        {
          totalPlayTimeOfCurrentDate: this.res?.totalPlayTimeOfCurrentDate,
        },
        {
          form: 'evaluation',
        }
      )
      this.res = null
      player?.dispose()
      player = null
      this.starting = false
      this.evaluating = false
      setTimeout(() => {
        Toast.clear()
        if (hint) {
          Toast(hint)
        }
      })
      RuntimeUtils.clearIntervalTimeline()
    },
    clearStartStatus() {
      console.log('clearStartStatus')
      this.starting = false
      this.evaluating = false
    },
    backDetail() {
      this.close()
    },
    formatTimes() {
      let ListenMode = false
      let dontEvaluatingMode = false
      let skip = false
      const datas = []
      for (let index = 0; index < state.times.length; index++) {
        const item = state.times[index]
        const note = getNoteByMeasuresSlursStart(item)
        // console.log(item.nodeElement)
        const rate = runtime.speed / state.baseSpeed //1
        // const fixtime = 0
        const start = item.sourceRelativeTime || item.relativeTime
        const end = item.sourceRelaEndtime || item.relaEndtime
        const isStaccato = note.isStaccato
        const noteRate = isStaccato ? 0.5 : 1
        if (note.formatLyricsEntries.contains('Play') || note.formatLyricsEntries.contains('Play...')) {
          ListenMode = false
        }
        if (note.formatLyricsEntries.contains('Listen')) {
          ListenMode = true
        }
        if (note.formatLyricsEntries.contains('纯律结束')) {
          dontEvaluatingMode = false
        }
        if (note.formatLyricsEntries.contains('纯律')) {
          dontEvaluatingMode = true
        }
        const nextNote = state.times[index + 1]
        // console.log("noteinfo", note.noteElement.isRestFlag && !!note.stave && !!nextNote)
        if (skip && (note.stave || !note.noteElement.isRestFlag || (nextNote && !nextNote.noteElement.isRestFlag))) {
          skip = false
        }
        if (note.noteElement.isRestFlag && !!note.stave && !!nextNote && nextNote.noteElement.isRestFlag) {
          skip = true
        }
        // console.log(note.measureOpenIndex, item.measureOpenIndex, note)
        // console.log("skip", skip)
        const data = {
          timeStamp: (start * 1000) / rate,
          duration: ((end * 1000) / rate - (start * 1000) / rate) * noteRate,
          frequency: item.noteElement?.pitch?.frequency || -1,
          nextFrequency: item.noteElement?.pitch?.nextFrequency || -1,
          prevFrequency: item.noteElement?.pitch?.prevFrequency || -1,
          // 重复的情况index会自然累加,render的index是谱面渲染的index
          measureIndex: note.measureOpenIndex,
          measureRenderIndex: note.noteElement.sourceMeasure.measureListIndex,
          // dontEvaluating: ListenMode,
          dontEvaluating: ListenMode || dontEvaluatingMode,
          musicalNotesIndex: item.i,
          denominator: note.noteElement?.Length.denominator,
        }
        datas.push(data)
      }
      return datas
    },
    cancelEvaluating(data?: IPostMessage) {
      this.starting = false
      if (data?.content.reson) {
        this.cancel(data?.content.reson)
      }
    },
    // sendResult(evt?: IPostMessage) {
    //   console.log('sendResult', evt)
    //   if (evt?.content) {
    //     const data = evt?.content?.body
    //     if (evt?.content.header.commond === 'overall') {
    //       Toast.clear()
    //       this.res = data
    //       this.endloading = false
    //       RuntimeUtils.event.emit('onEvaluationResult', data)
    //     } else if (evt?.content.header.commond === 'checkDone') {
    //       this.checkStatus = true
    //       // postMessage({
    //       //   api: 'endSoundCheck'
    //       // })
    //     } else if (evt?.content.header.commond === 'checking') {
    //       // this.trend = evt?.content?.body?.trend
    //       this.frequency = evt?.content?.body?.frequency
    //     } else {
    //       const getBeforeNote = (index: number) => {
    //         while (index >= 0) {
    //           const item = state.times[index]
    //           if (item.stave) {
    //             return item
    //           }
    //           index--
    //         }
    //       }
    //       const setEvaluatings = (
    //         note: any,
    //         data: any,
    //         dontTransition = false
    //       ) => {
    //         const startNote = getBoundingBoxByverticalNote(note)
    //         state.evaluatings = {
    //           ...state.evaluatings,
    //           [startNote.measureIndex]: {
    //             ...startNote,
    //             ...getLeveByScoreMeasure(data.score),
    //             score: data.score,
    //             dontTransition,
    //           },
    //         }
    //       }

    //       for (let index = 0; index < state.times.length; index++) {
    //         let time = state.times[index]
    //         if (
    //           data.measureRenderIndex ==
    //           time.noteElement.sourceMeasure.measureListIndex
    //         ) {
    //           if (!time.stave) {
    //             const ntime = getBeforeNote(index)
    //             // console.log('ntime', ntime)
    //             if (ntime) {
    //               time = ntime
    //             }
    //           }
    //           // if (state.evaluatings[data.measureRenderIndex]) {
    //           //   // 重复问题，老数据移除
    //           //   state.evaluatings = {
    //           //     ...state.evaluatings,
    //           //     [data.measureRenderIndex]: undefined
    //           //   }
    //           // }
    //           // console.log('sendResult', data, time, time.noteElement.tie)

    //           // const startNote = getBoundingBoxByverticalNote(time)
    //           // const endNote = getBoundingBoxByverticalNote(getNoteByMeasuresSlursStart(time))//getParentNote

    //           // if (!time.noteElement.tie) continue
    //           // for (const item of time.noteElement.tie.notes) {
    //           //   const note = getParentNote(item)
    //           //   if (!note) continue
    //           //   const startNote = getBoundingBoxByverticalNote(note)
    //           //   state.evaluatings = {
    //           //     ...state.evaluatings,
    //           //     [startNote.measureIndex]: {
    //           //       ...startNote,
    //           //       ...getLeveByScoreMeasure(data.score),
    //           //       score: data.score,
    //           //       dontTransition: item !== time.noteElement.tie.StartNote,
    //           //     },
    //           //   }
    //           // }

    //           if (!time.noteElement.tie) {
    //             setEvaluatings(time, data)
    //           } else {
    //             for (const item of time.noteElement.tie.notes) {
    //               const note = getParentNote(item)
    //               if (!note) continue
    //               setEvaluatings(
    //                 note,
    //                 data,
    //                 item !== time.noteElement.tie.StartNote
    //               )
    //               // const startNote = getBoundingBoxByverticalNote(note)
    //               // state.evaluatings = {
    //               //   ...state.evaluatings,
    //               //   [startNote.measureIndex]: {
    //               //     ...startNote,
    //               //     ...getLeveByScoreMeasure(data.score),
    //               //     score: data.score,
    //               //     dontTransition: item !== time.noteElement.tie.StartNote,
    //               //   },
    //               // }
    //             }
    //           }

    //           // if (startNote.measureIndex !== endNote.measureIndex) {
    //           //   state.evaluatings = {
    //           //     ...state.evaluatings,
    //           //     [endNote.measureIndex]: {
    //           //       ...endNote,
    //           //       ...getLeveByScoreMeasure(data.score),
    //           //       score: data.score,
    //           //       dontTransition: true
    //           //     },
    //           //   }
    //           // }
    //           break
    //         }
    //       }
    //       // for (const time of state.times) {
    //       //   if (data.measureRenderIndex == time.noteElement.sourceMeasure.measureListIndex) {
    //       //     if (state.evaluatings[data.measureRenderIndex]) return
    //       //     const startNote = getBoundingBoxByverticalNote(time)
    //       //     const endNote = getBoundingBoxByverticalNote(getNoteBySlursStart(time, true, 'end'))
    //       //     state.evaluatings = {
    //       //       ...state.evaluatings,
    //       //       [startNote.measureIndex]: {
    //       //         ...startNote,
    //       //         ...getLeveByScoreMeasure(data.score),
    //       //         score: data.score,
    //       //       },
    //       //     }
    //       //     if (startNote.measureIndex !== endNote.measureIndex) {
    //       //       state.evaluatings = {
    //       //         ...state.evaluatings,
    //       //         [endNote.measureIndex]: {
    //       //           ...endNote,
    //       //           ...getLeveByScoreMeasure(data.score),
    //       //           score: data.score,
    //       //           dontTransition: true
    //       //         },
    //       //       }
    //       //     }
    //       //     break
    //       //   }
    //       // }
    //     }
    //   }
    // },

    sendResult(evt?: IPostMessage) {
      console.log('sendResult', evt)
      if (evt?.content) {
        const data = evt?.content?.body
        if (evt?.content.header.commond === 'overall') {
          detailState.isHideEvaluatReportSaveBtn = false
          Toast.clear()
          this.res = data
          this.endloading = false
          RuntimeUtils.event.emit('onEvaluationResult', data)
        } else if (evt?.content.header.commond === 'checkDone') {
          this.checkStatus = true
        } else if (evt?.content.header.commond === 'checking') {
          this.frequency = evt?.content?.body?.frequency
        } else if (evt?.content.header.commond === 'recordEnd') {
          if (this.delayData.checkStatus !== 'ing') return
          this.delayData.count++
          if (this.delayData.count >= 2) {
            this.handleToggleTune('finishTune')
            return
          }
          setTimeout(() => {
            this.startTune()
          }, 100)
        } else {
          const getBeforeNote = (index: number) => {
            while (index >= 0) {
              const item = state.times[index]
              if (item.stave) {
                return item
              }
              index--
            }
          }
          const setEvaluatings = (note: any, data: any, dontTransition = false) => {
            const startNote = getBoundingBoxByverticalNote(note)
            state.evaluatings = {
              ...state.evaluatings,
              [startNote.measureIndex]: {
                ...startNote,
                ...getLeveByScoreMeasure(data.score),
                score: data.score,
                dontTransition,
              },
            }
          }

          for (let index = 0; index < state.times.length; index++) {
            let time = state.times[index]
            if (data.measureRenderIndex == time.noteElement.sourceMeasure.measureListIndex) {
              if (!time.stave) {
                const ntime = getBeforeNote(index)
                // console.log('ntime', ntime)
                if (ntime) {
                  time = ntime
                }
              }

              if (!time.noteElement.tie) {
                setEvaluatings(time, data)
              } else {
                for (const item of time.noteElement.tie.notes) {
                  const note = getParentNote(item)
                  if (!note) continue
                  setEvaluatings(note, data, item !== time.noteElement.tie.StartNote)
                }
              }
              break
            }
          }
        }
      }
    },
    setWiredStatus(res?: IPostMessage) {
      this.erjiShow = !res?.content.checkIsWired
      this.tuningStatus = true
      if (!this.erjiShow) {
        this.erjiClicked = true
        this.tuningStatus = true
      }
    },
    endevent(evt: Event) {
      console.log((evt.target as HTMLAudioElement)?.src, this.playUrl)
      if ((evt.target as HTMLAudioElement)?.src === this.playUrl) {
        this.stop()
      }
    },
    viewReport() {
      // this.$router.push('/report')
      postMessage({
        api: 'openWebView',
        content: {
          // url: location.origin + '/accompany/#/report/',
          url: location.origin + '/accompany/#/report/' + this.res?.recordId || '',
          orientation: 0,
          isHideTitle: true, // 此处兼容安卓，意思为隐藏全部头部
          statusBarTextColor: false,
          isOpenLight: true,
        },
      })
    },
    closeErji() {
      this.erjiShow = false
      this.erjiClicked = true
    },
    sendUploadMessage(res?: IPostMessage) {
      postMessage({
        api: 'proxyServiceMessage',
        content: {
          header: {
            commond: 'videoUpload',
            status: 200,
            type: 'SOUND_COMPARE',
          },
          body: {
            filePath: res?.content?.filePath,
            recordId: this.res?.recordId,
          },
        },
      })
    },
    videoUpdate() {
      if (this.isSaveVideo) {
        postMessage(
          {
            api: 'videoUpdate',
          },
          (res) => {
            this.alertStatus = false
            if (res?.content) {
              if (res.content.type === 'error') {
                Toast(res.content.message)
                return
              }
              this.sendUploadMessage(res)
            }
          }
        )
      } else {
        this.alertStatus = false
        this.sendUploadMessage()
        Toast('上传成功')
      }
    },
    shareLoaded(evt: Event) {
      const el = evt.target as HTMLIFrameElement
      if (el) {
        // @ts-ignore
        el.contentWindow.setPng = (data: string) => {
          this.shareLoadedPngData = data
        }
      }
    },
    closeShare() {
      this.shareStatus = false
      this.shareLoadedPngData = null
    },
    shareNext() {
      if (!this.shareLoadedPngData) return
      postMessage(
        {
          api: 'shareAchievements',
          content: {
            title: '分享我的乐器练习进度，一起见证我的成长！',
            desc: '晒一下我的评测分数，快来“云练习”上和我PK一下吧！',
            image: this.shareLoadedPngData,
            video: '',
            type: 'image',
          },
        },
        (res) => {
          if (res?.content?.status) {
            this.shareStatus = false
          }
          if (!res?.content?.status && res?.content?.message) {
            Toast(res?.content?.message)
          }
        }
      )
    },
    getShareUrl() {
      const data: any = {
        name: appstate.user?.student?.username || '',
        subjectName: (appstate.user?.student?.subjectNames || '').split(',')[0] || '',
        avatar: encodeURIComponent(appstate.user?.student?.avatar || ''),
        score: this.res?.score || 0,
        examSongName: detailState.activeDetail?.examSongName || '',
      }
      // if (!this.isStrike) {
      //   data.intonation = this.res?.intonation
      //   data.cadence = this.res?.cadence
      //   data.integrity = this.res?.integrity
      // }
      if (!detailState.isPercussion) {
        data.intonation = this.res?.intonation
        data.cadence = this.res?.cadence
        data.integrity = this.res?.integrity
      }
      // return `${location.origin}/accompany/share-evaluating/index.html?${qs.stringify(data)}`
      return ''
    },

    /** 评测效验 */
    async checkEvaluating() {
      this.delayData.erji = await this.getWiredStatus()
      this.delayData.time = await this.getDeviceDelay()
      // 没有设备延迟数据,显示检测组件,并持续检测耳机状态
      if (!this.delayData.time || this.delayData.isForce) {
        this.delayData.open = runtime.delayCheckFirst && this.$route.query.evaluatingRecord ? false : true
        this.delayData.count = 0
        if (runtime.delayCheckFirst && this.$route.query.evaluatingRecord) {
          this.closeErji()
        }
        return
      }
      this.handleCheckDelayEnd()
    },
    /** 获取设备延迟 */
    getDeviceDelay(): Promise<number> {
      return new Promise((resolve) => {
        const timer = setTimeout(() => {
          resolve(0)
        }, 1000)
        postMessage(
          {
            api: 'getDeviceDelay',
          },
          (res) => {
            const delay = res?.content?.value > 0 ? res?.content?.value : 0
            clearTimeout(timer)
            resolve(delay)
          }
        )
      })
    },
    /** 获取耳机状态 */
    getWiredStatus(): Promise<boolean> {
      return new Promise((resolve) => {
        const timer = setTimeout(() => {
          resolve(false)
        }, 1000)
        postMessage(
          {
            api: 'isWiredHeadsetOn',
          },
          (res) => {
            const checkIsWired = res?.content?.checkIsWired ? true : false
            if (checkIsWired) {
              if (this.delayData.step <= 5) {
                this.delayData.step = 3
              }
            } else {
              if (this.delayData.step === 2 || this.delayData.step === 3) {
                this.delayData.step = 4
              }
            }
            clearTimeout(timer)
            resolve(checkIsWired)
          }
        )
      })
    },
    /** 持续检测耳机状态 */
    checkWiredStatus() {
      console.log('耳机状态', this.delayData.checkStatus)
      // 设备检测结束,停止获取耳机状态
      if (this.delayData.checkStatus !== 'ing' || this.delayData.open === false) {
        return
      }
      setTimeout(async () => {
        this.delayData.erji = await this.getWiredStatus()
        if (this.delayData.erji) {
          this.delayData.count = 0
          this.delayData.time = 0
          this.delayData.checkStatus = 'error'
        }
        this.checkWiredStatus()
      }, 1000)
    },
    /** 开始效音 */
    startTune() {
      // 带了耳机,停止播放效音
      if (this.delayData.erji) return
      this.handleToggleTune('start')
      setTimeout(() => {
        this.handleToggleTune('stop')
      }, 1500)
    },
    /** 设备延迟检测结束 */
    handleCheckDelayEnd() {
      if (this.delayData.erji) {
        this.closeErji()
      } else {
        this.erjiShow = true
        HeadphoneData.toggle()
      }
    },
    /** 切换效音 */
    handleToggleTune(state: 'start' | 'stop' | 'finishTune') {
      if (state === 'start') {
        this.delayData.step = 5
        // 开始效音
        postMessage({
          api: 'startTune',
          content: {
            count: this.delayData.count + '',
          },
        })
      } else if (state === 'stop') {
        // 结束效音，触发时机： 1.监听后台效音返回 2.点击跳过效音或关闭效音
        postMessage({
          api: 'endTune',
        })
      } else if (state === 'finishTune') {
        this.delayData.step = 6
        // 效音完成
        postMessage(
          {
            api: 'finishTune',
          },
          (res) => {
            const result = res?.content?.result //1成功 0失败
            // Toast('检测延迟完成')
            // setTimeout(() => {
            // 	this.delayData.open = false
            // }, 500)
          }
        )
      }
    },
    /** 停止设备延迟检测 */
    handleStopCheckDelay() {
      runtime.delayCheckFirst = true
      this.delayData.open = false
      this.delayData.checkStatus = 'init'
      this.handleToggleTune('stop')
      this.close()
    },
    /** 开始检测设备延迟 */
    async handleStartCheckDelay() {
      if (this.delayData.checkStatus === 'ing') return
      this.delayData.step = 2
      this.delayData.erji = await this.getWiredStatus()
      if (this.delayData.erji) {
        this.delayData.checkStatus = 'error'
        return
      }
      this.delayData.checkStatus = 'ing'
      this.startTune()
      this.checkWiredStatus()
    },
  },
  mounted() {
    if (!SettingState.eva.mute) {
      RuntimeUtils.changeAllMode()
    } else {
      RuntimeUtils.changeMode(getMusicMode())
    }
    state.renderLoading = false
    state.mode = 'evaluating'
    state.sectionStatus = false
    state.section = []
    listenerMessage('cancelEvaluating', this.cancelEvaluating)
    listenerMessage('sendResult', this.sendResult)
    listenerMessage('listenerWiredStatus', this.setWiredStatus)
    listenerMessage('recordStartTime', (res) => {
      console.log('监听时间', res?.content.inteveral, '系统时间', new Date().getTime())
    })
    RuntimeUtils.event.on('stopTick', this.clearStartStatus)
    RuntimeUtils.event.on('next-click', this.stop)
    RuntimeUtils.event.on('ended', this.endevent)
    RuntimeUtils.event.on('tickEnd', this.start)
    // console.log('runtime.songs', runtime.songs)
    runtime.audiosInstance?.audios[this.playUrl]?.addEventListener('play', this.timeupdate)
    runtime.evaluatingTips = true
    postMessage(
      {
        api: 'isWiredHeadsetOn',
      },
      this.setWiredStatus
    )
    hideComplexButton(handleComplexButton, true)
    // 开始效验
    this.checkEvaluating()
  },
  unmounted() {
    state.mode = this.oldMode
    removeListenerMessage('cancelEvaluating', this.cancelEvaluating)
    removeListenerMessage('sendResult', this.sendResult)
    removeListenerMessage('listenerWiredStatus', this.setWiredStatus)
    RuntimeUtils.event.off('stopTick', this.clearStartStatus)
    RuntimeUtils.event.off('next-click', this.stop)
    RuntimeUtils.event.off('ended', this.endevent)
    RuntimeUtils.event.off('tickEnd', this.start)
    runtime.audiosInstance?.audios[this.playUrl]?.removeEventListener('play', this.timeupdate)
    runtime.evaluatingTips = false
    state.evaluatings = {}
  },
  render() {
    const data = getLeveByScore(this.res?.score)
    return (
      <div class={styles.button}>
        {!(this.endloading || this.startloading) && !this.res && this.erjiClicked ? (
          this.evaluating && !state.isPauseRecording ? (
            <Button key="end" color="#01c1b5" round onClick={this.stop} icon="success">
              结束演奏
            </Button>
          ) : state.activeTick === -1 ? (
            <Button key="start" color="#01c1b5" round onClick={this.setPlayer}>
              {state.isPauseRecording ? '继续演奏' : '开始演奏'}
            </Button>
          ) : null
        ) : null}
        {/* {this.erjiClicked && SettingState.sett.tuning && state.subjectId !== 23 ? (
          <TuningPopup checkStatus={this.checkStatus} trend={this.trend}/>
        ) : null} */}
        {this.erjiClicked && SettingState.sett.tuning && !detailState.isPercussion && this.tuningStatus ? (
          <TuningPopup
            checkStatus={this.checkStatus}
            frequency={this.frequency}
            onOpen={() => (this.tuningStatus = true)}
            onClosed={() => (this.tuningStatus = false)}
          />
        ) : null}
        <Popup
          show={this.alertStatus}
          teleport="body"
          class={classnames([styles.fractionContainer, styles.erjiContainer])}
        >
          <div class={styles.fraction} style={{ width: 'calc(1rem * 2 * 3)' }}>
            <div class={styles.title}>提示</div>
            <div class={styles.content}>
              <div class={styles.detail} style={{ flexDirection: 'column' }}>
                <p class={styles.tips}>评测{this.isSaveVideo ? '音视频' : '音频'}是否上传到云端？</p>
              </div>
              <div class={styles.ctrls}>
                <Button color="#F0F0F0" round onClick={() => (this.alertStatus = false)} style={{ color: '#01c1b5' }}>
                  取消
                </Button>
                <Button color="#01c1b5" round onClick={this.videoUpdate} style={{ marginLeft: '10px' }}>
                  确认
                </Button>
              </div>
            </div>
          </div>
        </Popup>
        <Popup
          show={this.shareStatus}
          teleport="body"
          onClickCloseIcon={this.closeShare}
          class={classnames([styles.fractionContainer, styles.erjiContainer])}
        >
          <div class={styles.btns}>
            <div class={styles.sbtn} onClick={this.closeShare}>
              取消
            </div>
            <div
              class={{
                [styles.sbtn]: true,
                [styles.disabled]: !this.shareLoadedPngData,
              }}
              onClick={this.shareNext}
            >
              继续
            </div>
          </div>
          {this.shareStatus ? (
            <iframe class={styles.iframe} src={this.getShareUrl()} onLoad={this.shareLoaded} />
          ) : null}
        </Popup>
        <Popup
          show={this.erjiShow}
          teleport="body"
          closeable
          onClickCloseIcon={this.closeErji}
          class={classnames([styles.fractionContainer, styles.erjiContainer])}
        >
          <div class={styles.fraction} style={{ width: 'calc(1rem * 2 * 3)' }}>
            <div class={styles.title}>提示</div>
            <div class={styles.content}>
              <div class={styles.detail} style={{ flexDirection: 'column' }}>
                <img class={styles.erji} src={ErjiIcon} />
                <p class={styles.tips}>请佩戴耳机以保证测评准确率～</p>
              </div>
              <div class={styles.ctrls}>
                <Button color="#01c1b5" round onClick={this.closeErji}>
                  确认
                </Button>
              </div>
            </div>
          </div>
        </Popup>
        <Popup
          show={!!this.res}
          teleport="body"
          closeIcon={closeIcon2}
          closeable
          class={classnames(styles.fractionContainer, styles.resultContainer, {
            [styles.isPercussion]: detailState.isPercussion,
          })}
          onClickCloseIcon={this.close}
        >
          {this.res ? (
            <div class={styles.fraction}>
              <div class={styles.content}>
                {!detailState.isPercussion ? (
                  <div class={styles.leftContent}>
                    <img src={data.img} style={{ margin: detailState.isPercussion ? 'auto' : '' }} />
                    <div>
                      <span>{this.res?.score}</span>分<br />
                      {data.mome}
                    </div>
                  </div>
                ) : null}
                <div class={styles.headerButton}>
                  <div class={styles.tit}>智能评分</div>
                  <div style={{ display: 'flex' }}>
                    <Button
                      color="#F0F0F0"
                      onClick={() => (this.alertStatus = true)}
                      round
                      style={{
                        color: '#01c1b5',
                        margin: '0',
                        fontWeight: 'bold',
                        lineHeight: '30PX',
                        fontSize: '14PX',
                        padding: '0 10PX',
                        marginRight: '10PX',
                      }}
                    >
                      上传到云端
                    </Button>
                    {getRequestHostname() === '/api-student' ? (
                      <Button
                        color="#F0F0F0"
                        onClick={() => (this.shareStatus = true)}
                        round
                        style={{
                          color: '#01c1b5',
                          margin: '0',
                          fontWeight: 'bold',
                          lineHeight: '30PX',
                          fontSize: '14PX',
                          padding: '0 10PX',
                        }}
                      >
                        分享
                      </Button>
                    ) : null}
                  </div>
                </div>
                <div class={styles.detail}>
                  <img
                    src={data.img}
                    style={{
                      display: detailState.isPercussion ? '' : 'none',
                      margin: detailState.isPercussion ? 'auto' : '',
                    }}
                  />
                  <div class={styles.progress} style={{ display: detailState.isPercussion ? 'none' : '' }}>
                    <div class={styles.progressitem}>
                      <span>音准</span>
                      <Progress percentage={this.res?.intonation} color="linear-gradient(to right, #02E2DB, #01C1B5)" />
                      <span>{this.res?.intonation}</span>
                    </div>
                    <div class={styles.progressitem}>
                      <span>节奏</span>
                      <Progress percentage={this.res?.cadence} color="linear-gradient(to right, #02E2DB, #01C1B5)" />
                      <span>{this.res?.cadence}</span>
                    </div>
                    <div class={styles.progressitem}>
                      <span>完成度</span>
                      <Progress percentage={this.res?.integrity} color="linear-gradient(to right, #02E2DB, #01C1B5)" />
                      <span>{this.res?.integrity}</span>
                    </div>
                  </div>
                </div>
                {detailState.isPercussion ? (
                  <div class={styles.num}>
                    <strong>{this.res?.score}</strong>分 {data.mome}
                  </div>
                ) : null}
                <div class={styles.tips}>{data.tips}</div>
                <div class={styles.ctrls}>
                  <Button color="#01c1b5" round onClick={this.backDetail}>
                    去练习
                  </Button>
                  <Button color="#F79300" style={{ marginLeft: '10px' }} round onClick={() => this.retest()}>
                    再试一次
                  </Button>
                  <Button color="#F7B500" style={{ marginLeft: '10px' }} round onClick={this.viewReport}>
                    查看报告
                  </Button>
                </div>
              </div>
            </div>
          ) : null}
        </Popup>

        {/* 延迟检测窗口 */}
        <Popup
          teleport="body"
          class="popup-scale"
          transition="van-scale"
          overlay={false}
          show={this.delayData.open}
          onClose={() => this.handleCheckDelayEnd()}
        >
          <CheckDelayPopup
            delayData={this.delayData}
            onStartCheckDelay={() => this.handleStartCheckDelay()}
            onClose={() => this.handleStopCheckDelay()}
          />
        </Popup>

        {/* <Headphone onClose={this.closeErji} />
				<PhoneTip show={!this.delayData.erji && runtime.evaluatingTips} /> */}
      </div>
    )
  },
})
