import { defineComponent, onMounted, ref, computed } from "vue"
import styles from "./index.module.less"
import { audioData, changeCombineAudio } from "/src/view/audio-list"
import openImg from "./imgs/open.png"
import lockImg from "./imgs/lock.png"
import state from "/src/state"

export default defineComponent({
   name: "combineAudio",
   setup(props, { emit }) {
      const elementsData = ref<{ index: number; top: number; left: number }[]>([])
      onMounted(() => {
         const parent = document.querySelector("#osmdCanvasPage1")
         const elements = document.querySelectorAll("g[data-trackIdx]")
         const musicContainerPos = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
            top: 0,
            left: 0
         }
         const combineMusicsIndexs = Object.keys(audioData.combineMusics)
         elements.forEach(element => {
            const dataTrackIdx = element.getAttribute("data-trackIdx")
            // 当有 dataTrackIdx 并且有原音的时候 显示
            if (dataTrackIdx && combineMusicsIndexs.includes(dataTrackIdx)) {
               const elementRect = element.getBoundingClientRect()
               const height = elementRect.height
               let top = elementRect.top + height / 2 - 11 - musicContainerPos.top
               let left = elementRect.left - 22 - 10 - musicContainerPos.left
               elementsData.value.push({
                  index: parseInt(dataTrackIdx),
                  top: top,
                  left: left
               })
            }
         })
      })
      const combineZoom = computed(() => {
         let zoom = state.zoom
         if (zoom < 1) {
            zoom = 1
         } else if (zoom > 1.5) {
            zoom = 1.5
         }
         return zoom
      })
      return () => (
         <>
            <div class={[styles.combineAudio, state.playState === "play" && styles.play]}>
               {elementsData.value.map(item => {
                  return (
                     <img
                        class={styles.combineAudioImg}
                        onClick={() => {
                           changeCombineAudio(item.index)
                        }}
                        style={{
                           top: item.top + "px",
                           left: item.left - (combineZoom.value - 1) * 22 + "px",
                           "--combineZoom": combineZoom.value
                        }}
                        src={audioData.combineIndex === item.index ? openImg : lockImg}
                     />
                  )
               })}
            </div>
         </>
      )
   }
})
