//
//  YHAIViewModel.swift
//  galaxy
//
//  Created by Dufet on 2024/11/27.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHAIViewModel: NSObject {
    
    var listModel: YHAIListModel = YHAIListModel()
    var botConfig: YHAIBotConfigInfo = YHAIBotConfigInfo()
    var historyMessages: [YHAIHistoryMessage] = []
    var lastHistroyMsgId: String = ""
    
    func getAIEntranceList(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AIChat.aiProductList
        
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHAIListModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBackBlock(false, err)
                    return
                }
                self.listModel = resultModel
                callBackBlock(true, nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false, err)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestConversationId(callBackBlock: @escaping (_ sessionId: String) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AIChat.getAIChatSessionId
        
        _ = YHNetRequest.getRequest(url: strUrl) {  json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let sessionId = dic["conversationId"] as? String else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBackBlock("")
                    return
                }
                callBackBlock(sessionId)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock("")
            }
        } failBlock: { _ in
            callBackBlock("")
        }
    }
    
    func getHistoryChatMessages(botId: String, conversationId: String, messageId: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AIChat.chatHistory
        let params: [String: Any] = [
            "botId": botId,
            "conversationId": conversationId,
            "messageId": messageId
        ]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [Any], var arr = [YHAIHistoryMessage].deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBackBlock(false, err)
                    return
                    
                }
                
                if let lastMsg = arr.last {
                    self.lastHistroyMsgId = lastMsg.messageId
                }
                
                // 删除相邻两个相同的iqueston
                var result: [YHAIHistoryMessage] = []
                for curMsg in arr {
                    // 仅在结果数组为空或当前字符串与最后一个不同的情况下，才添加当前字符串
                    if result.isEmpty {
                        result.append(curMsg)
                    } else {
                        if let lastMsg = result.last {
                            let isSameQuestionMsg = (lastMsg.type == "question" && curMsg.type == "question" && lastMsg.contentText == curMsg.contentText)
                            if !isSameQuestionMsg {
                                result.append(curMsg)
                            }
                        }
                    }
                }
            
                self.historyMessages = result.reversed()
                
                callBackBlock(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false, err)
            }
            
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func createMessage(conversationId: String, role: String, msg: YHAIChatMessage, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        guard let msgDict = msg.body.toDictionary() else {
            return
        }
        let content = self.dicToJSONString(dict: msgDict)

        let params: [String: Any] = ["conversationId": conversationId,
                                     "contentType": "text",
                                     "role": role,
                                     "content": content]
        printLog("CREATE_MSG:\n \(params)")
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AIChat.createMessage
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callBackBlock(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false, err)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func getBotConfigInfoWithBotId(_ botId: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AIChat.botConfig
        let params: [String: Any] = ["botId": botId]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: params) {  json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHAIBotConfigInfo.deserialize(from: dic)  else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBackBlock(false, err)
                    return
                }
                self.botConfig = result
                callBackBlock(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false, err)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func dicToJSONString(dict: [String: Any]) -> String {
        if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
            return String(data: jsonData, encoding: .utf8) ?? ""
        }
        return ""
    }
}
