import { onMounted, Ref, ref } from 'vue'
import { OpenSheetMusicDisplay, EngravingRules, OSMDOptions } from '/osmd-extended/src'
import { formatZoom } from '/src/helpers/utils'
import { setEngravingRules } from './helpers'
import { Toast } from 'vant'
import qs from 'query-string'
const search = qs.parse(location.search);

/**
 * 合并规则
 * @param osmd OpenSheetMusicDisplay 实例
 * @param EngravingRules 规则
 */
export const useEngravingRules = (
  osmd: OpenSheetMusicDisplay,
  EngravingRules: { [P in keyof EngravingRules]?: EngravingRules[P] | undefined }
) => {
  onMounted(() => {
    setEngravingRules(osmd)

    for (const key in EngravingRules) {
      if (Object.prototype.hasOwnProperty.call(EngravingRules, key)) {
        let k: keyof EngravingRules = key as keyof EngravingRules
        const item = EngravingRules[k] as never
        osmd.EngravingRules[k] = item
      }
    }
  })
}

export const useOsmd = (
  container: Ref<HTMLDivElement | undefined>,
  opotions: OSMDOptions,
  setEngravingRules: { [P in keyof EngravingRules]?: EngravingRules[P] | undefined } = {}
) => {
  const osmd: Ref<OpenSheetMusicDisplay | undefined> = ref()
  if (container.value) {
    const rules = new EngravingRules()
    for (const [key, value] of Object.entries(setEngravingRules)) {
      /** EngravingRules 是class 索引好像有问题 */
      // @ts-ignore
      rules[key] = value as EngravingRules[keyof EngravingRules]
    }
    osmd.value = new OpenSheetMusicDisplay(
      container.value,
      {
        followCursor: false,
        autoResize: true,
        drawSubtitle: false,
        drawTitle: false,
        autoBeam: true,
        drawMetronomeMarks: false,
        drawMeasureNumbers: false,
        drawComposer: false,
        drawLyricist: false,
        ...opotions,
      },
      rules
    )
  }
  return osmd
}

export const useOsmdLoader = async (osmd: OpenSheetMusicDisplay, score: string) => {
  if (!score) throw 'score is required'
  try {
    if (score && osmd) {
      await osmd.load(score)
      // 自定义缩放比例
      let customZoom = formatZoom()
      osmd.zoom = customZoom

      await osmd.render()
    }
  } catch (error) {}
}
