import { defineComponent, nextTick, ref } from 'vue'
import MusicSheet from '/src/music-sheet'
import { useOriginSearch, useXml } from '../colexiu/uses'
import { OpenSheetMusicDisplay, PageFormat } from '/osmd-extended/src'
import { postMessage } from '/src/helpers/native-message'
import { svgtopng } from '../colexiu/helpers'
const search = useOriginSearch()

/** 暴露曲谱实例方便其他地方重新绘制曲谱 */
export const MusicSheetRef = ref()

export default defineComponent({
  name: 'Colexiu',
  setup() {
    let totalProduct = 0 // 总共生成的次数
    const renderLoading = ref(true)
    const renderError = ref(false)
    const score = ref<string>('')
    const pages = new PageFormat(650, 884)
    const engravingRules = ref<any>({})
    const reloadRenderStatus = ref(false)
    const staffType = ref<'staff' | 'first' | 'fixed'>('staff') // TODO: staff 五线谱 first 简谱首调 fixed 简谱固定调
    const staffImgs = ref<any>({
      staff: null,
      first: null,
      fixed: null,
    }) // 存取三种图片
    // if (search.pageType === 'multiple') {
    //   engravingRules.value = {
    //     PageFormat: pages,
    //   }
    // } else
    if (search.pageType === 'more') {
      engravingRules.value = {
        PageFormat: pages,
        DYMusicScoreType: 'staff', // staff 五线谱  jianpu 简谱
        RenderKeySignatures: true, // true 首调 false 固定调
      }
    }

    !(async function () {
      try {
        console.log('需要渲染的xml search.xml:', search.xml)
        const xml = await useXml(
          search.xml as string,
          {
            musicSheetName: (search.title as string) || '',
          } as any
        )
        if (!xml.value) {
          renderLoading.value = false
          renderError.value = true
          console.log('没有xml错误了')
          window.parent.postMessage(
            {
              api: 'osdmRenderedError',
            },
            '*'
          )
          return
        }
        score.value = xml.value
      } catch (error) {
        console.log('获取xml错误了', error)
        window.parent.postMessage(
          {
            api: 'osdmRenderedError',
          },
          '*'
        )
      }
    })()

    /** 当渲染完成后的回调 */
    const onRerender = async (osmd: OpenSheetMusicDisplay) => {
      postMessage({
        api: 'cloudLoading',
        content: {
          show: false,
          type: 'fullscreen',
        },
      })

      const getSvgPng = async (osmd: any) => {
        if (osmd) {
          for (const backend of osmd.Drawer.Backends) {
            const { state, width, height } = (backend as any).ctx
            const { x, y } = state.scale

            const cont = new XMLSerializer().serializeToString((backend as any).ctx.svg)
            return await svgtopng(cont, width / x, height / y)
          }
        }
      }
      const getSvgPngToSize = async (osmd: any) => {
        if (osmd) {
          const imgList = [] as any
          if (osmd.Drawer.Backends.length > 0) {
            for (let idx = 0, len = osmd.Drawer.Backends.length; idx < len; idx++) {
              const backend = osmd.Drawer.Backends[idx]
              const { state, width, height } = (backend as any).ctx
              const { x, y } = state.scale
              const cont = new XMLSerializer().serializeToString((backend as any).ctx.svg)
              imgList.push(await svgtopng(cont, width / x, height / y))
            }
            return imgList
          }
        }
      }
      if (window.parent) {
        // 获取图片
        try {
          // const img = await getSvgPng(osmd)
          // 处理三种图片
          const img = await getSvgPngToSize(osmd)
          if (staffType.value === 'staff') {
            totalProduct = 1
            staffType.value = 'first'
            staffImgs.value.staff = img
            engravingRules.value.DYMusicScoreType = 'jianpu'
            engravingRules.value.RenderKeySignatures = true
            await nextTick()
            reloadRenderStatus.value = true
            setTimeout(() => {
              reloadRenderStatus.value = false
            }, 100)
            // MusicSheetRef.value?.setRender()
          } else if (staffType.value === 'first') {
            totalProduct = 2
            staffType.value = 'fixed'
            staffImgs.value.first = img
            engravingRules.value.DYMusicScoreType = 'jianpu'
            engravingRules.value.RenderKeySignatures = false
            // MusicSheetRef.value?.setRender()
            await nextTick()
            reloadRenderStatus.value = true
            setTimeout(() => {
              reloadRenderStatus.value = false
            }, 100)
          } else if (staffType.value === 'fixed') {
            totalProduct = 3
            staffImgs.value.fixed = img
            console.log(staffImgs.value, 'staffImgs fixed = last')
          }
          if (totalProduct === 3) {
            console.log(staffImgs.value, 'staffImgs ------------- postMessage')
            window.parent.postMessage(
              {
                api: 'osdmRendered',
                content: {
                  img: JSON.parse(JSON.stringify(staffImgs.value)),
                },
              },
              '*'
            )
          }
        } catch (error) {
          console.log('渲染错误了')
          console.log(error, 'error')
          window.parent.postMessage(
            {
              api: 'osdmRenderedError',
            },
            '*'
          )
        }
        // let png = svgtopng()
      }
    }

    const onStartRender = async () => {
      // renderLoading.value = true
      // postMessage({
      //   api: 'cloudLoading',
      //   content: {
      //     show: true,
      //     type: 'fullscreen',
      //   },
      // })
    }
    const onRenderError = () => {
      console.log('onRenderError错误了')
      postMessage({
        api: 'cloudLoading',
        content: {
          show: false,
          type: 'fullscreen',
        },
      })
      renderError.value = true
      renderLoading.value = false

      if (window.parent) {
        // 获取图片
        window.parent.postMessage(
          {
            api: 'osdmRenderedError',
          },
          '*'
        )
      }
    }

    return () => {
      return (
        !reloadRenderStatus.value && (
          <MusicSheet
            ref={MusicSheetRef}
            score={score.value}
            isSoundEffect={true}
            opotions={{
              drawTitle: false,
              drawComposer: true,
              drawLyricist: false,
              drawMetronomeMarks: true,
              drawMeasureNumbers: true,
              autoResize: false,
            }}
            EngravingRules={engravingRules}
            onStartRender={onStartRender}
            onRenderError={onRenderError}
            onRerender={onRerender}
          />
        )
      )
    }
  },
})
