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

import UIKit
import SmartCodable

class YHAIMessageModel: NSObject {

}

enum YHAIMessageType: Int {
    
    case unknown = 0
    case text = 1  // 文字消息
    case cardList = 2 // 卡片列表消息
    case productList = 3 // 商品列表消息
    case picture = 4 // 图片消息
    
    // 自定义case
    case thinking = 9527  // 思考消息
    case recommendText = -9527 // 推荐文字消息

}

class YHAIChatMessage: CustomStringConvertible, NSCopying {
    
    let completeText = "conversation.chat.completed"
    
    var id: String = ""
    var event: String = ""
    var data: String = ""
    var dataDict: [String: Any] = [:]
    var messageId: String = ""
    var isSelf: Bool = false
    var isDone: Bool = false
    var body = YHAIMessageBody()
    
    func copy(with zone: NSZone? = nil) -> Any {
        let msg = YHAIChatMessage()
        msg.id = self.id
        msg.event = self.event
        msg.data = self.data
        msg.dataDict = self.dataDict
        msg.messageId = self.messageId
        msg.isSelf = self.isSelf
        msg.isDone = self.isDone
        if let body = self.body.copy() as? YHAIMessageBody {
            msg.body = body
        }
        return msg
    }
    
    func isMessageCompleted() -> Bool {
        if self.body.status == "completed" {
            return true
        }
        return false
    }
    
    func isTextCompleted() -> Bool {
        if self.body.contentType == YHAIMessageType.text.rawValue && self.body.status == "completed" && self.body.type == "answer" {
            return true
        }
        return false
    }
    
    func setDone() {
        self.isDone = true
    }
    
    func isTextMessage() -> Bool {
        let type = self.getType()
        return  type == .text || type == .recommendText
    }
    
    func isNeedSpiceMessage() -> Bool {
        let type = self.getType()
        return  type == .text && self.body.type == "answer"
    }
    
    static func createQuestionMessage(_ text: String) -> YHAIChatMessage {
        let question = YHAIChatMessage()
        question.isSelf = true
        let body = YHAIMessageBody()
        body.contentType = 1
        body.contentText = text
        question.setDone()
        question.body = body
        question.messageId = UUID().uuidString + NSDate().timeIntervalSince1970.description
        question.updateBodyToData()
        return question
    }
    
    static func createThinkingMesssage() -> YHAIChatMessage {
        let message = YHAIChatMessage()
        message.isSelf = false
        let body = YHAIMessageBody()
        body.contentType = YHAIMessageType.thinking.rawValue
        message.setDone()
        message.body = body
        message.messageId = UUID().uuidString + NSDate().timeIntervalSince1970.description
        message.updateBodyToData()
        return message
    }
    
    static func createTextMesssage(text: String) -> YHAIChatMessage {
        let message = YHAIChatMessage()
        message.messageId = UUID().uuidString + NSDate().timeIntervalSince1970.description
        message.isSelf = false
        let body = YHAIMessageBody()
        body.contentType = YHAIMessageType.text.rawValue
        body.contentText = text
        message.setDone()
        message.body = body
        message.updateBodyToData()
        return message
    }
    
    static func createPictureMessage(imgType: Int, url: String, downloadUrl: String) -> YHAIChatMessage {
        let message = YHAIChatMessage()
        message.messageId = UUID().uuidString + NSDate().timeIntervalSince1970.description
        message.isSelf = false
        let body = YHAIMessageBody()
        message.setDone()
        body.contentType = YHAIMessageType.picture.rawValue
        let imgInfo = YHAIImageInfo()
        imgInfo.imageType = imgType
        imgInfo.imageUrl = url
        imgInfo.imageDownloadUrl = downloadUrl
        body.imageInfo = imgInfo
        message.body = body
        message.updateBodyToData()
        return message
    }
    
    func updateBodyToData() {
        dataDict = body.toDictionary() ?? [:]
        data = self.dicToJSONString(dict: dataDict)
    }
    
    func updateDataToBody() {
        
    }
    
    func dicToJSONString(dict: [String: Any]) -> String {
        if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
            return String(data: jsonData, encoding: .utf8) ?? ""
        }
        return ""
    }
    
    //
    func isUserfulMessage() -> Bool {
        if !self.body.isStart() {
            return true
        }
        return false
    }
    
    // 获取消息类型
    func getType() -> YHAIMessageType {
        if let contentType = dataDict["contentType"] as? Int {
            if contentType == YHAIMessageType.thinking.rawValue {
                return .thinking
            }
            if contentType == YHAIMessageType.text.rawValue {
                if let type = dataDict["type"] as? String {
                    if type == "follow_up" {
                        return .recommendText
                    }
                }
                return .text
            }
            if contentType == YHAIMessageType.cardList.rawValue {
                return .cardList
            }
            
            if contentType == YHAIMessageType.picture.rawValue {
                return .picture
            }
            if contentType == YHAIMessageType.productList.rawValue {
                return .productList
            }
        }
        return .unknown
    }
    
    // 获取文字消息的文字
    func getText() -> String {
        let msgType = getType()
        if msgType == .text || msgType == .recommendText {
            if let text = dataDict["contentText"] as? String, !text.isEmpty {
                return text
            }
        }
        return ""
    }
    
    var description: String {
        return "uudi:\(messageId)\n id:\(id)\n event:\(event)\n data:\(data)\n \n"
    }
}

class YHAIMessageBody: SmartCodable, NSCopying {
    
    var contentType: Int = 0
    var contentText: String = ""
    var contentTextIndex: Int = 0
    var chatId: String = ""
    var botId: String = ""
    var status: String = ""
    var type: String = ""
    var cardsInfo: YHAIListInfoModel?
    var imageInfo: YHAIImageInfo?
    
    func isStart() -> Bool {
        if status == "start" {
            return true
        }
        return false
    }
    
    func isDone() -> Bool {
        if status == "done" {
            return true
        }
        return false
    }
    
    func copy(with zone: NSZone? = nil) -> Any {
        let body = YHAIMessageBody()
        body.contentType = self.contentType
        body.contentText = self.contentText
        body.chatId = self.chatId
        body.botId = self.botId
        body.status = self.status
        body.type = self.type
        return body
    }
    
    required init() {
        
    }
    
//    var description: String {
//        return "contentType:\(contentType)\n contentText: \(contentText)\n type: \(type)\n status: \(status))\n"
//    }
}

enum YHAIJumpPageType: String {
    // customerVoice -> APP客户心声  productList -> APP-首页银河甄选  AppServiceTab -> 服务页
    case customerHeart = "customerVoice" // APP客户心声
    case galaxySelect = "productList" // APP-首页银河甄选
    case appServiceTab = "AppServiceTab" // 服务页
}

class YHAIListInfoModel: SmartCodable {
    
    var title: String = ""
    var icon: String = ""
    var description: String = ""
    var btnText: String = ""
    var list: [YHAIListItemModel] = []
    var redirectMode: Int = 0 // 跳转模式 0: 不跳转 1：web页面跳转 2：APP跳转 3：Agent跳转
    // customerVoice -> APP客户心声  productList -> APP-首页银河甄选
    var redirectPath: String = ""
    var businessType: String = ""
    
    // 是否是测评
    func isEvaluation() -> Bool {
        return businessType == "evaluation"
    }
    
    required init() {
        
    }
}

class YHAIListItemModel: SmartCodable {
    
    var title: String = ""
    var cover: String = ""
    var description: String = ""
    var redirectMode: Int = 0 // 跳转模式 0: 不跳转 1：web页面跳转 2：APP跳转 3：Agent跳转
    // customerVoice -> APP客户心声  productList -> APP-首页银河甄选
    var redirectPath: String = ""
    var tags: [YHProductTag] = []
    var originalPrice: String = ""
    var discountPrice: String = ""
    
    required init() {
        
    }
}

class YHProductTag: SmartCodable {
    
    var text: String = ""
    var color: String = ""
    
    required init() {
        
    }
}

enum YHAIImageType: Int {
    case url = 1
    case local = 2
}

class YHAIImageInfo: SmartCodable {
    
    var imageType: Int = 0  // 0 url图片 1本地图片
    var imageUrl: String = ""
    var imageDownloadUrl: String = ""
    var localImageName: String = ""
    
    required init() {
        
    }
}
