import { defineComponent, nextTick, ref, Ref } from 'vue'
import { typeById, IVocals } from '/src/constant/fingering'
import event from '/src/components/music-score/event'
import state from '/src/pages/detail/state'
import getTypes from './types'
import styles from './index.module.less'
import classNames from 'classnames'

const imgRef: Ref = ref(null)

const containerRef: Ref = ref(null)

const getImageSize = (src: string) => {
  const img = new Image()
  img.src = src
  img.onload = () => {
    console.log(img.width, img.height)
  }
}

export default defineComponent({
  name: 'fingering',
  props: {
    type: {
      type: String,
      default: ''
    },
    fixedKey: {
      type: Number,
      default: 0
    },
    fingeringInfo: {
      type: Object
    },
    loaded: {
      type: Function,
      default: () => {}
    }
  },
  watch: {
    fixedKey() {
      this.index = 1
    },
    width() {
      this.loaded()
    },
    height() {
      this.loaded()
    },
  },
  computed: {
    formatFixedKey() {
      if (this.type === 'piccolo' && state.times[0]) {
        console.log(state)
        return this.fixedKey + ((1 - state.times[0].octaveOffset) * 12)
      } else {
        return this.fixedKey
      }
    },
    getSrc(): string {
      if (this.activeType && this.fingeringInfo?.name === 'trombone') {
        if (!this.activeType.relationship[this.formatFixedKey]) {
          return this.activeType.json.full2
        }
      }
      return this.activeType.json.full
    },
    activeRelationship() {
      const { activeType }: any = this
      const relationships = activeType.relationship
      let rs = relationships[(this as any).formatFixedKey] || relationships[0] || []
      if (typeof rs[0] === 'number' || typeof rs[0] === 'string') {
        return [rs]
      } else if (typeof rs[0] === 'object') {
        return rs
      }
      return [[]]
    },
  },
  data() {
    return {
      width: 'auto',
      height: 'auto',
      activeType: null as any,
      index: 1,
      fulled: false
    }
  },
  methods: {
    changeIndex() {
      let nextIndex = this.index === this.activeRelationship.length ? 1 : this.index + 1
      this.index = nextIndex
      // console.log(this.index)
    },
    fullLoaded() {
      setTimeout(async () => {
        this.fulled = true
        if (this.activeType && this.activeType.width) {
          this.width = this.activeType.width
          this.height = 'auto'
        }  else {
          if (this.fingeringInfo?.direction === 'vertical') {
            this.width = 'auto'
            this.height = imgRef.value?.height + 'px'
          } else {
            this.height = 'auto'
            this.width = imgRef.value?.width + 'px'
          }
        }
        await nextTick()
        this.loaded()
      })
    },
    getRotate(key: string | number) {
      if (key && this.fingeringInfo?.name === 'small-drum') {
        if (typeof key === 'string' && key.indexOf('active-') > -1) {
          const isLeft = key.indexOf('active-left') > -1
          return {
            transform:`rotate(${isLeft ? '-10' : '5'}deg)`,
            transformOrigin: '0 0',
          }
        }
      }
      return {}
    },
  },
  async mounted () {
    event.on('loaded', this.fullLoaded)
    const activeType = await getTypes((this.type as IVocals))
    this.activeType = activeType
    getImageSize(this.getSrc)
    console.log(await (containerRef.value as HTMLDivElement))
  },
  beforeUnmount() {
    this.loaded()
    event.off('loaded', this.fullLoaded)
  },
  render() {
    if (!this.activeType) {
      return null
    }
    const { activeType }: any = this
    const relationships = activeType.relationship
    const rs = relationships[this.formatFixedKey] || relationships[0] || []
    const imgWidth = activeType.width || 'auto'
    console.log(this.formatFixedKey)
    return (
      <div
        ref={containerRef}
        class={classNames(this.fingeringInfo?.name, styles.container)}
        style={{...this.activeType.styles, width: this.width, height: this.height, opacity: this.fulled ? 1 : 0}}
      >
        {rs.includes(0) ? <span style={{
          position: 'absolute',
          top: 0,
          right: 0,
          color: 'rgb(1, 193, 181)',
          fontWeight: 'bold',
        }}>转调</span> : null}
        <img
          ref={imgRef}
          src={this.getSrc}
          style={{
            height: activeType.height,
            width: imgWidth,
            // maxHeight: document.querySelector('.' + styles.container)?.clientHeight + 'px'
          }}
          onLoad={this.fullLoaded}
        />
        {this.activeRelationship[this.index - 1].map((key: number | string, index: number) => {
          const nk = typeof key === 'string' ? key.replace('active-', '') : key
          return (
            <img
             data-index={nk}
             style={{
               position: 'absolute',
               top: 0,
               left: 0,
               zIndex: index,
               height: activeType.height,
               width: imgWidth,
             }}
             src={activeType.json[nk]}
           />
         )
        })}
        {this.activeRelationship.length > 1 ? (
          <div
            onClick={this.changeIndex}
            class={styles.changeIndex}
          >替指</div>
        ) : null}
      </div>
    )
  }
})
