//
//  YHIMTestViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/11/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import HyphenateChat

class YHIMTestViewController: YHBaseViewController {
    
    private let roomID : String = "265239166779417"
    private let yHID : String = "1040217809134595"
    
    private var myTextField : UITextField?
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.
        gk_navTitle = "IM 测试"
        
        if EMClient.shared().isLoggedIn {
            YHHUD.flash(message: "已 登录IM服务器")
        } else {
            YHHUD.flash(message: "未 登录IM服务器")
        }
        
        setupUI()
        //2、处理代理回调
        EMClient.shared().roomManager?.add(self, delegateQueue: nil)
        EMClient.shared().chatManager?.add(self, delegateQueue: nil)
    }
    
    deinit {
        EMClient.shared().roomManager?.remove(self)
        EMClient.shared().chatManager?.remove(self)
    }
}

private extension YHIMTestViewController {
    func setupUI() {
        var tagView : UIView?
        
        //1.登录
        do {
            let addBtn = UIButton()
            addBtn.setTitle("1、登录IM 服务器", for: .normal)
            view.addSubview(addBtn)
            addBtn.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(80)
                make.centerX.equalToSuperview()
                make.width.equalTo(300)
                make.height.equalTo(44)
            }
            addBtn.backgroundColor = UIColor.red//for test hjl
            addBtn.addTarget(self, action: #selector(userLoginOp), for: .touchUpInside)
            tagView = addBtn
        }
        
        //2.加入聊天室
        do {
            let addBtn = UIButton()
            addBtn.setTitle("2、加入聊天室", for: .normal)
            view.addSubview(addBtn)
            if let tagView = tagView {
                addBtn.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            addBtn.backgroundColor = UIColor.red
            addBtn.addTarget(self, action: #selector(joinChatRoom), for: .touchUpInside)
            
            tagView = addBtn
        }
        
        
        //3.发送消息
        do {
            
            let textField : UITextField = UITextField()
            textField.placeholder = "请输入发送内容"
            textField.borderStyle = .line
            view.addSubview(textField)
            if let tagView = tagView {
                textField.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            tagView = textField
            
            myTextField = textField
            
            
            let addBtn = UIButton()
            addBtn.setTitle("3、发送信息", for: .normal)
            view.addSubview(addBtn)
            if let tagView = tagView {
                addBtn.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            addBtn.backgroundColor = UIColor.red
            addBtn.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
            tagView = addBtn
        }
        
        //4.获取历史消息
        do {
            let addBtn = UIButton()
            addBtn.setTitle("4、获取历史消息-需付费", for: .normal)
            view.addSubview(addBtn)
            if let tagView = tagView {
                addBtn.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            addBtn.backgroundColor = UIColor.red
            addBtn.addTarget(self, action: #selector(fetchHistoryMessage), for: .touchUpInside)
            tagView = addBtn
        }
        
        
        //5、退出聊天室
        do {
            let addBtn = UIButton()
            addBtn.setTitle("5、退出聊天室", for: .normal)
            view.addSubview(addBtn)
            if let tagView = tagView {
                addBtn.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            addBtn.backgroundColor = UIColor.red
            addBtn.addTarget(self, action: #selector(quitChatRoom), for: .touchUpInside)
            tagView = addBtn
        }
        
        
        //6.聊天室成员列表
        do {
            let addBtn = UIButton()
            addBtn.setTitle("6、聊天室成员列表", for: .normal)
            view.addSubview(addBtn)
            if let tagView = tagView {
                addBtn.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            addBtn.backgroundColor = UIColor.red
            addBtn.addTarget(self, action: #selector(fetchRoomMemberList), for: .touchUpInside)
            tagView = addBtn
        }
        
        //7、退出IM服务器
        do {
            let addBtn = UIButton()
            addBtn.setTitle("7、退出IM服务器", for: .normal)
            view.addSubview(addBtn)
            if let tagView = tagView {
                addBtn.snp.makeConstraints { make in
                    make.top.equalTo(tagView.snp.bottom).offset(20)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(300)
                    make.height.equalTo(44)
                }
            }
            addBtn.backgroundColor = UIColor.red
            addBtn.addTarget(self, action: #selector(quitIM), for: .touchUpInside)
            tagView = addBtn
        }
    }
    
    //7.聊天室成员列表
    @objc func quitIM(){
        EMClient.shared().logout(true) { err in
            if let err = err {
                YHHUD.flash(message: err.errorDescription)
            } else {
                YHHUD.flash(message: "退出IM服务器-成功")
            }
        }
    }
    
    //6.聊天室成员列表
    @objc func fetchRoomMemberList(){
        EMClient.shared().roomManager?.getChatroomMemberListFromServer(withId: roomID, cursor: nil, pageSize: 20, completion: { result, error in
            if let err = error {
                YHHUD.flash(message: err.errorDescription)
            } else {
                if let ret = result {
                    let count = (ret.list?.count ?? 0) + 1
                    YHHUD.flash(message: "聊天室人数 \(count)")
                }
            }
        })
        
    }

    
    //5.退出聊天室
    @objc func quitChatRoom(){
        EMClient.shared().roomManager?.leaveChatroom(roomID, completion: { err in
            if let error = err {
                YHHUD.flash(message: error.errorDescription)
            } else {
                YHHUD.flash(message: "退出聊天室-成功")
            }
        })
    }
    
    //4.获取历史消息
    @objc func fetchHistoryMessage(){
        let option = EMFetchServerMessagesOption()
        EMClient.shared().chatManager?.fetchMessagesFromServer(by: self.roomID, conversationType: .chatRoom, cursor: nil, pageSize: 50, option: option, completion: { result, err in
            
            DispatchQueue.main.async {
                
                if let err = err {
                    // 获取失败
                    printLog("获取历史消息--失败")
                    printLog(err)
                    
                    YHHUD.flash(message: "获取历史消息-失败")
                } else {
                    // 获取成功
                    printLog(result)
                    YHHUD.flash(message: "获取历史消息-成功")
                    
                    if let ret = result,let arr = ret.list,arr.count > 0 {
                        YHHUD.flash(message: "获取历史消息 \(arr.count) 条")
                        for (index,item) in arr.enumerated() {
                            printLog(item)
                        }
                    } else {
                        YHHUD.flash(message: "获取历史消息 (0) 条")
                    }
                }
                
            }
            DispatchQueue.main.async {
                
            }
            
        })
    }
    
    //3.发送消息
    @objc func sendMessage() {
        var sendText : String = ""
        if let tf = myTextField {
            sendText = tf.text ?? ""
        } else {
            return
        }
        
        if sendText.isEmpty {
            YHHUD.flash(message: "请输入内容")
            return
        }
        
        
        let textMessageBody = EMTextMessageBody(text: sendText)
        // 消息接收方，单聊为对端用户的 ID，群聊为群组 ID，聊天室为聊天室 ID。
        let conversationId = roomID
        let message = EMChatMessage(conversationID: conversationId, body: textMessageBody, ext:["fromNickName":"YinHe3775"])
        // 会话类型，单聊为 `EMChatTypeChat`，群聊为 `EMChatTypeGroupChat`，聊天室为 `EMChatTypeChatRoom`，默认为单聊。
        message.chatType = .chatRoom
        EMClient.shared().chatManager?.send(message, progress: nil, completion: { message, error in
            if let err = error {
                YHHUD.flash(message: err.errorDescription)
            } else {
                YHHUD.flash(message: "消息发送-成功")
            }
        })
    }
    
    //2.加入聊天室
    @objc func joinChatRoom() {
        EMClient.shared().roomManager?.joinChatroom(self.roomID, ext: "nickname=DavidTest", leaveOtherRooms: true, completion: { room, err in
            if let err = err {
                YHHUD.flash(message: err.errorDescription)
            } else {
                YHHUD.flash(message: "加入聊天室-成功")
            }
        })
    }
    
    //1.登录 IM服务器
    @objc func userLoginOp() {
        EMClient.shared().login(withUsername: yHID, token: "YWMtqUTnNKsxEe-ZVA-eCJXgmszPhuTA1UDqp8xrPJoVisk1wDGwqzER74uZ-bqVfmOVAwMAAAGTY4WtWgABUYBw0BfZJnoSM_kNt49EM81gKznPICMuPw-M2Fhj96-G7Q") { name, err in
            if let err = err {
                if err.code.rawValue == 200 {
                    YHHUD.flash(message: err.errorDescription)
                } else {
                    YHHUD.flash(message: "登录-失败")
                }
            } else {
                YHHUD.flash(message: "登录-成功")
            }
        }
    }
    
    
    
    
//    func getRoomInfo() {
//        EMClient.shared().roomManager?.getChatroomSpecificationFromServer(withId: roomID, fetchMembers: true, completion: { emChatRoom, err in
//            printLog(emChatRoom)
//            if let err = err {
//                
//            } else {
//                
//            }
//        })
//        
//        
//        EMClient.shared().roomManager?.getChatroomSpecificationFromServer(withId: roomID, completion: { emChatRoom, err in
//            printLog(emChatRoom)
//            
//            if let err = err {
//                print(err)
//            } else {
//                
//                if let roomInfo = emChatRoom {
//                    printLog(roomInfo.adminList)
//                    printLog(roomInfo.chatroomId)
//                    printLog(roomInfo.blacklist)
//                    printLog(roomInfo.memberList)
//                }
//                
//            }
//        })
//
//    }
    
}

// 收到其他人加入聊天室的回调
extension YHIMTestViewController: EMChatroomManagerDelegate {
    func userDidJoin(_ aChatroom: EMChatroom, user aUsername: String, ext: String?) {
        printLog(aChatroom)
        printLog(aUsername)
        printLog(ext)
        
        YHHUD.flash(message: "\(aChatroom) 加入聊天室了")
    }
    
    func userDidJoin(_ aChatroom: EMChatroom, user aUsername: String) {
        let memberCount = aChatroom.occupantsCount
        printLog(memberCount)
        YHHUD.flash(message: "\(aUsername) 加入 聊天室了")
    }
    func userDidLeave(_ aChatroom: EMChatroom, user aUsername: String) {
        let memberCount = aChatroom.occupantsCount
        printLog(memberCount)
    
        YHHUD.flash(message: "\(aUsername) 离开 聊天室了")
    }
}

extension YHIMTestViewController: EMChatManagerDelegate {
    //收到消息
    func messagesDidReceive(_ aMessages: [EMChatMessage]) {
        for(i,t) in aMessages.enumerated() {
            printLog(t.ext)
            
            var nickName : String = ""
            if let ext = t.ext {
                nickName = ext["fromNickName"] as? String ?? "YinHe"
            }
            
            if let body = t.body as? EMTextMessageBody,body.type == .text {
                printLog(body.text)
                YHHUD.flash(message: "\(nickName) : \(body.text)")
            }
        }
    }
}

