//
//  TSChatViewController+SendMsg.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/17.
//

extension TSChatViewController {
    
    func inputSendMsg(_ data: [Any]) {
        
        //判断 vip
        if kJudgeVip(externalBool: kPurchaseDefault.freeNumAvailable(type: .aichat) == false, vc: self, closePageBlock: {[weak self] in
            guard let self = self else { return }
        }){ return }
        
        sendMessages(data)
        messagesCollectionView.scrollToLastItem(animated: true)
        view.endEditing(true)
    }
    
    
    private func sendMessages(_ data: [Any]) {
        let user = viewModel.kUserSender
        for component in data {
            if let str = component as? String {
                let message = TSChatMessage(text: str, user: user, messageId: UUID().uuidString, date: Date())
                insertMessage(message)
                //保存这条消息到本地数据库
                //发送消息后,进行AI 对话生成
                generativeAIChat(message: message)
            }
        }
    }
    
    func generativeAIChat(message:TSChatMessage) {
        var messageString = ""
        switch message.kind {
        case .text(let message):
            messageString = message
        default:
            break
        }
        
        if messageString.count == 0 {
            return
        }
        
        let message = TSChatMessage(attributedText: kMDAttributedString(text: ""), user: viewModel.kAIUser, messageId: UUID().uuidString, date: Date())
        message.sendState = .start
        insertMessage(message)
        
        inputBarVC.sendEnabled(enabled: false)
        viewModel.sendChatMessage(message: messageString) {[weak self] string in
            guard let self = self else { return }
            debugPrint("viewModel.AiMDString=\(viewModel.AiMDString)")
            message.kind = .attributedText(kMDAttributedString(text: viewModel.AiMDString))
            message.sendState = .progress(0.5)
            updataAIChatCellUI()
            
        } completion: {[weak self] data, error in
            guard let self = self else { return }
            if let netData = data {
                message.sendState = .success("netData")
                //保存这条消息到本地数据库
                //消耗一次 AI 次数
                kPurchaseDefault.useOnceForFree(type: .aichat)
                
            }else {
                message.kind = .attributedText(kMDAttributedString(text: kAIErrorString))
                message.sendState = .failed(kAIErrorString)
                //保存这条消息到本地数据库
            }
            updataAIChatCellUI()
            
            kExecuteOnMainThread {
                self.inputBarVC.sendEnabled(enabled: true)
                
                //更新 Vip
                if kPurchaseDefault.isVip == false{
                    self.updateVipView()
                }
                
//                self.messagesCollectionView.scrollToLastItem(animated: false)
            }
        }
    }
    
    func updataAIChatCellUI(){
        kExecuteOnMainThread {
            if self.messageList.count >= 2 {
                UIView.performWithoutAnimation {
                    self.messagesCollectionView.reloadItems(at: [self.lastIndexPath])
                }
            }else{
                self.messagesCollectionView.reloadData()
            }
        }
    }
    

}
