//
//  YHAIRobotChatViewController.swift
//  galaxy
//
//  Created by Dufet on 2024/11/29.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//
import UIKit
import Alamofire
import IQKeyboardManagerSwift
import JXSegmentedView

class YHAIRobotChatViewController: YHBaseViewController {

    var myTitle: String = ""
    var robotId: String = ""
    var listItemId: Int = 0
    var isUserScrolling: Bool = false
    var lastUserScrollTime: CFTimeInterval = 0.0
    let minimumScrollInterval: CFTimeInterval = 2.0
    var conversationId: String = ""
    var messages:[YHAIChatMessage] = []
    var isNeedShowBannerHeader: Bool = false
    var robotType: String = ""
    let manager = YHAIRequestManager()
    let viewModel = YHAIViewModel()

    lazy var chatConfig: YHAIChatConfiguration = {
        let config = YHAIChatConfiguration()
        return config
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRectMake(0, 0, k_Height_NavigationtBarAndStatuBar, KScreenHeight-k_Height_NavigationtBarAndStatuBar-64-k_Height_safeAreaInsetsBottom()), 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 bgImgView: UIImageView = {
        let v = UIImageView(image: UIImage(named: "ai_chat_bg"))
        return v
    }()
    
    lazy var bottomInputView: YHAITextInputView = {
        let v = YHAITextInputView(frame: .zero)
        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 cleanBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "msg_clean"), for: .normal)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        btn.addTarget(self, action: #selector(didCleanButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var thinkingMessage: YHAIChatMessage = {
        let msg = YHAIChatMessage.createThinkingMesssage()
        return msg
    }()
    
    lazy var bannerView: YHAIChatBannerView = {
        
        let view = YHAIChatBannerView(frame: CGRectMake(0, 0, KScreenWidth, 360))
        view.bgImgV.image = getBannerBg()
        view.titleLabel.text = getHeaderTitle()
        view.descLabel.text = getHeaderDesc()
        view.bannerArr = self.getBannerForRobotType(robotType)
        view.messages = getFlowMessages()
        view.selectFlowMsgBlock = {
            [weak self] text in
            guard let self = self else { return }
            if self.isNeedStopResonse() {
                self.stopAutoResponse { success in
                    self.sendMessage(text, true)
                }
            } else {
                self.sendMessage(text, true)
            }
        }
        view.selectBannerItemBlock = {
            [weak self] model in
            guard let self = self else { return }
            var text = ""
            if !model.msg.isEmpty {
                text = model.msg
                
            } else if !model.desc.isEmpty {
                text = model.desc
            }

            if self.isNeedStopResonse() {
                self.stopAutoResponse { success in
                    self.sendMessage(text, true)
                }
            } else {
                self.sendMessage(text, true)
            }
        }
        return view
    }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        gk_navBarAlpha = 0
        IQKeyboardManager.shared.isEnabled = false
        view.backgroundColor = .clear
        view.addSubview(bgImgView)
        
        gk_navTitle = myTitle
        gk_navTitleColor = .mainTextColor
        gk_navigationBar.addSubview(cleanBtn)
        
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomInputView)
        self.view.addSubview(self.bgImgView)
        self.view.insertSubview(bgImgView, belowSubview: gk_navigationBar)
        
        if self.isNeedShowBannerHeader {
            self.tableView.tableHeaderView = self.bannerView
        } else {
            self.tableView.tableHeaderView = nil
        }
        
        cleanBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        
        bgImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-64-k_Height_safeAreaInsetsBottom())
        }
        bottomInputView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
        }
        
        getHistoryMessages()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.bottomInputView.showKeyBoard(false)
    }
    
    @objc override func backItemClick(_ sender: Any) {
        
        if self.isNeedStopResonse() {
            self.stopAutoResponse { success in
            
            }
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    func reloadAndScrollToBottom(_ forceScrollToBottom: Bool = false, _ isNeedAccurate: Bool = false) {
        
        self.tableView.reloadData()
        
        if !forceScrollToBottom && !canTriggerProgrammaticScroll() {
            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.chatConfig.removeThinkingMessageFromChatList(&messages)
        let question = YHAIChatMessage.createQuestionMessage(text)
        messages.append(question)
        messages.append(thinkingMessage)
        self.bottomInputView.status = .loading
        self.chatConfig.disableHandleMessage = false
        self.manager.disableHandleMessage = false
        self.reloadAndScrollToBottom(forceScrollToBottom)
        
        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(forceScrollToBottom)
        }
    }
        
    func getHistoryMessages() {
        
        viewModel.getHistoryChatMessages(botId: robotId, conversationId: conversationId, messageId: "") {
            [weak self] success, error in
            guard let self = self else { return }
            
            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)
            reloadAndScrollToBottom(true, true)
            
            autoResponseLocalTextMessage()
        }
    }
    
    func autoResponseLocalTextMessage() {
        if messages.count <= 0 {
            if robotType == YHAIRobotType.sale.rawValue {
                let text = "你好，我是新港生活规划师，如果您有关于香港身份政策或者办理细节方面的问题，可以随时问我哦。"
                let msg = self.chatConfig.createRobotResponseTextMessage(text)
                messages.append(msg)
                
            } else if robotType == YHAIRobotType.main.rawValue {
                let text = "您好，我是港小宝，为新中产提供一站式服务。您有香港身份和生活的问题，可以咨询我~"
                let msg = self.chatConfig.createRobotResponseTextMessage(text)
                messages.append(msg)
            }
        }
        
        if robotType == YHAIRobotType.image.rawValue {
            let previewUrl = "https://prod-cdn-pub.galaxy-immi.com/5000000/chats/mask_group.jpg"
            let msg = self.chatConfig.createRobotResponseLocalPictureMessage("ai_auto_chat_img", previewUrl:previewUrl)
            messages.append(msg)
        }
        self.reloadAndScrollToBottom(true)
    }
    
    func uploadEvaluationMessage(_ msg: YHAIChatMessage, callback:((Bool)->())? = nil) {
        viewModel.createMessage(conversationId: conversationId, role: "assistant", msg: msg) {
            success, error in
            callback?(success)
        }
    }
    
    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
            
        }
    }
    
    @objc func didCleanButtonClicked() {
        
        YHCommonAlertView.show("删除历史记录", "删除后记录无法恢复", "取消", "删除", fullGuestureEnable: false) {
            
        } callBack: {
            self.manager.clearLobalSubRobotConversationIdForListItemId("\(self.listItemId)")
            self.viewModel.requestConversationId { sessionId in
                if !sessionId.isEmpty {
                    self.conversationId = sessionId
                    self.manager.saveLobalSubRobotConversationId(sessionId, listItemId: "\(self.listItemId)")
                    self.messages.removeAll()
                    self.tableView.reloadData()
                    YHHUD.flash(message: "清除成功")
                }
            }
        }
    }
    
    func getBannerBg() -> UIImage? {
        if robotType == YHAIRobotType.education.rawValue {
            return UIImage(named: "ai_chat_header_bg_1")

        } else if robotType == YHAIRobotType.sale.rawValue {
            return UIImage(named: "ai_chat_header_bg_0")
        }
        return UIImage(named: "ai_chat_header_bg_0")
    }
    
    func getFlowMessages() -> [String] {
        
        if robotType == YHAIRobotType.education.rawValue {
            return  ["香港教育有哪些优势？", "去香港读书有哪些条件？", "申请香港学校费用是多少？", "了解银河教育插班服务流程", "了解银河教育插班录取率"]

        } else if robotType == YHAIRobotType.sale.rawValue {
            return  ["优才学历加分要求是什么？", "优才现在要怎么申请？", "墨尔本大学是优才合资格大学吗？", "推荐一些优才产品"]

        }
        return []
    }
    
    func getHeaderTitle() -> String {
        
        if robotType == YHAIRobotType.education.rawValue {
            return "Hello，我是香港教育宝"

        } else if robotType == YHAIRobotType.sale.rawValue {
            return  "Hello，我是新港生活规划师"
        }
        return ""
    }
    
    func getHeaderDesc() -> String {
        
        if robotType == YHAIRobotType.education.rawValue {
            return "有香港教育的问题尽管问我"

        } else if robotType == YHAIRobotType.sale.rawValue {
            return  "香港身份办理问题可以找我"
        }
        return ""
    }
    
    func getBannerForRobotType(_ robotType: String) -> [YHAIChatBannerItem] {
        
        if robotType == YHAIRobotType.sale.rawValue {
            return  [YHAIChatBannerItem(id: 0, title: "了解银河集团", desc: "香港身份生活一站式服务平台", msg: "银河集团，能够为我提供什么？"),
                     YHAIChatBannerItem(id: 1, title: "香港身份智能评估", desc: "20s快速评估，了解自身条件是否符合", msg: "开始身份办理评估"),
                     YHAIChatBannerItem(id: 2, title: "银河产品矩阵", desc: "香港身份、生活多样产品", msg: "介绍一下银河的产品"),]
           
        }
        if robotType == YHAIRobotType.education.rawValue {
            return  [YHAIChatBannerItem(id: 0, title: "幼中小学升学", desc: "去香港插班需要考核哪些"),
                     YHAIChatBannerItem(id: 1, title: "大学升学", desc: "DSE分数和Alevel的换算关系"),
                     YHAIChatBannerItem(id: 2, title: "银河教育服务", desc: "银河教育插班成功率如何？"),]
        }
        return []
    }
    
    func isNeedStopResonse() -> Bool {
        return self.bottomInputView.status == .loading
    }
}

extension YHAIRobotChatViewController: 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 msg.isTextMessage() {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHAITextMessageCell.cellReuseIdentifier, for: indexPath) as!  YHAITextMessageCell
                cell.message = msg
                cell.messageClick = {
                    [weak self] text in
                    guard let self = self else { return }
                    
                    if self.isNeedStopResonse() {
                        self.stopAutoResponse { success in
                            self.sendMessage(text, true)
                        }
                    } else {
                        self.sendMessage(text, true)
                    }
                }
                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 !message.isTextMessage() {
                return UITableView.automaticDimension
            }
            
            let text = message.body.contentText // 要显示的文本内容
            let font = UIFont.PFSC_R(ofSize: 14) // 字体大小
            let maxWidth = KScreenWidth-20*2-16*2 // 最大宽度限制
            
            let attributes = [NSAttributedString.Key.font : font] as [NSAttributedString.Key : Any]
            let size = (text as NSString).boundingRect(with: CGSize(width: maxWidth, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size

            var textHeight = ceil(size.height)
            if textHeight < 20.0 {
                textHeight = 20.0
            }
            
            if message.isSelf || msgType == .recommendText {
                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 UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    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 tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isUserScrolling = true
        lastUserScrollTime = CACurrentMediaTime()
    }
        
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            isUserScrolling = false
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        isUserScrolling = false
        lastUserScrollTime = CACurrentMediaTime()
    }
    
    // 检查是否可以执行代码触发的滚动
    func canTriggerProgrammaticScroll() -> Bool {
        let currentTime = CACurrentMediaTime()
        return (currentTime - lastUserScrollTime) >= minimumScrollInterval
    }
}

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


