import { defineComponent } from 'vue'
import { Icon, Popover, Toast } from 'vant'
import MusicScore from '/src/components/music-score'
import { postMessage } from '/src/helpers/native-message'
// import requestOrigin from 'umi-request'
import state from '/src/pages/detail/state'
import DotIcon from './icons/dot.png'
import DotActiveIcon from './icons/dot-active.png'
import DotErrorIcon from './icons/dot-error.png'
import score from './data'

import styles from './index.module.less'
import { getAllNodes } from '../helpers'

// let timer: any = null
let time = 0
export default defineComponent({
  name: 'tuning-content',
  props: {
    // checkStatus: {
    //   type: Boolean,
    //   default: false
    // },
    // trend: {
    //   type: Number,
    //   default: -1
    // },
    frequency: {
      type: Number,
      default: -1
    },
    close: {
      type: Function,
      default: () => {}
    }
  },
  watch: {
    checkStatus() {
      this.end()
      this.notes = [DotActiveIcon, DotActiveIcon, DotActiveIcon]
    },
    frequency: {
      deep: true,
      handler(val) {
        const trend = Math.abs(this.frequency - this.checkFrequency) <= 5 ? 0 : this.frequency - this.checkFrequency > 0 ? 1 : -1
        const notes = [DotIcon, DotIcon, DotIcon]
        this.trend = trend
        notes[trend + 1] = (trend === 0 ? DotActiveIcon : DotErrorIcon)
        this.notes = [...notes]
        if (trend !== 0) {
          time = new Date().getTime()
        }
        console.log(trend, new Date().getTime() - time)
        if (new Date().getTime() - time > 3000) {
          this.checkStatus = true
        }
      }
    },
  },
  data() {
    return {
      time: 0,
      checking: false,
      checkStatus: false,
      checkFrequency: -1,
      notes: [DotIcon, DotIcon, DotIcon],
      scoreInfo: score(state.subjectId),
      trend: -1,
      tips: [
        '左边红灯表示吹奏的音过低',
        '吹奏时请保持中间绿灯亮起',
        '右边红灯表示吹奏的音过高',
      ]
    }
  },
  methods: {
    start(notes: any[]) {
      // this.end()
      if (this.checkStatus || this.checking) return
      this.checking = true
      // let index = 0
      // timer = setInterval(() => {
      //   if (index === this.notes.length - 1) {
      //     index = 0
      //   } else {
      //     index ++
      //   }
      //   this.notes = this.notes.map((note, i) => i === index ? DotActiveIcon : DotIcon)
      // }, 800)
      console.log('frequency', notes[0].frequency)
      postMessage({
        api: 'proxyServiceMessage',
        content: {
          header:{
            status: 200,
            commond: 'xmlInfo',
            type: 'SOUND_CHECK'
          },
          body: {
            frequency: notes[0].frequency
          }
        }
      })
      console.log('startSoundCheck')
      postMessage({
        api: 'startSoundCheck'
      })
    },
    end() {
      this.checking = false
      // clearInterval(timer)
      postMessage({
        api: 'endSoundCheck'
      }, () => {
        if (this.checkStatus) {
          Toast('校音完成')
          setTimeout(() => {
            this.close()
            this.checkStatus = false
            time = 0
          }, 1000)
        }
      })
    }
  },
  async mounted() {
    // this.start()
    // try {
    //   const res = await requestOrigin.get('./demo.xml')
    //   this.score = res
    // } catch (error) {}
  },
  unmounted() {
    this.end()
  },
  render() {
    return (
      <div class={styles.content}>
        {/* <div class={styles.title}>校音</div> */}
        {this.scoreInfo ? (
          <MusicScore
            class={styles.notes}
            score={this.scoreInfo.xml}
            opotions={{
              stretchLastSystemLine: true,
              drawMetronomeMarks: false,
              drawPartAbbreviations: false,
              drawPartNames: false,
              drawSlurs: false,
              drawTimeSignatures: false,
            }}
            onRerender={(osmd: any) => {
              const notes = getAllNodes(osmd)
              this.checkFrequency = notes[0].frequency
              console.log('this.checkFrequency', this.checkFrequency)
              this.start(notes)
            }}
          />
        ) : null}
        <p class={styles.tips}>{this.tips[this.trend + 1]}</p>
        <div class={styles.steps}>
          {this.notes.map((note, index) => <img key={index} src={note}/>)}
        </div>
      </div>
    )
  }
})
