//
//  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 disableScrollToBottom: Bool = false
    var isHaveAutoResponseText = false
    var conversationId: String = ""
    var messages: [YHAIChatMessage] = []
    var isNeedShowBannerHeader: Bool = false
    var robotType: String = ""
    let manager = YHAIRequestManager()
    let viewModel = YHAIViewModel()
    var flowMessages: [String] = []

    lazy var chatConfig: YHAIChatConfiguration = {
        let config = YHAIChatConfiguration()
        return config
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: k_Height_NavigationtBarAndStatuBar, height: 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.frame = CGRect(x: KScreenWidth-24-20, y: k_Height_statusBar()+k_Height_NavContentBar/2.0-12, width: 24, height: 24)
        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 bgImgHeight = 242.0/335.0 * (KScreenWidth-40.0)
        let height = 350.0-242.0+bgImgHeight
        let view = YHAIChatBannerView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: height))
        view.config = getBannerConfig()
        view.selectFlowMsgBlock = {
            [weak self] text in
            guard let self = self else { return }
            if self.isNeedStopResonse() {
                self.stopAutoResponse { _ 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 { _ 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
        
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomInputView)
        self.view.addSubview(self.bgImgView)
        self.view.insertSubview(bgImgView, belowSubview: gk_navigationBar)

        self.gk_navigationItem.rightBarButtonItem = UIBarButtonItem.gk_item(image: UIImage(named: "msg_clean"), target: self, action: #selector(didCleanButtonClicked))
        
        if self.isNeedShowBannerHeader {
            self.tableView.tableHeaderView = self.bannerView
        } else {
            self.tableView.tableHeaderView = nil
        }
        
        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 { _ in
            
            }
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    func getBotConfig() {
        self.viewModel.getBotConfigInfoWithBotId(self.robotId) {
            [weak self] _, _ in
            guard let self = self else { return }
            self.flowMessages.removeAll()
            self.flowMessages.append(contentsOf: self.viewModel.botConfig.onboardingInfo.suggestedQuestions)
            
            if self.flowMessages.count > 0 {
                self.bannerView.messages = self.flowMessages

            } else {
                if robotType == YHAIRobotType.sale.rawValue {
                    self.bannerView.messages = ["优才学历加分要求是什么？", "优才现在要怎么申请？", "墨尔本大学是优才合资格大学吗？", "推荐一些优才产品"]
                    
                } else if robotType == YHAIRobotType.education.rawValue {
                    self.bannerView.messages = ["香港教育有哪些优势？", "去香港读书有哪些条件？", "申请香港学校费用是多少？", "了解银河教育插班服务流程", "了解银河教育插班录取率"]
                }
            }
            autoResponseLocalTextMessage()
        }
        
    }
    
    func reloadAndScrollToBottom() {
        
        self.tableView.reloadData()
        
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            
            if disableScrollToBottom {
                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.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()
        }
    }
        
    func getHistoryMessages() {
        
        viewModel.getHistoryChatMessages(botId: robotId, conversationId: conversationId, messageId: "") {
            [weak self] _, _ 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()
            getBotConfig()
        }
    }
    
    func autoResponseTextMessage(_ message: String) {
        if message.isEmpty {
            return
        }
        if messages.count <= 0 || !isHaveAutoResponseText {
            isHaveAutoResponseText = true
            let msg = self.chatConfig.createRobotResponseTextMessage(message)
            messages.append(msg)
            self.reloadAndScrollToBottom()
        }
    }
    
    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 message = self.viewModel.botConfig.onboardingInfo.prologue
                autoResponseTextMessage(message)
            }
        }
        
        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()
    }
    
    func uploadEvaluationMessage(_ msg: YHAIChatMessage, callback: ((Bool) -> Void)? = nil) {
        viewModel.createMessage(conversationId: conversationId, role: "assistant", msg: msg) {
            success, _ in
            callback?(success)
        }
    }
    
    func stopAutoResponse(completion: ((Bool) -> Void)? = 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) { _, _ in
            
        }
    }
    
    @objc func didCleanButtonClicked() {
        
        YHCommonAlertView.show("删除历史记录", "删除后记录无法恢复", "取消", "删除", fullGuestureEnable: false) {
            
        } callBack: {
            self.manager.clearLobalSubRobotConversationIdForListItemId("\(self.listItemId)")
            YHHUD.flash(message: "删除历史记录中...")
            self.viewModel.requestConversationId { sessionId in
                YHHUD.hide()
                if !sessionId.isEmpty {
                    self.conversationId = sessionId
                    self.manager.saveLobalSubRobotConversationId(sessionId, listItemId: "\(self.listItemId)")
                    self.messages.removeAll()
                    self.tableView.reloadData()
                    YHHUD.flash(message: "清除成功")
                }
            }
        }
    }
    
    func getBannerConfig() -> YHAIChatBannerViewConfig {
        
        let config = YHAIChatBannerViewConfig()
        
        if robotType == YHAIRobotType.sale.rawValue {
            config.title = "Hello，我是新港生活规划师"
            config.bannerTitleColor = .brandMainColor
            config.desc = "香港身份办理问题可以找我"
            config.bgColor = .init(hex: 0xE6F4FF)
            config.indicatorColor = .brandMainColor
            config.bgImageName = "ai_chat_header_bg_0"
            config.bannerItems =  [YHAIChatBannerItem(id: 0, title: "了解银河集团", desc: "香港身份生活一站式服务平台", msg: "银河集团，能够为我提供什么？"),
                                   YHAIChatBannerItem(id: 1, title: "香港身份智能评估", desc: "20s快速评估，了解自身条件是否符合", msg: "开始身份办理评估"),
                                   YHAIChatBannerItem(id: 2, title: "银河产品矩阵", desc: "香港身份、生活多样产品", msg: "介绍一下银河的产品") ]
            
        } else if robotType == YHAIRobotType.education.rawValue {
            config.title = "Hello，我是香港教育宝"
            config.bannerTitleColor = .init(hex: 0x00C77C)
            config.desc = "有香港教育的问题尽管问我"
            config.bgColor = .init(hex: 0xDAF6FC)
            config.indicatorColor = .init(hex: 0x00C77C)
            config.bgImageName = "ai_chat_header_bg_1"
            config.bannerItems =  [YHAIChatBannerItem(id: 0, title: "幼中小学升学", desc: "去香港插班需要考核哪些"),
                                   YHAIChatBannerItem(id: 1, title: "大学升学", desc: "DSE分数和Alevel的换算关系"),
                                   YHAIChatBannerItem(id: 2, title: "银河教育服务", desc: "银河教育插班成功率如何？") ]
            
        } else if robotType == YHAIRobotType.business.rawValue {
            config.title = "Hello，我是银河商务规划师"
            config.bannerTitleColor = .brandMainColor
            config.desc = "企业问题都可以找我～"
            config.bgColor = .init(hex: 0xE6F4FF)
            config.indicatorColor = .brandMainColor
            config.bgImageName = "ai_chat_header_bg_2"
            config.bannerItems =  [YHAIChatBannerItem(id: 0, title: "注册公司KYC", desc: "公司注册时，KYC或尽职调查文件的目的是什么?"),
                                   YHAIChatBannerItem(id: 1, title: "雇员个税", desc: "具体计算薪俸税税率时，雇员个税如何计算？"),
                                   YHAIChatBannerItem(id: 2, title: "香港公司取名", desc: "选择香港公司的名称有什么限制，跟内地有什么区别？") ]
            
        }
        return config
    }
    
    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 {
        
        var msgType = YHAIMessageType.unknown
        var msg = YHAIChatMessage()
        if 0 <= indexPath.row, indexPath.row < messages.count {
            msg = messages[indexPath.row]
            msgType = msg.getType()
            if msgType == .text {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHAITextMessageCell.cellReuseIdentifier, for: indexPath) as?  YHAITextMessageCell else {
                    return UITableViewCell()
                }
                cell.message = msg
                return cell
                
            } else if msgType == .recommendText {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHRecommendTextMessageCell.cellReuseIdentifier, for: indexPath) as?  YHRecommendTextMessageCell else {
                    return UITableViewCell()
                }
                cell.message = msg
                cell.messageClick = {
                    [weak self] text in
                    guard let self = self else { return }
                    
                    if self.isNeedStopResonse() {
                        self.stopAutoResponse { _ in
                            self.sendMessage(text, true)
                        }
                    } else {
                        self.sendMessage(text, true)
                    }
                }
                return cell
                
            } else if msgType == .thinking {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHAIThinkingMessageCell.cellReuseIdentifier, for: indexPath) as?  YHAIThinkingMessageCell else {
                    return UITableViewCell()
                }
                return cell
                
            } else if msgType == .productList {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHProductListMessageCell.cellReuseIdentifier, for: indexPath) as?  YHProductListMessageCell else {
                    return UITableViewCell()
                }
                if let listModel = msg.body.cardsInfo {
                    cell.listModel = listModel
                }
                return cell
                
            } else if msgType == .cardList {
                
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHCardMessageCell.cellReuseIdentifier, for: indexPath) as?  YHCardMessageCell else {
                    return UITableViewCell()

                }
                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 {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHAIPictureMessageCell.cellReuseIdentifier, for: indexPath) as? YHAIPictureMessageCell else {
                    return UITableViewCell()
                }
                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 == .unknown {
                return 0.0
            }
            
            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))
                let 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, 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 40.0
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        printLog("DisableScrollToBottom")
        disableScrollToBottom = true
        self.bottomInputView.showKeyBoard(false)
    }
        
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
       
    }
}

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