// YHIMMessageHandler.swift
import UIKit
import SafariServices
import TUIConversation
import TUIChat
import IQKeyboardManagerSwift

class YHIMMessageHandler: NSObject {
    weak var viewController: UIViewController?
    weak var navigationController: UINavigationController?
    
    private lazy var previewFileTool: YHFilePreviewTool = {
        guard let vc = viewController else { fatalError("ViewController不能为空") }
        return YHFilePreviewTool(targetVC: vc)
    }()
    
    init(viewController: UIViewController,
         navigationController: UINavigationController?) {
        self.viewController = viewController
        self.navigationController = navigationController
        super.init()
    }
}

// MARK: - TUIYHCustomCellClickDelegate
extension YHIMMessageHandler: TUIYHCustomCellClickDelegate {
    
    func didTap(inFileCell cellData: TUIFileMessageCellData) {        
        var isExist: ObjCBool = false
        let path = cellData.getFilePath(&isExist)
        
        if isExist.boolValue {
            let url = URL(fileURLWithPath: path)
            previewFileTool.openXLSXFile(at: url, fileName: cellData.fileName)
        } else {
            cellData.downloadFile()
        }
    }
    
    func didTapCustomOrderCell(_ cellData: TUIOrderCellData) {
        let linkAddress = cellData.link ?? ""
        
        // 处理普通URL
        if linkAddress.count > 0,
           linkAddress.isValidHttpUrl || linkAddress.isValidHttpsUrl || linkAddress.isValidFileUrl,
           let url = URL(string: linkAddress) {
            showSafari(url: url)
            return
        }
        
        // 处理自定义消息
        handleCustomMessage(linkAddress)
    }
    
    private func handleCustomMessage(_ content: String?) {
        guard let dicData = content,
              !dicData.isEmpty,
              let data = dicData.data(using: .utf8),
              let jsonObject = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              !jsonObject.isEmpty else {
            printLog("消息解析失败")
            return
        }
        
        let msgType = jsonObject["msg_type"] as? String ?? ""
        let navH5Url = jsonObject["nav_h5_url"] as? String ?? ""
        let orderID = jsonObject["order_id"] as? Int ?? -1
        let type = jsonObject["type"] as? Int ?? -1
        let batchId = jsonObject["batch_id"] as? Int ?? 0
        
        if msgType == "card_msg", navH5Url.count > 0 {
            let title = jsonObject["title"] as? String ?? ""
            showH5Page(baseUrl: navH5Url, title: title)
        } else if orderID > -1, type > -1 {
            showOrderMessage(type: type, orderId: orderID, batchId: batchId)
        }
    }
}

// MARK: - 公开方法
extension YHIMMessageHandler {
    
    /// 处理IM消息点击
    /// - Parameter conversationData: 会话数据
    @MainActor func handleIMMessageTap(conversationData: TUIConversationCellData) {
        updateNavigateBarBeforeEnterChatVC()
        
        let params: [String: Any] = [
            TUICore_TUIChatObjectFactory_ChatViewController_Title: conversationData.title,
            TUICore_TUIChatObjectFactory_ChatViewController_UserID: conversationData.userID,
            TUICore_TUIChatObjectFactory_ChatViewController_GroupID: conversationData.groupID,
            TUICore_TUIChatObjectFactory_ChatViewController_AvatarImage: conversationData.avatarImage,
            TUICore_TUIChatObjectFactory_ChatViewController_AvatarUrl: conversationData.faceUrl,
            TUICore_TUIChatObjectFactory_ChatViewController_ConversationID: conversationData.conversationID,
            TUICore_TUIChatObjectFactory_ChatViewController_AtTipsStr: conversationData.atTipsStr,
            TUICore_TUIChatObjectFactory_ChatViewController_AtMsgSeqs: conversationData.atMsgSeqs,
            TUICore_TUIChatObjectFactory_ChatViewController_Draft: conversationData.draftText
        ]
        
        pushToChatViewController(with: params)
    }
    
    /// 处理远程通知
    /// - Parameter userInfo: 通知数据
    @MainActor func handleRemoteNotification(_ userInfo: [AnyHashable: Any]) {
        let extString = userInfo["ext"] as? String ?? "{}"
        let extData = extString.data(using: .utf8) ?? Data()
        let ext = (try? JSONSerialization.jsonObject(with: extData, options: [])) as? [String: Any] ?? [:]
        let entity = ext["entity"] as? [String: Any] ?? [:]
        let chatType = entity["chatType"] as? Int ?? 0
        let senderID = entity["sender"] as? String ?? ""
        let nickName = entity["nickname"] as? String ?? ""
        let aps = userInfo["aps"] as? [String: Any] ?? [:]
        let alert = aps["alert"] as? [String: Any] ?? [:]
        let title = alert["title"] as? String ?? nickName
        
        guard senderID.count > 0 else { return }
        
        updateNavigateBarBeforeEnterChatVC()
        
        var param: [String: Any] = [
            TUICore_TUIChatObjectFactory_ChatViewController_Title: title,
            TUICore_TUIChatObjectFactory_ChatViewController_AvatarUrl: "",
            TUICore_TUIChatObjectFactory_ChatViewController_AtTipsStr: "",
            TUICore_TUIChatObjectFactory_ChatViewController_AtMsgSeqs: [],
            TUICore_TUIChatObjectFactory_ChatViewController_Draft: ""
        ]
        
        if chatType == 2 { // 群聊
            param[TUICore_TUIChatObjectFactory_ChatViewController_GroupID] = senderID
            param[TUICore_TUIChatObjectFactory_ChatViewController_ConversationID] = "group_\(senderID)"
        } else { // 单聊
            param[TUICore_TUIChatObjectFactory_ChatViewController_UserID] = senderID
            param[TUICore_TUIChatObjectFactory_ChatViewController_ConversationID] = "c2c_\(senderID)"
        }
        
        pushToChatViewController(with: param)
    }
    
    @MainActor func gotoChatVC(senderID: String, isGroupChat: Bool = false) {
        guard senderID.count > 0 else { return }
        
        updateNavigateBarBeforeEnterChatVC()
        
        var param: [String: Any] = [
            TUICore_TUIChatObjectFactory_ChatViewController_Title: "",
            TUICore_TUIChatObjectFactory_ChatViewController_AvatarUrl: "",
            TUICore_TUIChatObjectFactory_ChatViewController_AtTipsStr: "",
            TUICore_TUIChatObjectFactory_ChatViewController_AtMsgSeqs: [],
            TUICore_TUIChatObjectFactory_ChatViewController_Draft: ""
        ]
        
        if isGroupChat { // 群聊
            param[TUICore_TUIChatObjectFactory_ChatViewController_GroupID] = senderID
            param[TUICore_TUIChatObjectFactory_ChatViewController_ConversationID] = "group_\(senderID)"
        } else { // 单聊
            param[TUICore_TUIChatObjectFactory_ChatViewController_UserID] = senderID
            param[TUICore_TUIChatObjectFactory_ChatViewController_ConversationID] = "c2c_\(senderID)"
        }
        
        pushToChatViewController(with: param)
    }
}

// MARK: - 私有方法
extension YHIMMessageHandler {
    
    /// 跳转到聊天页面(统一方法)
    private func pushToChatViewController(with params: [String: Any]) {
        let vc = navigationController?.push(
            TUICore_TUIChatObjectFactory_ChatViewController_Classic,
            param: params,
            forResult: nil
        )
        
        if let chatVC = vc as? TUIBaseChatViewController {
            chatVC.navigationItem.rightBarButtonItem = nil
            chatVC.navigationItem.rightBarButtonItems = nil
            chatVC.yhCustomCellClickDelegate = self
        }
    }
    
    /// 更新导航栏配置
    @MainActor private func updateNavigateBarBeforeEnterChatVC() {
        IQKeyboardManager.shared.isEnabled = false
        navigationController?.gk_hideNavigationBar = false
        navigationController?.isNavigationBarHidden = false
        
        let appearance = UINavigationBarAppearance()
        appearance.backgroundColor = .white
        appearance.shadowImage = UIImage()
        appearance.shadowColor = .clear
        
        navigationController?.navigationBar.tintColor = .black
        navigationController?.navigationBar.standardAppearance = appearance
        navigationController?.navigationBar.scrollEdgeAppearance = appearance
    }
    
    /// 显示Safari浏览器
    private func showSafari(url: URL) {
        let safariVC = SFSafariViewController(url: url)
        safariVC.dismissButtonStyle = .close
        safariVC.modalPresentationStyle = .fullScreen
        viewController?.present(safariVC, animated: true)
    }
    
    /// 显示H5页面(带Token)
    private func showH5Page(baseUrl: String, title: String) {
        var finalUrl = baseUrl
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let separator = baseUrl.contains("?") ? "&" : "?"
            finalUrl = baseUrl + separator + "param=" + token
        }
        
        let webVC = YHH5WebViewVC()
        webVC.isFullScreenFlag = false
        webVC.navTitle = title
        webVC.url = finalUrl
        navigationController?.pushViewController(webVC)
    }
    
    /// 显示订单消息页面
    private func showOrderMessage(type: Int, orderId: Int, batchId: Int) {
        YHServiceOrderListViewController.jumpToMessageController(
            type: type,
            orderId: orderId,
            batchId
        )
    }
}
