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

import UIKit
import Alamofire
import IQKeyboardManagerSwift
import JXSegmentedView

class YHAIMainChatViewController: YHBaseViewController {

    var robotId: String = ""
    var conversationId: String = ""
    var isNeedAutoResponseImage = false
    var isHaveAutoResponseText = false
    var messages:[YHAIChatMessage] = []
    var disableScrollToBottom: Bool = false
    let manager = YHAIRequestManager()
    let viewModel = YHAIViewModel()
    
    lazy var chatConfig: YHAIChatConfiguration = {
        let config = YHAIChatConfiguration()
        return config
    }()

    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        chatConfig.registerMessageGroupCells(tableView)
        return tableView
    }()
    
    lazy var bottomInputView: YHAITextInputView = {
        let v = YHAITextInputView(frame: .zero)
        v.backgroundColor = .clear
        v.sendBlock = {
            [weak self] text in
            guard let self = self else { return }
            self.sendMessage(text)
        }
        v.stopSendBlock = {
            [weak self] in
            guard let self = self else { return }
            self.stopAutoResponse()
        }
        return v
    }()
    
    lazy var thinkingMessage: YHAIChatMessage = {
        let msg = YHAIChatMessage.createThinkingMesssage()
        return msg
    }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = .clear
        IQKeyboardManager.shared.isEnabled = false
        
        gk_navTitle = "AI对话"
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomInputView)
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(0)
            make.bottom.equalTo(-66-k_Height_safeAreaInsetsBottom())
        }
        
        bottomInputView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
        }
        
        self.manager.getMainChatConversationId {
            sesseionId in
            self.conversationId = sesseionId
            self.getHistoryMessages()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        autoResponseTextMessage()

    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.bottomInputView.showKeyBoard(false)
    }
    
    func reloadAndScrollToBottom() {
        
        self.tableView.reloadData()
        
        if disableScrollToBottom {
            return
        }
        
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            
            // 使用 UIView.animate 实现更丝滑的滚动效果
            UIView.animate(withDuration: 0.5,
                           delay: 0,
                           usingSpringWithDamping: 1.0, // 弹簧阻尼，控制回弹效果
                           initialSpringVelocity: 0.3,  // 初始速度
                           options: [.curveEaseOut, .allowUserInteraction],
                           animations: {
                
                if self.messages.count > 0 {
                    let lastIndexPath = IndexPath(row: self.messages.count-1, section: 0)
                    self.tableView.scrollToRow(at: lastIndexPath, at: .bottom, animated: false)
                }
                
            }, completion: nil)
        }
    }
    
    func sendMessage(_ text: String, _ forceScrollToBottom: Bool = false) {
        self.manager.getMainChatConversationId {
            sesseionId in
            self.conversationId = sesseionId
            self.chatConfig.removeThinkingMessageFromChatList(&self.messages)
            let question = YHAIChatMessage.createQuestionMessage(text)
            self.messages.append(question)
            self.messages.append(self.thinkingMessage)
            self.bottomInputView.status = .loading
            self.chatConfig.disableHandleMessage = false
            self.manager.disableHandleMessage = false
            self.disableScrollToBottom = false
            self.reloadAndScrollToBottom()

            self.manager.requestAI(botId: self.robotId, conversationId: self.conversationId, question:text) {
                [weak self] res, done in
                guard let self = self else { return }
                self.chatConfig.handleReceiveMessage(res, done, &messages)
                if done {
                    print("RESPONSE-DONE")
                    self.bottomInputView.status = self.bottomInputView.textView.text.isEmpty ? .disableSend : .enableSend
                }
                self.reloadAndScrollToBottom()
            }
        }
    }
    
    // isPull 是否是下拉组件触发
    func getHistoryMessages() {
        viewModel.getHistoryChatMessages(botId: robotId, conversationId: conversationId, messageId: "") {
            [weak self] success, error in
            guard let self = self else { return }
            self.tableView.es.stopPullToRefresh()
            
            var results = self.viewModel.historyMessages.map {
                return $0.convertToChatMessage()
            }
        
            let uuids = messages.map {
                return $0.messageId
            }
            // 过滤掉当前相同消息
            results = results.filter {
                return !uuids.contains($0.messageId)
            }
            messages.insert(contentsOf: results, at: 0)
            autoResponseTextMessage()
            self.reloadAndScrollToBottom()
        }
    }
    
    func autoResponseTextMessage() {
        if messages.count <= 0 || !isHaveAutoResponseText {
            isHaveAutoResponseText = true
            let text = "您好，我是港小宝，为新中产提供一站式服务。您有香港身份和生活的问题，可以咨询我~"
            let msg = self.chatConfig.createRobotResponseTextMessage(text)
            messages.append(msg)
            self.reloadAndScrollToBottom()
        }
    }
    
    func stopAutoResponse(completion:((Bool)->())? = nil) {
        self.manager.cancelCurrentRequest()
        self.reloadAndScrollToBottom()
        self.chatConfig.disableHandleMessage = true
        self.manager.disableHandleMessage = true
        self.chatConfig.removeThinkingMessageFromChatList(&self.messages)
        self.bottomInputView.status = self.bottomInputView.textView.text.isEmpty ? .disableSend : .enableSend
        completion?(true)
        self.manager.stopChat(chatId: self.manager.chatId, conversationId: self.conversationId) { success, error in
            
        }
    }
    
    func uploadEvaluationMessage(_ msg: YHAIChatMessage, callback:((Bool)->())? = nil) {
        viewModel.createMessage(conversationId: conversationId, role: "assistant", msg: msg) {
            [weak self] success, error in
            guard let self = self else { return }
            callback?(success)
        }
    }
    
    @objc func didCleanButtonClicked() {
        
        YHCommonAlertView.show("删除历史记录", "删除后记录无法恢复", "取消", "删除", fullGuestureEnable: false) {
            
        } callBack: {
            self.manager.clearGlobalConverastionId()
            YHHUD.flash(message: "删除历史记录中...")
            self.viewModel.requestConversationId { sessionId in
                YHHUD.hide()
                if !sessionId.isEmpty {
                    self.conversationId = sessionId
                    self.manager.saveGlobalConverastionId(sessionId)
                    self.messages.removeAll()
                    self.tableView.reloadData()
                    YHHUD.flash(message: "清除成功")
                }
            }
        }
    }
    
    func isNeedStopResonse() -> Bool {
        return self.bottomInputView.status == .loading
    }
}

extension YHAIMainChatViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if 0 <= indexPath.row, indexPath.row < messages.count {
            let msg = messages[indexPath.row]
            let msgType = msg.getType()
            if msgType == .text {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHAITextMessageCell.cellReuseIdentifier, for: indexPath) as!  YHAITextMessageCell
                cell.message = msg
                return cell
                
            } else if msgType == .recommendText {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHRecommendTextMessageCell.cellReuseIdentifier, for: indexPath) as!  YHRecommendTextMessageCell
                cell.message = msg
                cell.messageClick = {
                    [weak self] text in
                    guard let self = self else { return }
                    self.bottomInputView.showKeyBoard(false)
                    
                    if self.isNeedStopResonse() {
                        self.stopAutoResponse { success in
                            self.sendMessage(text)
                        }
                    } else {
                        self.sendMessage(text)
                    }
                }
                return cell
                
            } else if msgType == .thinking {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHAIThinkingMessageCell.cellReuseIdentifier, for: indexPath) as!  YHAIThinkingMessageCell
                return cell
                
            } else if msgType == .productList {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHProductListMessageCell.cellReuseIdentifier, for: indexPath) as!  YHProductListMessageCell
                if let listModel = msg.body.cardsInfo {
                    cell.listModel = listModel
                }
                return cell
                
            } else if msgType == .cardList {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHCardMessageCell.cellReuseIdentifier, for: indexPath) as!  YHCardMessageCell
                if let listModel = msg.body.cardsInfo {
                    cell.cardListModel = listModel
                    cell.evaluationResultCallback = {
                        [weak self] dict in
                        guard let self = self else { return }
                        
                        // 生成测评结果文字 和测评结果图片 两种消息
                        var arr = [YHAIChatMessage]()
                        if let satisfy_count = dict["meet_number"] as? Int {
                            let text = "测评成功！优才新政策要求满足12项评核准则中的任意6项即可申请（即12分制满足6分），您当前满足\(satisfy_count)项，联系专属顾问咨询详细方案！"
                            let textMsg = YHAIChatMessage.createTextMesssage(text: text)
                            arr.append(textMsg)
                            self.uploadEvaluationMessage(textMsg)
                        }

                        if let imgUrl = dict["consultant_qr_code_with_text"] as? String {
                            var downUrl = ""
                            if let downloadImgUrl = dict["consultant_qr_code"] as? String {
                                downUrl = downloadImgUrl
                            }
                            let picMsg = YHAIChatMessage.createPictureMessage(imgType: 1, url: imgUrl, downloadUrl: downUrl)
                            arr.append(picMsg)
                            self.uploadEvaluationMessage(picMsg)
                        }
                        
                        if arr.count > 0 {
                            messages.append(contentsOf: arr)
                            self.reloadAndScrollToBottom()
                        }
                    }
                    cell.updateBlock = {
                        [weak self] in
                        guard let self = self else { return }
                        self.tableView.reloadData()
                    }
                }
                return cell
                
            } else if msgType == .picture {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHAIPictureMessageCell.cellReuseIdentifier, for: indexPath) as!  YHAIPictureMessageCell
                if let imgInfo = msg.body.imageInfo {
                    cell.imgInfo = imgInfo
                }
                cell.updateBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    self.tableView.reloadData()
                }
                return cell
            }
        }
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        defaultCell.backgroundColor = .clear
        defaultCell.contentView.backgroundColor = .clear
        return defaultCell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if 0 <= indexPath.row, indexPath.row < messages.count {
            let message = messages[indexPath.row]
            let msgType = message.getType()
            
            if msgType == .productList {
                var height = 16+70.0
                if let listModel = message.body.cardsInfo {
                    height += (120.0 * Double(listModel.list.count) + 40.0)
                }
                return height
            }
            
            if msgType == .recommendText { // 推荐文字消息
                let label = UILabel()
                label.textAlignment = .left
                label.font = UIFont.PFSC_M(ofSize:12)
                label.numberOfLines = 0
                label.text = message.body.contentText
                let maxWidth = KScreenWidth-20*2-16*2 // 最大宽度限制
                let size = label.sizeThatFits(CGSize(width: maxWidth, height: .greatestFiniteMagnitude))
                var textHeight = ceil(size.height)
                return textHeight+10.0*3.0
            }
            
            if msgType != .text  {
                return UITableView.automaticDimension
            }
            
            // 以下是文字消息计算高度
            
            let label = UILabel()
            label.textAlignment = .left
            label.font = UIFont.PFSC_R(ofSize:14)
            label.numberOfLines = 0
            
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 4.0
            
            let attributedText = NSAttributedString(
                string: message.body.contentText,
                attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle,
                             NSAttributedString.Key.font: UIFont.PFSC_R(ofSize:14)]
            )
            label.attributedText = attributedText
            
            let maxWidth = message.isSelf ? KScreenWidth-58-20-16*2 : KScreenWidth-20*2-16*2 // 最大宽度限制
            let size = label.sizeThatFits(CGSize(width: maxWidth, height: .greatestFiniteMagnitude))
            var textHeight = ceil(size.height)
            if textHeight < 20.0 {
                textHeight = 20.0
            }
            
            if message.isSelf {
                return textHeight + 16.0*2 + 16.0
            }
            
            let complete = message.isDone
            let isNeedShowCopyView = complete
            let isNeedShowLoadingView = !complete
            
            var resultHeight = textHeight+16.0*2.0
            if isNeedShowLoadingView {
                resultHeight += (18+6)
            }
            
            if isNeedShowCopyView {
                resultHeight += (16+37)
            } else {
                resultHeight += 16
            }
            return resultHeight
        }
        
        return 0.0
    }

    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 40.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        disableScrollToBottom = true
        self.bottomInputView.showKeyBoard(false)
    }
        
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    
    }
}

extension YHAIMainChatViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

