import { defineComponent, nextTick, ref, Ref } from 'vue'
import { Button, Popover, Circle, Toast } from 'vant'
import classnames from 'classnames'
import EventEmitter from 'eventemitter3'
import event from '/src/components/music-score/event'
import Icons from './icons/index.json'
import Speed from './speed'
import state from './state'
import { resetPlayer } from './evaluating'
import SettingPopup from './setting-popup'
import runtime, * as RuntimeUtils from './runtime'
import { getDuration } from '/src/pages/detail/helpers'
import { getAllNodes } from './helpers'
import styles from './header.module.less'
import indexStyles from './index.module.less'

import { postMessage, listenerMessage } from '/src/helpers/native-message'

export const btnEvent = new EventEmitter()

let cloudDeailInited: boolean = false

const speedRef: Ref = ref(null)

export default defineComponent({
  props: {
    title: {
      type: String,
      default: '',
    },
    songs: {
      type: Object,
      default: {}
    },
    openLib: {
      type: Function,
      default: () => {}
    },
    openList: {
      type: Function,
      default: () => {}
    },
    onActiveKeyChange: {
      type: Function,
      default: () => {}
    },
    lib: {
      type: Object,
      default: null
    },
  },
  beforeCreate() {
    postMessage({
      api: 'setStatusBarTextColor',
      content: {
        statusBarTextColor: false
      }
    })
    listenerMessage('suspendPlay', () => {
      if (state.activeTick > -1) {
        RuntimeUtils.stopTick()
      }
      // console.log(runtime.audiosInstance.getStatus())
      if (runtime.audiosInstance.getStatus() === 'play') {
        RuntimeUtils.resetPlayStatus()
        if (runtime.evaluatingStatus) {
          postMessage({
            api: 'pauseRecording'
          }, () => {
            state.isPauseRecording = true
          })
        }
      }
    })
  },
  mounted() {
    try {
      state.times = getAllNodes(runtime.osmd)
      console.log('state.times', state.times)
    } catch (error) {
      console.log(error)
    }
    const durationNum = state.times[(state.times.length - 1 || 0)]?.endtime || 0
    console.log('durationNum', durationNum)
    const midiUrl = state.activeDetail.midiUrl
    if (!cloudDeailInited && midiUrl) {
      cloudDeailInited = true
      state.midiPlayIniting = true
      // 发送初始化信息
      postMessage({
        api: 'cloudDetail',
        content: {
          midi: midiUrl,
          denominator: getDuration(runtime.osmd).denominator,
          numerator: getDuration(runtime.osmd).numerator,
          originalSpeed: state.activeDetail.originalSpeed,
          interval: 50,
          duration: durationNum * 1000,
        }
      }, () => {
        state.midiPlayIniting = false
        if (midiUrl) {
          RuntimeUtils.changeMode('music')
        }
      })
      runtime.durationNum = durationNum
      // postMessage({
      //   api: 'cloudChangeSpeed',
      //   content: {
      //     speed: state.activeDetail.speed,
      //     originalSpeed: state.activeDetail.originalSpeed,
      //   }
      // })
    }
    console.log(state.times)
    RuntimeUtils.changeSpeed(state.activeSpeed)
    RuntimeUtils.setAudioInit()
    event.on('section-click', RuntimeUtils.noteClick)
  },
  unmounted() {
    RuntimeUtils.resetPlayStatus()
    runtime.audiosInstance?.destroyed()
    event.off('section-click', RuntimeUtils.noteClick)
  },
  created() {
    runtime.isFirstPlay = false//runtime.browser.mobile
  },
  computed: {
    // timesByBox() {
    //   return (state as any).times.map((item: any) => {
    //     const box = item.svgElelent.attrs.el.getBBox()
    //     return {
    //       id: item.id,
    //       lat: box.x,
    //       lon: box.y
    //     }
    //   })
    // },
    isAppPlay() {
      return state.activeDetail?.isAppPlay
    },
    playerButtonIsDisabled() {
      return (state.activeDetail?.isAppPlay ?
        !state.activeDetail?.midiUrl :
        runtime.audiosInstance?.length == 0 || state.mode === 'homework'
      ) || runtime.evaluatingStatus || state.midiPlayIniting
    },
    changeModeIsDisabled(): boolean {
      return (
        state.activeDetail?.isAppPlay ?
          state.activeDetail?.midiUrl === '' :
          runtime.isFirstPlay || runtime.audiosInstance?.length == 1
        ) || runtime.evaluatingStatus || state.midiPlayIniting
    },
    playerButtonText() {
      return runtime.playState === 'play' || runtime.metroing ? '停止' : '播放'
    }
  },
  data() {
    return {
      mainWidth: document.querySelector('.' + indexStyles.main)?.clientWidth,
      wrapWidth: document.querySelector('.' + indexStyles.wraper)?.clientWidth,
      openCameraStatus: false,
    }
  },
  methods: {
    async startEvaluating() {
      if (runtime.evaluatingStatus) {
        postMessage({
          api: 'proxyServiceMessage',
          content: {
            header:{
              commond: 'recordCancel',
              type: 'SOUND_COMPARE',
              status: 200,
            }
          }
        })
        postMessage({
          api: 'cancelEvaluating',
        }, () => {
          Toast.clear()
        })
      }
      RuntimeUtils.resetPlayStatus()
      runtime.evaluatingStatus = !runtime.evaluatingStatus
      resetPlayer()
      await nextTick()
      runtime.osmd.drawer.backend.resize(
        this.wrapWidth,
        runtime.osmd.drawer.backend.height
      )
      // state.renderLoading = true
      // console.log('renderLoading', state.renderLoading)
      btnEvent.emit('startEvaluating')
      // setTimeout(async () => {
      //   state.times = getAllNodes(runtime.osmd)
      // }, 18)
    },
    async evaluating() {
      this.startEvaluating()
    },
    async openCamera() {
      this.openCameraStatus = true
      postMessage({
        api: 'openCamera',
      }, () => {
        this.openCameraStatus = false
        runtime.cameraStatus = true
      })
    },
  },
  render() {
    const progress = Math.floor((runtime.currentTimeNum / runtime.durationNum) * 100) || 0
    // console.log(runtime.currentTimeNum, runtime.durationNum)
    const isHomework = state.mode === 'homework'
    return (
      <div class={styles['right-icons']}>
        <div
          class={styles.buttonWraper}
          id="tips-step-2"
        >
          <Button
            class={styles.button}
            icon={runtime.evaluatingStatus ? Icons.evaluating2 : Icons.evaluating}
            disabled={(this.isAppPlay ? !state.activeDetail?.midiUrl || state.midiPlayIniting : (!(runtime.songs.background || runtime.songs.music))) || isHomework || !state.enableEvaluation}
            onClick={this.authBefore('evaluating', this.evaluating)}
          />
          <span>评测</span>
        </div>
        <div class={styles.buttonWraper} id="tips-step-4">
          <Button
            class={styles.button}
            icon={Icons['section' + state.section.length]}
            color="#01C1B5"
            disabled={runtime.isFirstPlay || runtime.evaluatingStatus || isHomework}
            onClick={this.authBefore('excerpts', RuntimeUtils.sectionChange)}
          />
          <span>选段</span>
        </div>
        <div
          class={classnames(styles.buttonWraper, styles.circleWraper)}
          id="tips-step-5"
          onClick={!this.playerButtonIsDisabled && this.authBefore('follow', RuntimeUtils.setPlayState)}
        >
          <Button
            class={styles.button}
            icon={runtime.playState === 'play' || runtime.metroing ? Icons.pause : Icons.play}
            disabled={this.playerButtonIsDisabled}
            color={runtime.loading ? '#01C1B5' : ''}
          />
          <Circle
            class={classnames(styles.circle, styles.button)}
            stroke-width={80}
            currentRate={progress}
            rate={100}
            layerColor="#01C1B5"
            color="#FFC830"
          />
          <span>{this.playerButtonText}</span>
        </div>
        <div class={styles.buttonWraper} id="tips-step-6">
          <Button
            class={styles.button}
            disabled={this.changeModeIsDisabled || isHomework}
            icon={runtime.mode === 'background' ? Icons.background : Icons.music}
            onClick={this.authBefore('switch', () => {
              RuntimeUtils.changeMode(runtime.mode === 'background' ? 'music' : 'background')
            })}
          />
          <span>{runtime.mode === 'background' ? '伴奏' : '原声'}</span>
        </div>
        <div class={styles.buttonWraper} id="tips-step-7">
          <Button
            class={styles.button}
            icon={Icons.replay}
            disabled={runtime.isFirstPlay || runtime.evaluatingStatus || isHomework}
            onClick={this.authBefore('follow', async () => {
              if (state.activeTick > -1) {
                return
              }
              RuntimeUtils.setCurrentTime(0)
              RuntimeUtils.ended(new Event('ended'))
            })}
          />
          <span>重播</span>
        </div>
        <Popover
          trigger="manual"
          show={runtime.speedShow && !(runtime.evaluatingStatus || runtime.playState === 'play')}
          placement="bottom"
          overlay={false}
          onUpdate:show={(show: boolean) => runtime.speedShow = show}
          vSlots={{
            reference: () => (
              <div
                id="tips-step-8"
                class={classnames(styles.badge, styles.buttonWraper)}
                style={{
                  zIndex: runtime.speedShow ? 99999 : 1
                }}
              >
                <Button
                  class={styles.button}
                  icon={Icons.setting}
                  disabled={runtime.evaluatingStatus || runtime.playState === 'play'}
                  onClick={this.authBefore('speed', () => {
                    speedRef.value?.refUpdateSpeed(runtime.speed)
                    runtime.speedShow = true
                  })}
                />
                <span class={styles.badgenum}>{runtime.speed}</span>
                <span>速度</span>
              </div>
            )
          }}
        >
          <Speed
            ref={speedRef}
            updateSpeed={(speed: number) => runtime.speed = speed}
            changed={RuntimeUtils.changeSpeed}
            mode={runtime.mode}
            changeMode={RuntimeUtils.changeMode}
            lib={this.lib}
          />
        </Popover>
        <SettingPopup disabled={runtime.evaluatingStatus || isHomework}>
          <div
            class={styles.buttonWraper}
          >
            <Button
              class={styles.button}
              icon={Icons.menu}
              disabled={runtime.evaluatingStatus || isHomework}
            />
            <span>设置</span>
          </div>
        </SettingPopup>
      </div>
    )
  }
})
