//
//  SpeakFreeTalkViewModel.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/9/8.
//

import UIKit
import Moya


class SpeakFreeTalkViewModel:  NetworkUtil<FreeTalkAPI> {

    private var talkId:String
    
    var isMute:Bool = false
    
    init(talkId: String, freeTalkUpdate: ((Any) -> Void)? = nil) {
        self.talkId = talkId
        self.freeTalkUpdate = freeTalkUpdate
    }
    
    var freeTalkUpdate:((Any)->Void)?
    
    var isSpeech:Bool = false {
        didSet{
            if let talk = freeTalkUpdate {
                talk(isSpeech)
            }
        }
    }
    
    var freeTalkMsg:[SpeakFreeTalkModel] = [] {
        didSet{
            if let talk = freeTalkUpdate {
                talk(freeTalkMsg)
            }
        }
    }
    
    func sendMessage(_ message:String) -> Void {
        let idx = SpeakElePublicManager.share.PublicData.AIerIndex
        let airs = SpeakHomeViewModel().AIser()[safe: idx]
        let vodioID = airs?.voiceId ?? ""
        isSpeech = false
        freeTalk(param: [
            "message":message,
            "talkId":talkId,
            "voiceId":vodioID
        ])
        
        if message.count > 0 {
            let talk = SpeakFreeTalkModel()
            talk.content = message
            talk.role = .User
            talk.AniState = .ANone
            self.freeTalkMsg.append(talk)
            
            let loading = SpeakFreeTalkModel()
            loading.role = .loading
            self.freeTalkMsg.append(loading)
        }
    }
    
    private func freeTalk(param:[String:Any]) -> Void {
        Print(param)
        request(.freeTalk(param)) {[weak self] (result: Result<SpeakNetBaseMode<[SpeakFreeTalkModel]>, Error>) in
            self?.isSpeech = true
            switch result {
            case .success(let res):
                if res.status == 200 {
                    if let data = res.result?.data {
                        for v in data {
                            v.role = .AI
                        }
                        if let last = self?.freeTalkMsg.last {
                            if last.role == .loading {
                                self?.freeTalkMsg.removeLast()
                            }
                        }
                        self?.freeTalkMsg.append(contentsOf: data)
                        DispatchQueue.global().async {
                            var Audioplay:[Data] = []
                            var duration = 0.0
                            for save in (data){
                                if let d = save.video {
                                    duration += save.videoTime ?? 0
                                    Audioplay.append(d)
                                    SpeakCache.cache.saveData(data: d, fileName: "\(save.recordId ?? 0)")
                                }
                            }
                            DispatchQueue.main.async {
                                if Audioplay.count > 0 {
                                    AudioPlayerManager.shared.setupAudioPlayer(with: Audioplay.first! ,isMuted: self?.isMute ?? false)
                                    Audioplay.remove(at: 0)
                                    AudioPlayerManager.shared.task = Audioplay
                                    let speed = SpeakElePublicManager.share.PublicData.speed
                                    SpeakAIVideoPlayManager.share.PlaySpeak(duration / speed)
                                }
                            }
                        }
                    }
                }else{
                    if let last = self?.freeTalkMsg.last {
                        if last.role == .loading {
                            self?.freeTalkMsg.removeLast()
                        }
                    }
                    SpWindow.rootViewController?.Alert(message: res.msg ?? "" ,afterClose: 1.5)
                }
                break
            case .failure(let error):
                if let last = self?.freeTalkMsg.last {
                    if last.role == .loading {
                        self?.freeTalkMsg.removeLast()
                    }
                }
                Print(error.localizedDescription)
                break
            }
        }
    }
    
}


enum FreeTalkAPI : BaseTargetType {
    case freeTalk([String:Any])
}

extension FreeTalkAPI {
    var baseURL: URL {
        return URL(string: "https://feedapihk.zhangxinhulian.com")!
    }
    
    var path: String {
        switch self {
        case .freeTalk:
            return "/api/learn/freeTalk"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .freeTalk:
            return .post
        }
    }
    
    var task: Task {
        switch self {
        case .freeTalk(let param):
            do {
                let pramdata = try JSONSerialization.data(withJSONObject: param)
                return .requestCompositeData(bodyData: pramdata, urlParameters: param)
            }catch{
                return .requestParameters(parameters: param, encoding: URLEncoding.httpBody)
            }
        }
    }
    
    var headers: [String: String]? {
        switch self {
        case .freeTalk:
            return ["Content-Type": "application/json",
                    "Authorization":SpeakElePublicManager.share.userInfo.token ?? ""]
        }
    }
}
