Untitled

 avatar
unknown
swift
a year ago
13 kB
3
Indexable
//
//  ChatListVC.swift
//  JILLII
//
//  Created by Prismetric  on 05/10/21.
//

import UIKit

class ChatListVC: UIViewController {
    
    @IBOutlet weak var tblChatList: UITableView!
    @IBOutlet weak var viewSearch:UIView!
    @IBOutlet weak var firstMessageUpperVw : UIView!
    @IBOutlet weak var lblCounts: UILabel!
    
    var arrChatConversation : [ChatConversation]?
    var filteredarrChatConversation : [ChatConversation]?
    var objUserProfile:UserData?
    
    @IBOutlet weak var lblNavHeader: UILabel!
    @IBOutlet weak var btnIimgHeaderProfile: UIButton!
    @IBOutlet weak var imgUserProfile: UIImageView!
    @IBOutlet weak var txtFieldSearch: UITextField!
    
    
    
    var operationAPI = OperationQueue()
    var refreshControl = UIRefreshControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tblChatList.register(UINib(nibName: "chatlistCell", bundle: nil), forCellReuseIdentifier: "chatlistCell")
        
        self.viewSearch.setCornerRadius_Extension(18.0)
        self.firstMessageUpperVw.btnGradiantBorderToview(5.0)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            
            
            self.imgUserProfile.setCornerRaduisToRound()
            self.lblNavHeader.text = objUserData.first_name + " \(objUserData.last_name)"
            if objUserData.image != ""{
                
                self.imgUserProfile.setImage(strUrl: objUserData.image, placeholder: UIImage(named: "user_images_login")!)
 
            }
        }
        
        self.refreshControl = UIRefreshControl()
        self.refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
        self.refreshControl.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
        self.refreshControl.tintColor = .gray
        self.tblChatList.refreshControl = self.refreshControl
        
        NotificationCenter.default.addObserver(self, selector: #selector(receivedMessage(notification:)), name: .ChatReceiveMessage, object: nil)
        
    }
    
    @IBAction func onTapEventMessage(_ sender: UIButton) {
        
        let vc = StoryBoard.Activity.instantiateViewController(withIdentifier: "ChatEventMessages") as! ChatEventMessages
      
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK: Received Message
    @objc func receivedMessage(notification: Notification) {
        self.JSONGetAllGroupUserList()
    }
    
    @objc func refresh(_ sender: AnyObject) {
        self.JSONGetAllGroupUserList()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.JSONGetAllGroupUserList()
        
    }
    
    @IBAction func Act_Back(_ sender: Any) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func Act_createGroup(_ sender: Any) {
        
        let vc = StoryBoard.Activity.instantiateViewController(withIdentifier: "CreateChatGroupVC") as! CreateChatGroupVC
      
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    } 
    
    //MARK: JSONGetAllGroupUserList
    func JSONGetAllGroupUserList() {
        let param = [String:String]()
        self.refreshControl.beginRefreshing()
        WebService.shared.RequesURL(ServerURL.get_chat_list , Perameters: param, showProgress: false, completion: { (response, status) in
            
            self.refreshControl.endRefreshing()
            if let dicPostData = response.object(forKey: "data") as? [String:Any] {
                
                if let arrChatsList = dicPostData["chats_list"] as? [[String:Any]] {
                    self.arrChatConversation = arrChatsList.map({ChatConversation.init($0)})
                    DispatchQueue.main.async {
                        self.filteredarrChatConversation = self.arrChatConversation
                        self.tblChatList.reloadData()
                    }
                }
                
                if let unread_msg_count = dicPostData["unread_msg_count"] as? Int {
                    self.lblCounts.text = ToString(unread_msg_count)
                    DispatchQueue.main.async {
                        self.tblChatList.reloadData()
                    }
                }
            }
            else {
                ShowAlert(title: enumAlert.Alert.rawValue, message: ToString(response["message"]), buttonTitle: "Ok", handlerCB: nil)
            }
//            self.strOffset = ToString(response.object(forKey: "offset"))
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.tblChatList.reloadData()
            }
            
        }) { (err) in
            self.refreshControl.endRefreshing()
            debugPrint(err.localizedDescription)
            ShowAlert(title: enumAlert.Alert.rawValue, message: ToString(err.localizedDescription), buttonTitle: "Ok", handlerCB: nil)
        }
    }
    
    @IBAction func clickOnProfileBtn(_ sender : UIButton){
        let vc = StoryBoard.ProfileAll.instantiateViewController(withIdentifier: "MyProfileVC") as! MyProfileVC
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension ChatListVC:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.filteredarrChatConversation?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "chatlistCell", for: indexPath) as! chatlistCell
        
        let dicConv = self.filteredarrChatConversation?[indexPath.row]

        if dicConv?.is_group == "1"
        {
            if let imgPro = dicConv?.group_image {
                cell.viewProfilePic.setImage(strUrl: imgPro, placeholder: UIImage(named: "Group_PlaceHolder")!)
            }
            else{
                cell.viewProfilePic.image = UIImage(named: "Group_PlaceHolder")!
            }
            
            cell.lblName.text = dicConv?.group_name
            
            switch dicConv?.last_message?.is_send {
            case "1":
                cell.lblTicDoubleTic.isHidden = false
            default:
                cell.lblTicDoubleTic.isHidden = true
            }
            
            switch dicConv?.last_message?.status {
            case "2":
                cell.lblTicDoubleTic.image = UIImage().imgMessageRead
            default:
                cell.lblTicDoubleTic.image = UIImage().imgMessageDelivered
            }

            if dicConv?.last_message?.is_send == "0" && dicConv?.last_message?.status != "2"{
                cell.imgChatDit.isHidden = false
                cell.lblLastMessage.textColor = UIColor.black
            }else{
                cell.imgChatDit.isHidden = true
                cell.lblLastMessage.textColor = #colorLiteral(red: 0.5019999743, green: 0.5099999905, blue: 0.5220000148, alpha: 1)
            }
        }
        else
        {
            if let imgPro = dicConv?.user_image {
                cell.viewProfilePic.setImage(strUrl: imgPro, placeholder: UIImage(named: "User_PlaceHolder")!)
            }
            else{
                cell.viewProfilePic.image = UIImage(named: "User_PlaceHolder")!
            }
            
            let nameF = dicConv?.first_name ?? ""
            let nameL = dicConv?.last_name ?? ""
            cell.lblName.text = nameF + " \(nameL)"
            
            switch dicConv?.last_message?.status {
            case "2":
                cell.lblTicDoubleTic.image = UIImage().imgMessageRead
            default:
                cell.lblTicDoubleTic.image = UIImage().imgMessageDelivered
            }
            
            switch dicConv?.last_message?.is_send {
            case "1":
                cell.lblTicDoubleTic.isHidden = false
            default:
                cell.lblTicDoubleTic.isHidden = true
            }
            
            if dicConv?.last_message?.is_send == "0" && dicConv?.last_message?.status != "2"{
                cell.imgChatDit.isHidden = false
                cell.lblLastMessage.textColor = UIColor.black
            }else{
                cell.imgChatDit.isHidden = true
                cell.lblLastMessage.textColor = #colorLiteral(red: 0.5019999743, green: 0.5099999905, blue: 0.5220000148, alpha: 1)
            }
        }
        
        debugPrint("F \(dicConv?.first_name ?? "")")
        debugPrint("L \(dicConv?.last_name ?? "")")

        
        if dicConv?.last_message?.chat_type == "0"{
            cell.lblLastMessage.text = dicConv?.last_message?.chat_message
            cell.imgMediaType.isHidden = true
        }else if dicConv?.last_message?.chat_type == "1"{
            cell.lblLastMessage.text = "photo"
            cell.imgMediaType.isHidden = false
            cell.imgMediaType.image = UIImage(systemName: "photo")
            cell.imgMediaType.tintColor = #colorLiteral(red: 0.4269999862, green: 0.4309999943, blue: 0.4390000105, alpha: 1)
        }else if dicConv?.last_message?.chat_type == "2"{
            cell.lblLastMessage.text = "video"
            cell.imgMediaType.isHidden = false
            cell.imgMediaType.image = UIImage(named: "video_camera_android")
            cell.imgMediaType.tintColor = #colorLiteral(red: 0.4269999862, green: 0.4309999943, blue: 0.4390000105, alpha: 1)
        }else{
            cell.lblLastMessage.text = dicConv?.last_message?.chat_message
        }
        
        let dateChat = dicConv?.created_at ?? ""
        if dateChat != "" {
            cell.lblTimeAgo.text = timeAgo(strDate: dateChat, secondString: "Now", "")//dateConvert_GlobalUTCToLocal(date: dateChat, FromFormate: AppDateFormatNotification, ToGetFormate: "dd MMM YYYY")
        }
        else{
            cell.lblTimeAgo.text = ""
        }
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let dicData = self.filteredarrChatConversation?[indexPath.row] {
            
            let vc = StoryBoard.Activity.instantiateViewController(withIdentifier: "ChatDetailVC") as! ChatDetailVC
            vc.siGroup = dicData.is_group == "1" ? true:false
            vc.objChatConversation = dicData
            UserDefaults.standard.set(dicData.user_id, forKey: "ChatId")
            vc.theme_color = ToString(dicData.chat_settings?.theme_colors)
            vc.isThemeYellow = true
            vc.leftVal = dicData.is_left
            let ThemeModel = ["theme_id":ToString(dicData.chat_settings?.theme_id),"theme_colors":ToString(dicData.chat_settings?.theme_colors)]
            UserDefaults.standard.set(ThemeModel, forKey: "ChatTheme")
            self.navigationController?.pushViewController(vc, animated: true)
            
        }
    }
}

extension UIRefreshControl {
    func programaticallyBeginRefreshing(in tableView: UITableView) {
        beginRefreshing()
        let offsetPoint = CGPoint.init(x: 0, y: -frame.size.height)
        tableView.setContentOffset(offsetPoint, animated: true)
    }
}

extension ChatListVC : UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let searchText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        filterContentForSearchText(searchText)
        return true
    }
    
    func filterContentForSearchText(_ searchText: String) {
        if searchText.isEmpty {
            // If search text is empty, show all contacts
            self.filteredarrChatConversation = self.arrChatConversation
        } else {
            // Filter contacts based on search text
            filteredarrChatConversation = self.arrChatConversation?.filter { contact in
                return contact.first_name.lowercased().contains(searchText.lowercased()) ||
                contact.last_name.lowercased().contains(searchText.lowercased()) || contact.group_name.lowercased().contains(searchText.lowercased())
            }
        }
        
        // Reload table view
        self.tblChatList.reloadData()
    }
}
Editor is loading...
Leave a Comment