//
//  AudioPlayerManager.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/14.
//

import UIKit
import AVFoundation

class AudioPlayerManager: NSObject, AVAudioPlayerDelegate {
    
    private var audioPlayer: AVAudioPlayer?
    static let shared = AudioPlayerManager()
    
    var isMute:Bool = false
    
    private override init() {
         
    }
    
    /// 播放本地 MP3 文件
    /// - Parameters:
    ///   - fileName: 本地文件名称（不带扩展名）
    ///   - fileType: 文件类型（如 "mp3"）
    func playLocalAudio(fileName: String, fileType: String = "mp3") {
        // 获取本地文件路径
        guard let path = Bundle.main.path(forResource: fileName, ofType: fileType) else {
            print("未找到音频文件：\(fileName).\(fileType)")
            return
        }
        let url = URL(fileURLWithPath: path)
        playAudio(with: url)
    }
    
    /// 播放网络 MP3 文件（需处理网络请求，建议在子线程中调用）
    /// - Parameter urlString: 网络音频 URL 字符串
    func playNetworkAudio(urlString: String) {
        guard let url = URL(string: urlString) else {
            print("无效的音频 URL：\(urlString)")
            return
        }
        // 网络音频需要先获取数据（实际开发中建议用 URLSession 异步加载）
        do {
            let data = try Data(contentsOf: url)
            setupAudioPlayer(with: data)
        } catch {
            print("加载网络音频失败：\(error.localizedDescription)")
        }
    }
    
    /// 通用播放方法（通过 URL 初始化播放器）
    private func playAudio(with url: URL) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.delegate = self
            if audioPlayer?.prepareToPlay() ?? false {
                audioPlayer?.play()
                print("开始播放音频")
            }
        } catch {
            print("初始化播放器失败：\(error.localizedDescription)")
        }
    }
    
    var task:[Data] = []
    
    private func setconfig() -> Void {
        do{
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.playback,mode: AVAudioSession.Mode.spokenAudio , options: [.duckOthers,.allowBluetoothA2DP])
            try audioSession.setActive(true)
        }catch{ }
    }
    
    @discardableResult
    func setupAudioPlayer(with data: Data ,isMuted:Bool = false ,rate:Double? = nil) -> Double {
        setconfig()
        do {
            audioPlayer = try AVAudioPlayer(data: data)
            audioPlayer?.delegate = self
            audioPlayer?.enableRate = true
            if rate != nil {
                audioPlayer?.rate = 0.5
            }else{
                audioPlayer?.rate = Float(SpeakElePublicManager.share.PublicData.speed)
            }
            audioPlayer?.volume = isMuted ? 0 : 1
            if audioPlayer?.prepareToPlay() ?? false {
                audioPlayer?.play()
                print("开始播放音频")
            }
            return audioPlayer?.duration ?? 0
        } catch {
            print("初始化播放器失败：\(error.localizedDescription)")
        }
        return 0
    }
    
    // 暂停播放
    func pause() {
        if audioPlayer?.isPlaying ?? false {
            audioPlayer?.pause()
            print("暂停播放")
        }
    }
    
    func stop() {
        
        do {
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.playback ,mode: AVAudioSession.Mode.spokenAudio , options: [.duckOthers,.allowBluetoothA2DP])
            try audioSession.setActive(true)
        }catch {}
        
        task.removeAll()
        audioPlayer?.stop()
        audioPlayer?.currentTime = 0 // 重置播放进度
        print("停止播放")
    }
    
    // 调整音量（0.0 ~ 1.0）
    func setVolume(_ volume: Float) {
        audioPlayer?.volume = max(0.0, min(1.0, volume))
    }
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            print("音频播放完成")
            if self.task.count > 0 {
                setupAudioPlayer(with: self.task.first! ,isMuted: self.isMute)
                self.task.remove(at: 0)
            }
        }
    }
    
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: (any Error)?) {
        if error != nil {
            
        }
    }
}
