<template>
	<div id="aplayer"></div>
</template>

<script setup>
import APlayer from "aplayer"; // 引入音乐插件
import "APlayer/dist/APlayer.min.css";
import { ref, computed, watch, onBeforeUnmount } from "vue";
import { useRoute } from 'vue-router';
import useFileDataStore from "@/components/file/stores/file-data";

let fileDataStore = useFileDataStore();

let route = useRoute();

watch(() => fileDataStore.audioArray, (newVal) => {
	let data = [];
	let currentAudioIndex = 0;
	newVal.forEach((item, index) => {
		if (item.fileName === fileDataStore.currentClickRow.fileName) {
			currentAudioIndex = index;
		}
		data.push({
			name: item.fileName,
			artist: ' ',
			url: item.url,
			cover: 'data:image/png;base64,[encoded data, 7468 characters]'
		})
	});

	initAudio(data, currentAudioIndex);
})

// 当前播放的音频所在路径
let currPath = ''

// 当前播放视频的实例
let ap;

/**
 * 初始化音频组件
 * @param data      音频列表
 * @param index     默认播放第 N 首
 */
let initAudio = (data, index) => {
	// 如果音频列表为空，则直接返回
	if (data.length === 0) {
		return;
	}
	const initButton = () => {
    setTimeout(() => {
      createCloseButton();
      // 监听窗口变化重新定位
      window.addEventListener('resize', createCloseButton);
    }, 500); // 延长等待时间确保DOM渲染完成
  };

	// 如果已经初始化过，则直接切换播放列表
	if (ap) {
		
		// 如果当前播放列表和之前一样，则不重新修改播放列表
		if (currPath !== route.params.fullpath) {
			ap.list.clear();
			ap.list.add(data);
		}
		currPath = route.params.fullpath
		ap.list.switch(index);
		ap.play();
		initButton();
	} else {
		// 创建一个音乐播放器实例，并挂载到 DOM 上，同时进行相关配置
		const el = document.getElementById("aplayer");
		ap = new APlayer({
			container: el,
			audio: data, // 音乐播放列表
			fixed: true, // 开启吸底模式
			autoplay: false, // 不开启自动播放
			preload: 'none' // 不预先加载
		});

		// 移除无用按钮, 添加按钮备注, 隐藏歌词功能
		el.getElementsByClassName("aplayer-miniswitcher")[0].click();
		el.getElementsByClassName('aplayer-icon-order')[0].setAttribute('title', '播放顺序');
		el.getElementsByClassName('aplayer-icon-loop')[0].setAttribute('title', '循环模式');
		el.getElementsByClassName('aplayer-icon-menu')[0].setAttribute('title', '播放列表');
		el.getElementsByClassName('aplayer-icon-lrc')[0].style.display = 'none';
		ap.play();
		currPath = route.params.fullpath
		ap.on('loadeddata', initButton);
	}
};
// 关闭按钮相关逻辑
let closeBtn = null;

const createCloseButton = () => {
  // 关键修改：定位到控制栏容器
  const controller = document.querySelector('.aplayer-controller');
  if (!controller) return;

  // 移除已存在的按钮
  if (closeBtn) {
    closeBtn.removeEventListener('click', handleClose);
    closeBtn.remove();
  }

  // 创建新按钮
  closeBtn = document.createElement('button');
  closeBtn.className = 'aplayer-close-btn';
  closeBtn.innerHTML = '×';
  closeBtn.style.cssText = `
    position: absolute;
    right: -5px;
    top:-40px;
    transform: translateY(-50%);
    z-index: 1001;
    background: none;
    border: none;
    color: #666;
    font-size: 24px;
    cursor: pointer;
    transition: color 0.3s;
  `;

  // 插入到控制栏
  controller.appendChild(closeBtn);
  closeBtn.addEventListener('click', handleClose);
};
onBeforeUnmount(() => {
	if (closeBtn) {
		closeBtn.removeEventListener('click', handleClose);
		closeBtn.remove();
	}
});
const handleClose = () => {
	if (ap) {
		ap.pause();
		ap.destroy();
		ap = null;
	}
	if (closeBtn) {
		closeBtn.removeEventListener('click', handleClose);
		closeBtn.remove();
		closeBtn = null;
	}
};
</script>

<style scoped>
#aplayer {
	position: relative !important;
	z-index: 99999;
}

/* 覆盖APlayer默认样式 */
::v-deep .aplayer-body {
	position: relative;
}
::v-deep .aplayer-controller {
  position: relative !important;
  height: 40px; /* 显式设置控制栏高度 */
}

/* 修复fixed模式下的层级 */
::v-deep .aplayer.aplayer-fixed {
  z-index: 99999 !important;
}
</style>