import {
	reactive,
	ref
} from 'vue';
import {
	onHide,
	onUnload
} from "@dcloudio/uni-app"
import {
	nextTick
} from 'vue';

let audioContext = null;
let code = null; // 身份标识
audioContext = uni.createInnerAudioContext(); // 单例模式[3](@ref)
audioContext.onEnded(() => {
	// console.log('触发播放结束')
	// 播放结束
	uni.$emit('danci-audio-ended', code)
	audioContext?.stop();

})
audioContext.onPlay(() => {
	// 播放
	// console.log('播放事件：', code)
	uni.$emit('danci-audio-play', code);
});
audioContext.onError((err) => {
	// 播放
	uni.$emit('danci-audio-ended', code)
	audioContext?.stop();
	// uni.$emit('danci-audio-play', code);
	uni.showToast({
		title: '音频播放异常，已重置'
	})
});
function createAudioNew() {
	audioContext = uni.createInnerAudioContext(); // 单例模式[3](@ref)
	audioContext.onEnded(() => {
		// console.log('触发播放结束')
		// 播放结束
		uni.$emit('danci-audio-ended', code)
		audioContext?.stop();
	
	})
	audioContext.onPlay(() => {
		// 播放
		// console.log('播放事件：', code)
		uni.$emit('danci-audio-play', code);
	});
	audioContext.onError((err) => {
		// 播放
		uni.$emit('danci-audio-ended', code)
		audioContext?.stop();
		// uni.$emit('danci-audio-play', code);
		uni.showToast({
			title: '音频播放异常，已重置'
		})
	});
}



export class audioPlayer {
	// 播放音频
	play(path, code1) {
		// console.log('播放文件地址', path)
		code = code1;
		if (audioContext.src === path && !audioContext.paused) return;
		audioContext.stop();
		audioContext.destroy();
		audioContext = null;
		
		nextTick(() => {
			createAudioNew();
			
			audioContext.src = path;
			audioContext.play();
		})
		

	}

	// 暂停播放
	pause() {
		audioContext?.pause();
	}

	// 停止播放（释放资源）
	stop() {
		audioContext?.stop();
	}

}

export function useAudioCache() {
	const cacheMapKey = 'audio_cache_map'; // Storage 中缓存映射的键名

	// 下载并缓存音频
	async function cacheAudio(url) {
		try {
			let cacheMap = uni.getStorageSync(cacheMapKey) || {};

			if (cacheMap[url]) {
				// console.log('已缓存音频地址', cacheMap[url])
				return cacheMap[url]; // 返回有效缓存路径
			}

			// 3. 下载音频文件
			const {
				tempFilePath
			} = await new Promise((resolve, reject) => {
				uni.downloadFile({
					url,
					success: resolve,
					fail: reject
				});
			});

			if (!tempFilePath.includes('.mp3')) {
				// console.log(`文件下载失败${url}`)
				return null;
			}

			// 4. 持久化存储到本地
			const savedFilePath = tempFilePath; // 跨平台安全路径[2](@ref)
			await uni.saveFile({
				tempFilePath,
				toSavedFilePath: savedFilePath
			});
			cacheMap[url] = savedFilePath;
			uni.setStorageSync(cacheMapKey, cacheMap);
			// console.log('当前音频地址', savedFilePath)
			return savedFilePath;
		} catch (err) {
			// console.error('音频缓存失败:', err);
			return null;
		}
	}

	function clearAudioCache() {
		// uni.setStorageSync(cacheMapKey, {})
		const cacheMap = uni.getStorageSync(cacheMapKey) || {};
		Object.entries(cacheMap).forEach(([key, path]) => {
			uni.removeSavedFile({
				filePath: path
			}); // 删除文件
			delete cacheMap[key];
		})
		// console.log('已清理完成', cacheMap)
		uni.setStorageSync(cacheMapKey, cacheMap)
	}

	return {
		cacheAudio,
		clearAudioCache
	}
}