import { defineComponent, reactive, ref } from 'vue'
import { IMusicScore, OpenSheetMusicDisplay } from '/osmd-extended/src'
import Vex from '/osmd-extended/node_modules/vexflow'
var osmd = reactive({}) as OpenSheetMusicDisplay
let timer: any = null
export default defineComponent({
  name: 'VelFlowTest',
  data() {
    return {
      // xml: '/jianpu/人生的旋转木马《哈尔的移动城堡》-修改.xml'
      //   xml: '/jianpu/四四拍-案例0629.xml',
      // xml: '/12个调-2.0.xml'
      // xml: '/12个调-4.0.xml'
      // xml: '/jianpu/1中华人民共和国国歌.xml'
      // xml: '/jianpu/八三拍-案例0629_jp.xml'
      // xml: '/jianpu/八六拍-案例0629.xml'
      // xml: '/jianpu/房子测试.xml'
      // xml: '/jianpu/房子测试1.xml'
      // xml: '/jianpu/萨克斯一级乐曲2爱的礼赞.xml'
      // xml: '/音符-符杆.xml'
      // xml: '/1.小字一组567练习 - 副本 (2).xml'
      // xml: '/钢琴-测评.xml'
      xml: 'https://oss.dayaedu.com/cloud-coach/1661242248370尤克里里-测试-音阶.xml',
    }
  },
  computed: {
    isHidden() {
      return osmd && osmd.cursor && osmd.cursor.Hidden
    },
  },
  async mounted() {
    osmd = new OpenSheetMusicDisplay(document.querySelector('#container1') as HTMLElement, {
      backend: 'svg',
      drawTitle: true,
      // drawFingerings: true,
      coloringSetCustom: ['#00ff00'],
      cursorsOptions: [
        {
          type: 0,
          color: 'green',
          alpha: 1,
          follow: true,
        },
        // {
        //   type: 0,
        //   color: 'red',
        //   alpha: 1,
        //   follow: true
        // }
      ],
    })
    // ;(window as any).osmd = osmd
    osmd.EngravingRules.StaffLineColor = 'rgba(238,128,196,1)'
    osmd.EngravingRules.DefaultColorCursor = 'rgba(238,128,196,1)'
    this.handleJianpu(this.xml)
    var canvas = document.getElementById('glyphs') as HTMLCanvasElement
    var x = 0

    // Get number of glyphs and rename elements
    var counter = 0
    for (var glyph in Vex.Flow.Font.glyphs) {
      Vex.Flow.Font.glyphs[glyph] = Vex.Flow.Font.glyphs[glyph]
      counter++
    }

    var canvas_height = ((counter + 1) / (800 / (120 * 2))) * 60
    canvas.height = canvas_height
    canvas.width = 800

    var ctx = canvas.getContext('2d') as any
    ctx.font = '14pt Courier'

    var y = 60
    for (var glyph in Vex.Flow.Font.glyphs) {
      ctx.fillStyle = '#222'
      ctx.fillText(glyph, x, y)
      x += 60

      // ctx.strokeStyle = "#aaa";
      // ctx.beginPath();
      // ctx.moveTo(x - 5, y);
      // ctx.lineTo(x + 5, y);
      // ctx.stroke()

      // ctx.beginPath();
      // ctx.moveTo(x, y - 5);
      // ctx.lineTo(x, y + 5);
      // ctx.stroke()

      ctx.fillStyle = 'green'
      // console.log(Vex.Flow.Font.glyphs)
      if (Vex.Flow.Font.glyphs[glyph].o) {
        let g = new Vex.Flow.Glyph(glyph, 45)
        g.render(ctx, x, y)
        ctx.save()
        ctx.font = '6pt Arial'
        var metrics = g.getMetrics()
        // ctx.fillText(Math.floor(g.getMetrics().width), x - 35, y - 15 );
        // ctx.fillText(Math.floor(g.getMetrics().height), x - 35, y - 8 );
        // ctx.fillText(Math.floor(g.getMetrics().x_min), x - 25, y - 1 );
        // ctx.fillText(Math.floor(g.getMetrics().x_max), x - 25, y + 8 );
        ctx.restore()
      }
      x += 60

      if (x >= 800) {
        x = 0
        y += 120
      }
    }
  },
  methods: {
    async handleJianpu(url = '', type: IMusicScore = 'staff') {
      osmd.EngravingRules.DYMusicScoreType = type
      await osmd.load(url)
      osmd.render()
      console.log(osmd)
      this.getAllNote()
      osmd.cursor.reset()
    },
    getAllNote() {
      var allNotes = []
      osmd.cursor.reset()
      const iterator = osmd.cursor.Iterator

      // console.log({...iterator})
      while (!iterator.EndReached) {
        const voices = iterator.CurrentVoiceEntries?.[0] ? [iterator.CurrentVoiceEntries?.[0]] : []
        const voices2: any = iterator.CurrentVoiceEntries?.[1]
        for (var i = 0; i < voices.length; i++) {
          const v = voices[i]
          const notes = v.Notes
          for (var j = 0; j < notes.length; j++) {
            const note = notes[j]
            // make sure our note is not silent
            if (note != null && note.halfTone != 0 && !note.isRest()) {
              allNotes.push({
                note: note.halfTone + 12, // see issue #224
                time: iterator.currentTimeStamp.RealValue * 4,
                halfTone1: notes.map((n) => n.halfTone + 12).filter(Boolean),
                halfTone2:
                  voices2 && Array.isArray(voices2.notes)
                    ? voices2.notes.map((n: any) => n.halfTone + 12).filter(Boolean)
                    : [],
              })
            }
          }
        }
        iterator.moveToNext()
      }
      console.log(allNotes)
    },
    onNext() {
      // 下一步
      osmd.cursor.next()
      console.log(osmd.cursor)
    },
    onReset() {
      // 重置
      osmd.cursor.reset()
      // osmd.cursor.show()
    },
    onToggle() {
      // 隐藏
      if (!osmd.cursor.Hidden) {
        osmd.cursor.hide()
      } else {
        osmd.cursor.show()
      }
    },
    autoPlay() {
      clearTimeout(timer)
      let time = 0
      timer = setInterval(() => {
        console.log(osmd.cursor.cursorElement.style.display)
        if (new Date().getTime() - time > 2000) {
          osmd.cursor.next()
        }
        if (1) time = new Date().getTime()

        console.log(osmd.cursor.cursorElement.style.display)
      }, 1000)
    },
  },
  render() {
    return (
      <div>
        <button onClick={() => this.handleJianpu(this.xml, 'jianpu')}>简谱</button>
        <button onClick={() => this.handleJianpu('/jianpu/四二拍-案例0629.xml', 'jianpu')}>四二</button>
        <button onClick={() => this.handleJianpu('/jianpu/四三拍-案例0629.xml', 'jianpu')}>四三</button>
        <button onClick={() => this.handleJianpu('/jianpu/四四拍-案例0629.xml', 'jianpu')}>四四</button>
        <button onClick={() => this.handleJianpu('/jianpu/八三拍-案例0629_jp.xml', 'jianpu')}>八三</button>
        <button onClick={() => this.handleJianpu('/jianpu/八六拍-案例0629.xml', 'jianpu')}>八六</button>
        <div>
          <button onClick={this.onNext}>next</button>
          <button onClick={this.onReset}>reset</button>
          <button onClick={this.onToggle}>隐藏cursor</button>
          <button onClick={this.onToggle}>显示cursorsh</button>
          <button onClick={this.autoPlay}>自动</button>
        </div>
        <div id="container1"></div>
        <canvas id="glyphs" width="800" height="1600">
          HTML5 Canvas not supported on this browser.
        </canvas>
      </div>
    )
  },
})
