//
//  SpeakAudioRecorder.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/30.
//

import UIKit
import AVFoundation


class SpeakAudioRecorder: NSObject , AVAudioRecorderDelegate {
    
    // 单例模式
    static let shared = SpeakAudioRecorder()
    // 录音器
    private var audioRecorder: AVAudioRecorder?
    // 录音文件URL
    private var audioFileURL: URL?
    // 录音状态
    var isRecording: Bool {
        return audioRecorder?.isRecording ?? false
    }
    
    var callblocksssssss:((Bool)->Void)?
    
    // 权限状态
    var hasPermission: Bool {
        switch AVAudioSession.sharedInstance().recordPermission {
        case .granted:
            return true
        case .denied:
            return false
        case .undetermined:
            requestPermission { su in
                if let cccccc = self.callblocksssssss {
                    cccccc(su)
                }
            }
            return false
        @unknown default:
            return false
        }
    }
    
    override private init() {
        super.init()
        setupAudioSession()
    }
    
    // 配置音频会话
    private func setupAudioSession() {
        do{
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.playAndRecord ,mode: AVAudioSession.Mode.spokenAudio , options: [.duckOthers,.allowBluetoothA2DP])
            try audioSession.setActive(true)
        }catch{ }
    }
    
    // 请求录音权限
    func requestPermission(completion: @escaping (Bool) -> Void) {
        let session = AVAudioSession.sharedInstance()
        switch session.recordPermission {
        case .granted:
            completion(true)
        case .denied:
            completion(false)
        case .undetermined:
            session.requestRecordPermission { granted in
                DispatchQueue.main.async {
                    completion(granted)
                }
            }
        @unknown default:
            completion(false)
        }
    }
    
    // 开始录音
    func startRecording(fileName: String = "recording", completion: @escaping (Bool, Error?) -> Void) {
        setupAudioSession()
        guard hasPermission else {
            completion(false, NSError(domain: "权限被拒绝", code: 1001, userInfo: nil))
            return
        }
        
        guard !isRecording else {
            completion(false, NSError(domain: "正在录音中", code: 1002, userInfo: nil))
            return
        }
        // 创建录音文件URL
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documentsDirectory.appendingPathComponent("\(fileName).m4a")
        audioFileURL = fileURL
        // 录音设置
        let settings: [String: Any] = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVSampleRateKey: 44100,
            AVNumberOfChannelsKey: 2,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]
        
        do {
            // 创建录音器
            audioRecorder = try AVAudioRecorder(url: fileURL, settings: settings)
            audioRecorder?.delegate = self
            audioRecorder?.prepareToRecord()
            
            // 开始录音
            if audioRecorder?.record() == true {
                completion(true, nil)
            } else {
                completion(false, NSError(domain: "录音启动失败", code: 1003, userInfo: nil))
            }
        } catch {
            completion(false, error)
        }
    }
    
    // 暂停录音
    func pauseRecording() {
        audioRecorder?.pause()
    }
    
    // 恢复录音
    func resumeRecording() {
        audioRecorder?.record()
    }
    
    // 停止录音
    func stopRecording(completion: ((URL?, Error?) -> Void)? = nil) {
        let fileURL = audioFileURL
        audioRecorder?.stop()
        audioRecorder = nil
        if let fileURL = fileURL, FileManager.default.fileExists(atPath: fileURL.path) {
            completion?(fileURL, nil)
        } else {
            completion?(nil, NSError(domain: "录音文件不存在", code: 1004, userInfo: nil))
        }
    }
    // 删除录音文件
    func deleteRecording(at url: URL, completion: ((Bool) -> Void)? = nil) {
        do {
            try FileManager.default.removeItem(at: url)
            completion?(true)
        } catch {
            print("删除录音失败: \(error)")
            completion?(false)
        }
    }
    // AVAudioRecorderDelegate方法
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        print("录音完成，是否成功: \(flag)")
    }
    
    func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
        if let error = error {
            print("录音编码错误: \(error)")
        }
    }
}
