import { Button, Popover, Popup, Toast } from 'vant'
import { defineComponent, onBeforeUnmount, onMounted, ref, Ref, watch } from 'vue'
import MusicSheet from '/src/music-sheet'
import { postMessage, listenerMessage, removeListenerMessage, IPostMessage } from '/src/helpers/native-message'
import { OpenSheetMusicDisplay } from '/osmd-extended/src'
import SettingState from '/src/pages/detail/setting-state'
import styles from './index.module.less'
import iconArrow from './icons/icon-arrow.svg'
import iconBottom from './icons/icon-bottom.png'
import iconRed from './icons/icon-red.png'
import iconBack from './icons/back.png'
import iconGreen from './icons/icon-green.png'
import iconWhite from './icons/icon-white.png'
import iconSound from './icons/icon-sound.png'
import getScore from '/src/pages/detail/tuning-popup/data'
import { getAllNodes } from '/src/pages/detail/helpers'
import { storeKeys } from '/src/constant/store-keys'
import contentSound from './sound.svg'

// 检测状态
const checkStatus: Ref<'checking' | 'success' | 'fail'> = ref('checking')
// 待检测的频率
const checkFrequency = ref(417.19244620530856)
// 当前显示的3个点状态
const dotIcons: Ref<string[]> = ref([iconWhite, iconWhite, iconWhite])
// 当前检测状态 -1 0 1
const trend = ref(-1)
// 上次检查正确时间
const time = ref(0)

const useStart = () => {
  postMessage({
    api: 'proxyServiceMessage',
    content: {
      header: {
        status: 200,
        commond: 'xmlInfo',
        type: 'SOUND_CHECK',
      },
      body: {
        frequency: checkFrequency.value,
      },
    },
  })
  postMessage({ api: 'startSoundCheck' }, () => {
    checkStatus.value = 'checking'
  })
  localStorage.setItem(storeKeys.lastCheckTime, '' + new Date().valueOf())
}

/**
 * 结束校音
 */
const useEnd = () => {
  postMessage({
    api: 'endSoundCheck',
  })
}

/**
 * 设置监听实时返回的频率信息
 */
const useLister = () => {
  const onSendResult = (evt?: IPostMessage) => {
    const frequency: number = evt?.content?.body.frequency
    console.log('frequency', frequency, checkFrequency.value)
    trend.value = Math.abs(frequency - checkFrequency.value) <= 5 ? 0 : frequency - checkFrequency.value > 0 ? 1 : -1
    dotIcons.value = [iconWhite, iconWhite, iconWhite]
    dotIcons.value[trend.value + 1] = trend.value === 0 ? iconGreen : iconRed
    if (trend.value !== 0) {
      time.value = new Date().getTime()
    }
    if (new Date().getTime() - time.value > 3000) {
      useEnd()
      checkStatus.value = 'success'
      dotIcons.value = [iconGreen, iconGreen, iconGreen]
      // 一秒钟之后关闭弹窗
      setTimeout(() => {
        soundEffectShow.value = false
      }, 1000)
    }
  }
  onMounted(() => {
    useStart()
    listenerMessage('sendResult', onSendResult)
  })
  onBeforeUnmount(() => {
    removeListenerMessage('sendResult', onSendResult)
  })
}

export const soundEffectShow = ref<boolean>(false)
//效音组件
export default defineComponent({
  name: 'ColexiuSoundEffect',
  setup() {
    const show = ref<boolean>(false)
    const onSelect = (val: any) => {
      if (val.text === '关闭校音') {
        // 关闭全局校音
        SettingState.sett.tuning = false
      }
      soundEffectShow.value = false
    }

    useLister()

    /**
     * 监听状态触发方法
     */
    watch(soundEffectShow, () => {
      if (soundEffectShow.value === false) {
        useEnd()
      }
    })
    return () => {
      const data = getScore(2)
      const score = data?.xml || ''
      return (
        <div class={styles.box}>
          <img class={styles.iconSound} src={iconSound} />
          <div class={styles.wrap}>
            <div class={styles.staff}>
              <img src={contentSound} />
              {/* <MusicSheet
                isSoundEffect={true}
                opotions={{
                  stretchLastSystemLine: true,
                  drawMetronomeMarks: false,
                  drawPartAbbreviations: false,
                  drawPartNames: false,
                  drawSlurs: false,
                  drawTimeSignatures: false,
                  followCursor: false,
                }}
                score={score}
                showSection={false}
                onRerender={useStart}
              /> */}
            </div>
            <div class={styles.des}>
              请演奏 <span style={{ color: 'var(--primary-color)' }}>Ab</span>直到绿灯全部亮起
            </div>
            <div class={styles.lampWrap}>
              {dotIcons.value.map((item, index) => (
                <div class={styles.lamp} key={index}>
                  <img class={[checkStatus.value === 'checking' && styles.flickerAnimate]} src={item} />
                </div>
              ))}
            </div>
          </div>
          <img class={styles.bottom} src={iconBottom} />
          <Button class={styles.button} icon={iconBack} onClick={() => (soundEffectShow.value = false)} />

          <Popover
            class={styles.skepItems}
            v-model:show={show.value}
            actions={[{ text: '跳过本次' }, { text: '关闭校音' }]}
            onSelect={(val) => onSelect(val)}
            vSlots={{
              reference: () => (
                <Button class={styles.skepBtn} icon={iconArrow} iconPosition="right">
                  跳过
                </Button>
              ),
            }}
          ></Popover>
        </div>
      )
    }
  },
})
