//
//  YHMessageSessionCell.swift
//  galaxy
//
//  Created by edy on 2024/4/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import TUICore

class YHMessageSessionCell: UITableViewCell {

    static let cellReuseIdentifier = "YHMessageSessionCell"
    let badgeHeight = 18.0
    
    var iconContentView: UIView!
    var iconImgView: UIImageView!
    var badgeLabel: UILabel!
    var nameLabel: UILabel!
    var detailLabel: UILabel!
    var timeLabel: UILabel!
    var bottomLineView: UIView!
    private var currentGroupId: String?
        
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func updateModel(_ model: YHMessageInfoModel) {
        
        self.nameLabel.text = model.getTitle()
        self.iconContentView.backgroundColor = UIColor(hex: 0xF4F6FA)

        if model.type == YHMessageType.yinheManager.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_yinhe_manager")
            
        } else if model.type == YHMessageType.infoFill.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_info_fill")
            
        } else if model.type == YHMessageType.cerUpload.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_cer_upload")
            
        } else if model.type == YHMessageType.draft.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_draft")
            
        } else if model.type == YHMessageType.fileSign.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_file_sign")
            
        } else if model.type == YHMessageType.infoSubmit.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_info_submit")
        
        } else if model.type == YHMessageType.identityApproved.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_identity_approved")
        
        } else if model.type == YHMessageType.goToHK.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_goToHK")
        
        } else if model.type == YHMessageType.renewal.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_renewal")
            
        } else if model.type == YHMessageType.business.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_business")
            
        } else if model.type == YHMessageType.article.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_news")
            self.iconContentView.backgroundColor = UIColor(hex: 0xF0F5FF)

        } else if model.type == YHMessageType.txIM.rawValue {
            updatePortrait(convData: model)
            
        } else if model.type == YHMessageType.trip.rawValue {
            self.iconImgView.image = UIImage(named: "msg_icon_gift")
                            
        }
        
        self.badgeLabel.isHidden = model.unreadCount <= 0
        let unreadCountText =  (model.unreadCount < 100 ? String(model.unreadCount) : "99+")
        self.badgeLabel.text = unreadCountText
        self.badgeLabel.snp.updateConstraints { make in
            var width = badgeHeight
            if unreadCountText.count < 2 { // 个位数
                width = badgeHeight
                
            } else if unreadCountText.count == 2 { // 两位数
                width = 26.0
            } else if unreadCountText.count >= 3 { // 三位数
                width = 32.0
            }
            make.width.equalTo(width)
        }
        let isBigIcon = model.type == YHMessageType.yinheManager.rawValue || model.type == YHMessageType.txIM.rawValue
        self.iconImgView.snp.updateConstraints { make in
            let width = isBigIcon ? 44.0 : 21.0
            let height = isBigIcon ? 44.0 : 21.0
            make.width.equalTo(width)
            make.height.equalTo(height)
        }
        
        if model.type == YHMessageType.txIM.rawValue {
            let attr = NSMutableAttributedString(attributedString: model.attributedSubtitle)
            attr.setAttributes([.foregroundColor: UIColor.mainTextColor50, .font: UIFont.PFSC_R(ofSize: 12)], range: NSRange(location: 0, length: attr.string.count))
            self.detailLabel.attributedText = !attr.string.isEmpty ? attr : NSAttributedString(string: "暂无消息".local, attributes: [.foregroundColor: UIColor.mainTextColor50, .font: UIFont.PFSC_R(ofSize: 12)])
        } else {
            self.detailLabel.text = !model.lastMessage.isEmpty ? model.lastMessage : "暂无消息".local
        }
        self.timeLabel.text =  formatTimestamp(Double(model.lastMessageTime))
        self.timeLabel.isHidden = model.lastMessage.isEmpty
    }
    
    func formatTimestamp(_ timestamp: TimeInterval) -> String {
        let currentDate = Date()
        let calendar = Calendar.current
        let currentYear = calendar.component(.year, from: currentDate)
        let currentDay = calendar.component(.day, from: currentDate)
        
        let date = Date(timeIntervalSince1970: timestamp)
        let year = calendar.component(.year, from: date)
        let day = calendar.component(.day, from: date)
        
        let dateFormatter = DateFormatter()
        
        if year == currentYear {
            if day == currentDay {
                dateFormatter.dateFormat = "HH:mm"
            } else {
                dateFormatter.dateFormat = "MM-dd"
            }
        } else {
            dateFormatter.dateFormat = "yyyy-MM-dd"
        }
        
        return dateFormatter.string(from: date)
    }
    
    private func updatePortrait(convData: YHMessageInfoModel) {
        if !convData.groupID.isEmpty {
            currentGroupId = convData.groupID
            // Group avatar
            if !convData.avatar.isEmpty {
                // Group avatar has been manually set externally
                self.iconImgView.kf.setImage(with: URL(string: convData.avatar), placeholder: convData.avatarImage ?? UIImage(named: "people_head_default"))
            } else {
                if TUIConfig.default().enableGroupGridAvatar {
                    // Use synthetic avatar
                    self.iconImgView.image = convData.avatarImage ?? UIImage(named: "people_head_default")
                    
                    TUIGroupAvatar.getCacheGroupAvatar(convData.groupID) { [weak self] (avatar, callbackGroupID) in
                        guard let self = self else { return }
                        
                        if callbackGroupID == self.currentGroupId {
                            if let avatar = avatar {
                                // Cache hit
                                self.iconImgView.image = avatar
                            } else {
                                // Need to synthesize new avatar
                                self.iconImgView.image = convData.avatarImage ?? UIImage(named: "people_head_default")
                                let placeholderImage = convData.avatarImage ?? UIImage(named: "people_head_default") ?? UIImage()
                                TUIGroupAvatar.fetchGroupAvatars(convData.groupID, placeholder: placeholderImage) { [weak self] (success, image, fetchGroupID) in
                                    guard let self = self else { return }
                                    
                                    if fetchGroupID == self.currentGroupId {
                                        let placeholder = success ? image : TUIConfig.default().getGroupAvatarImage(byGroupType: convData.groupType)
                                        self.iconImgView.image = placeholder
                                    }
                                    // Ignore if cell has been reused
                                }
                            }
                        }
                        // Ignore if cell has been reused
                    }
                } else {
                    // Synthetic avatars not allowed, use default
                    self.iconImgView.image = convData.avatarImage ?? UIImage(named: "people_head_default")
                }
            }
        } else {
            self.iconImgView.kf.setImage(with: URL(string: convData.avatar), placeholder: convData.avatarImage ?? UIImage(named: "people_head_default"))
        }
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        contentView.backgroundColor = .white
        
        iconContentView = UIView()
        iconContentView.backgroundColor = UIColor(hex: 0xF4F6FA)
        iconContentView.layer.cornerRadius = 22.0
        contentView.addSubview(iconContentView)
        
        iconImgView = UIImageView()
        iconContentView.addSubview(iconImgView)
        
        badgeLabel = UILabel()
        badgeLabel.backgroundColor = UIColor.failColor
        badgeLabel.textColor = .white
        badgeLabel.textAlignment = .center
        badgeLabel.font = UIFont.PFSC_M(ofSize: 11)
        badgeLabel.layer.cornerRadius = badgeHeight/2.0
        badgeLabel.clipsToBounds = true
        iconContentView.addSubview(badgeLabel)

        nameLabel = UILabel()
        nameLabel.textColor = UIColor.mainTextColor
        nameLabel.textAlignment = .left
        nameLabel.font = UIFont.PFSC_M(ofSize: 15)
        contentView.addSubview(nameLabel)
        
        detailLabel = UILabel()
        detailLabel.textColor = UIColor.mainTextColor50
        detailLabel.textAlignment = .left
        detailLabel.font = UIFont.PFSC_R(ofSize: 12)
        contentView.addSubview(detailLabel)
        
        timeLabel = UILabel()
        timeLabel.textColor = UIColor.mainTextColor30
        timeLabel.textAlignment = .right
        timeLabel.font = UIFont.PFSC_R(ofSize: 11)
        timeLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        timeLabel.setContentHuggingPriority(.required, for: .horizontal)
        contentView.addSubview(timeLabel)
        
        bottomLineView = UIView()
        bottomLineView.backgroundColor = UIColor.mainTextColor5
        contentView.addSubview(bottomLineView)

        iconContentView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.centerY.equalToSuperview()
        }
        
        iconImgView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 21, height: 21))
            make.center.equalToSuperview()
        }
        
        badgeLabel.snp.makeConstraints { make in
            make.width.equalTo(badgeHeight)
            make.height.equalTo(badgeHeight)
            make.top.equalToSuperview().offset(-4)
            make.right.equalTo(iconContentView.snp.right).offset(6)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(iconContentView.snp.right).offset(16)
            make.right.equalTo(timeLabel.snp.left).offset(-20)
            make.top.equalTo(iconContentView)
            make.height.equalTo(21)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.left.equalTo(nameLabel)
            make.right.equalTo(timeLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(2)
            make.height.equalTo(17)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(nameLabel)
            make.height.equalTo(15)
        }
        
        bottomLineView.snp.makeConstraints { make in
            make.left.right.equalTo(detailLabel)
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
    }
}
