/**
 * 此处为新版本，旧版本因为显示尺寸等问题，后续都会使用此版本
 */
import { defineComponent, onMounted, Ref, ref, toRefs } from 'vue'
import state from '/src/pages/detail/state'
import styles from './index-svg.module.less'
import classNames from 'classnames'

export const getImageSize = (src: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = src
    img.onload = () => {
      resolve(img)
    }
    img.onerror = (err) => reject(err)
  })
}

export const formatFixedKey = (type: string, fixedKey: number): Ref<number> => {
  if (type === 'piccolo' && state.times[0]) {
    return ref(fixedKey + (1 - state.times[0].octaveOffset) * 12)
  } else {
    return ref(fixedKey)
  }
}

export const formatRelationship = (relationships: any, usedFixedKey: number) => {
  let rs = relationships[usedFixedKey] || relationships[0] || []
  if (typeof rs[0] === 'number' || typeof rs[0] === 'string') {
    return [rs]
  } else if (typeof rs[0] === 'object') {
    return rs
  }
  return [[]]
}

export const useFingeringSrc = (activeType: any, fingeringName: string, formatFixedKey: number): Ref<string> => {
  const src = ref('')
  if (activeType && fingeringName === 'trombone') {
    if (!activeType.relationship[formatFixedKey]) {
      src.value = activeType.json.full2
      return src
    }
  }
  src.value = activeType.json.full
  return src
}

export default defineComponent({
  name: 'fingering',
  props: {
    type: {
      type: String,
      default: '',
    },
    fixedKey: {
      type: Number,
      default: 0,
    },
    fingeringInfo: {
      type: Object,
    },
    loaded: {
      type: Function,
      default: () => {},
    },
    viewInfo: {
      type: Object,
    },
  },
  setup(props, { expose }) {
    const refProps = toRefs(props)
    const container: Ref<HTMLDivElement | null> = ref(null)
    const imgRef: Ref<HTMLImageElement | null> = ref(null)
    const containerWidth = ref(0)
    const index = ref(0)

    // 横向具体指法样式
    const ItemImgStyleTransverse = {
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
    }

    // 竖向具体指法样式
    const ItemImgStyleVertical = {
      top: '50%',
      left: 0,
      // transform: 'translateY(-50%)',
    }

    expose({
      container,
      containerWidth,
    })

    return () => {
      if (!refProps.viewInfo.value?.activeType) return null
      const usedFixedKey = formatFixedKey(props.fingeringInfo?.name, refProps.fixedKey.value).value
      //    console.log("🚀 ~ ",props.fingeringInfo?.name, refProps.fixedKey.value)
      const relationshipGroup = formatRelationship(refProps.viewInfo.value?.activeType?.relationship, usedFixedKey || 0)
      const classActive = [] as any
      if (state.activeNote) {
        // 右手
        state.activeNote?.halfTone1.forEach((n: number) => {
          let ns = refProps.viewInfo.value?.activeType?.relationship?.[n] || []
          ns = ns.map((rigthN: any) => 'right' + rigthN)
          classActive.push(...ns)
        })
        //左手
        state.activeNote?.halfTone2.forEach((n: number) => {
          let ns = refProps.viewInfo.value?.activeType?.relationship?.[n] || []
          ns = ns.map((rigthN: any) => 'left' + rigthN)
          classActive.push(...ns)
        })
        // console.log("🚀 ~ file: index-svg.tsx ~ line 116 ~ state.activeNote?.halfTone2.forEach ~ classActive", classActive)
      }

      const changeIndex = () => {
        let nextIndex = index.value === relationshipGroup.length - 1 ? 0 : index.value + 1
        index.value = nextIndex
      }

      const rs = relationshipGroup[index.value] || []

      return (
        <div
          ref={container}
          class={classNames(props.fingeringInfo?.name, styles.container)}
          style={{
            width: props.fingeringInfo?.direction === 'vertical' ? props.fingeringInfo?.width : '',
            height: props.fingeringInfo?.direction === 'transverse' ? props.fingeringInfo?.height || '' : '100%',
            display: 'flex',
            paddingLeft: props.fingeringInfo?.direction === 'vertical' ? props.fingeringInfo?.paddingLeft : '',
            paddingRight: props.fingeringInfo?.direction === 'vertical' ? props.fingeringInfo?.paddingRight : '',
          }}
        >
          {rs.includes(0) ? (
            <span
              style={{
                position: 'absolute',
                top: '.5vh',
                right: '.5vw',
                color: 'rgb(1, 193, 181)',
                fontWeight: 'bold',
              }}
            >
              转调
            </span>
          ) : null}
          <div
            style={{ width: '100%', height: '100%'}}
            class={classActive}
            innerHTML={refProps.viewInfo.value?.activeType?.json.full2}
          ></div>

          {relationshipGroup.length > 1 ? (
            <div role="button" onClick={changeIndex} class={['substituteFinger', styles.changeIndex]}>
              替指
            </div>
          ) : null}
        </div>
      )
    }
  },
})
