import { defineComponent, onMounted, reactive, Ref, ref, watch } from 'vue'
import request from '/src/helpers/request'
import originRequest from 'umi-request'
import MusicSheet from '/src/music-sheet'
import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
import {
  formatXML,
  onlyVisible,
  getAllNodes,
  getCustomInfo,
  getBoundingBoxByverticalNote,
  getParentNote,
} from '/src/pages/detail/helpers'
import SettingState from '/src/pages/detail/setting-state'
import detailState from '/src/pages/detail/state'
import { useMidi, useOriginSearch, useFee, useCamera, useUser } from '../colexiu/uses'
import styles from '../colexiu/index.module.less'
import detailStyles from './index.module.less'
import { OpenSheetMusicDisplay, PageFormat } from '/osmd-extended/src'
import { MusicSheelDetail, ShaeetStatusType } from '../colexiu/index.d'
// import ReplayIcon from './button-normal.svg'
import BackIcon from '../colexiu/header/icons/back.svg'
import PlayerPopup from '/src/pages/report/player'
import { colorsClass } from '/src/pages/report'
import { getLeveByScoreMeasure } from '/src/pages/detail/evaluating/helper'
import { Button, Skeleton, Sticky } from 'vant'
import { postMessage } from '/src/helpers/native-message'
import Empty from '/src/components/empty'
import { useSpecialShapedScreen } from '../colexiu/uses/use-app'
import { svgtopng } from '/src/subpages/colexiu-website/helpers/index'
const search = useOriginSearch()
console.log(search, 'search')

const useXml = async (url: string, detail: MusicSheelDetail) => {
  const xml = await originRequest(url)
  let score = ref<string>('')
  const parseXmlInfo = getCustomInfo(xml)
  score.value = formatXML(parseXmlInfo.parsedXML, {
    title: detail.musicSheetName,
  })
  // part-index 声部id
  const partIndex = Number(search['part-index']) || 0
  score.value = onlyVisible(score.value, partIndex)
  return score
}

const useDetail = (id: number | string): [Ref<ShaeetStatusType>, Ref<MusicSheelDetail>, Ref<any>] => {
  const status = ref<ShaeetStatusType>('loading')
  const data = ref<MusicSheelDetail>({})
  const record = ref<any>({})
  onMounted(async () => {
    status.value = 'loading'
    try {
      // partIndex   是声部id 当我切换声部 曲目id的时候需要重新渲染
      const res = await request.get(`/open/music/sheet/detail/${search.id}`, {
        prefix: '/api-website',
      })
      data.value = res.data
      detailState.partIndex = 0
      status.value = 'success'
    } catch (error) {
      status.value = 'error'
      console.log(error)
    }
  })
  return [status, data, record]
}

export default defineComponent({
  name: 'ColexiuWebSite',
  setup() {
    const renderLoading = ref(true)
    const renderError = ref(false)
    const score = ref<string>('')
    const [detailStatus, detail, record] = useDetail(search.id as string)
    const pages = new PageFormat(650, 884)
    watch(detailStatus, async () => {
      if (detailStatus.value === 'success' && detail.value.xmlFileUrl) {
        const xml = await useXml(detail.value.xmlFileUrl, detail.value)
        score.value = xml.value
      }
    })

    // useUser()

    useSpecialShapedScreen()
    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
        }
      }
    }

    const onRerender = async (osmd: osmd) => {
      // 判断 当前页面 有没有 获取元素的方法
      if (window.parent) {
        // 获取图片
        // const img = await getSvgPng(osmd)

        // 裁切显示多张图片，判断是显示多张还是一张
        const img = search.pageType === 'multiple' ? await getSvgPngToSize(osmd) : await getSvgPng(osmd)
        console.log(img, 'img')
        // let png = svgtopng()
        window.parent.postMessage(img, '*')
      }
      runtime.osmd = osmd
      const allNote = getAllNodes(osmd)
      renderLoading.value = false
      // for (const note of record.value.musicalNotesPlayStats.notesData) {
      //   const active = allNote[note.musicalNotesIndex]
      //   setTimeout(() => {
      //     const svgEl = document.getElementById('vf-' + active.id)
      //     svgEl?.classList.add((colorsClass as any)[note.musicalErrorType])
      //   }, 300)
      // }
      const setEvaluatings = (note: any, data: any, dontTransition = true) => {
        const startNote = getBoundingBoxByverticalNote(note)
        detailState.evaluatings = {
          ...detailState.evaluatings,
          [startNote.measureIndex]: {
            ...startNote,
            ...getLeveByScoreMeasure(data.score),
            score: data.score,
            dontTransition,
          },
        }
      }

      if (record.value.userMeasureScore) {
        for (const key in record.value.userMeasureScore) {
          if (Object.prototype.hasOwnProperty.call(record.value.userMeasureScore, key)) {
            const data = record.value.userMeasureScore[key]
            for (const time of allNote) {
              if (data.measureRenderIndex == time.noteElement.sourceMeasure.MeasureNumberXML - 1) {
                if (!time.noteElement.tie) {
                  setEvaluatings(time, data)
                } else {
                  for (const item of time.noteElement.tie.notes) {
                    const note = getParentNote(item)
                    if (!note) continue
                    setEvaluatings(note, data, item !== time.noteElement.tie.StartNote)
                  }
                }
              }
            }
          }
        }
      }
      // console.log(detailState.evaluatings, record.value.userMeasureScore)
      // detailState.activeDetail.originalSpeed = osmd.Sheet.userStartTempoInBPM
      // RuntimeUtils.setAudioInit()
    }
    const onRenderError = () => {
      renderError.value = true
      renderLoading.value = false
    }
    return () => {
      const loading = renderLoading.value || detailStatus.value === 'loading'
      const error = renderError.value || detailStatus.value === 'error'
      // console.log('ColexiuRender', detail.value.musicSubject, score.value)
      return (
        <div
          class={[
            styles.container,
            SettingState.sett.eyeProtection && 'eyeProtection',
            SettingState.sett.camera && 'openCamera',
          ]}
        >
          <div
            id="colexiu-detail-music-sheet"
            class={[styles.musicSheet, detailStyles.musicSheet]}
            style={{
              paddingLeft: detailState.isSpecialShapedScreen ? detailState.notchHeight / 2 + 'px' : 'auto',
            }}
          >
            {loading && !error && <Skeleton class={styles.skeleton} rowWidth="80%" title row={15} />}
            {error && <Empty />}
            {score.value && (
              <MusicSheet
                score={score.value}
                opotions={{
                  drawTitle: false,
                  drawComposer: false,
                  drawLyricist: false,
                  drawMetronomeMarks: true,
                  drawMeasureNumbers: true,
                }}
                EngravingRules={
                  search.pageType === 'multiple'
                    ? {
                        PageFormat: pages,
                      }
                    : {}
                }
                onRerender={onRerender}
                onRenderError={onRenderError}
              />
            )}
          </div>
          {record.value?.videoFilePath && record.value?.expire === 0 ? (
            <PlayerPopup {...record.value} btnClass={detailStyles.btn} popupClass={detailStyles.popup}>
              <Button class={detailStyles.btnCont}>
                <img src={ReplayIcon} />
              </Button>
            </PlayerPopup>
          ) : null}
        </div>
      )
    }
  },
})
