//
//  CustomMessageContentCell.swift
//  ChatExample
//
//  Created by Vignesh J on 01/05/21.
//  Copyright © 2021 MessageKit. All rights reserved.
//

import MessageKit
import UIKit

class TSMessageContentCell: MessageCollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        setupSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        setupSubviews()
    }
    
    /// The `MessageCellDelegate` for the cell.
    weak var delegate: MessageCellDelegate?
    var cellTapType:TSChatMsgViewTapType?
    /// 顶部内容
    var topContainerView: UIView = {
        let containerView = UIView()
        containerView.clipsToBounds = true
//        containerView.backgroundColor = .red
        return containerView
    }()
    
    /// 中部内容
    var centerContainerView: UIView = {
        let containerView = UIView()
//        containerView.backgroundColor = .yellow
        return containerView
    }()

    
    /// 底部内容
    var bottomContainerView: UIView = {
        let containerView = UIView()
//        containerView.backgroundColor = .blue
        return containerView
    }()
    
    
    
    
    /// 消息内容容器.frame由 子视图自动布局撑起大小
    var messageContainerView: UIView = {
        let containerView = UIView()
        containerView.cornerRadius = 16
        return containerView
    }()
    
    var messageTopContainerView: UIView = {
        let containerView = UIView()
//        containerView.backgroundColor = .orange
        return containerView
    }()
    var messageCenterContainerView: UIView = {
        let containerView = UIView()
        return containerView
    }()
    var messageBottomContainerView: UIView = {
        let containerView = UIView()
//        containerView.backgroundColor = .purple
        return containerView
    }()
    

    // 左头像
    var leadingAvatarImageView: UIImageView = {
        let imageView = UIImageView.createImageView(imageName: "aichat_avatar")
        imageView.isHidden = true
        return imageView
    }()
    
    // 右头像(预留)
    var trailingAvatarImageView: UIImageView = {
        let imageView = UIImageView.createImageView(imageName: "aichat_avatar")
        imageView.isHidden = true
        return imageView
    }()
    
    
    //工具栏,复制,copy 等
    lazy var msgToolView: TSChatMsgToolView = {
        let msgToolView = TSChatMsgToolView()
        msgToolView.didTapCustomViewBlock = {[weak self] tapType in
            guard let self = self else { return }
            if let delegate = delegate{
                cellTapType = tapType
                delegate.didTapBackground(in: self)
            }
        }
        return msgToolView
    }()
 
    
    //初始化 cell
    func setupSubviews() {
        contentView.addSubview(topContainerView)
        contentView.addSubview(centerContainerView)
        contentView.addSubview(bottomContainerView)
        topContainerView.snp.makeConstraints { make in
            make.leading.top.trailing.equalTo(0)
        }
        centerContainerView.snp.makeConstraints { make in
            make.top.equalTo(topContainerView.snp.bottom)
            make.leading.trailing.equalTo(0)
        }
        
        bottomContainerView.snp.makeConstraints { make in
            make.top.equalTo(centerContainerView.snp.bottom)
            make.leading.trailing.bottom.equalTo(0)
        }
        
        setUpTopContainerView()
        setUpCenterContainerView()
        setUpBottomContainerView()
    }
    

    func setUpTopContainerView() {
        
    }
    
    func setUpCenterContainerView() {
        centerContainerView.addSubview(leadingAvatarImageView)
        centerContainerView.addSubview(messageContainerView)
        centerContainerView.addSubview(trailingAvatarImageView)
        
        let leadingAvatarEdge = TSLayoutSizeCalculator.leadingAvatarEdge
        let leadingAvatarSize = TSLayoutSizeCalculator.leadingAvatarSize
        leadingAvatarImageView.snp.makeConstraints { make in
            make.leading.equalTo(leadingAvatarEdge.left)
            make.top.equalTo(leadingAvatarEdge.top)
            make.size.equalTo(leadingAvatarSize)
        }
        
        //暂时没用,预留的,数值都是 0
        let traingAvatarEdge = TSLayoutSizeCalculator.traingAvatarEdge
        let trainggAvatarSize = TSLayoutSizeCalculator.traingAvatarSize
        trailingAvatarImageView.snp.makeConstraints { make in
            make.trailing.equalTo(traingAvatarEdge.right)
            make.top.equalTo(traingAvatarEdge.top)
            make.size.equalTo(trainggAvatarSize)
        }
        
        let cellMessageContainerEdge = TSLayoutSizeCalculator.cellMessageContainerLeadingEdge
        messageContainerView.snp.makeConstraints { make in
            make.leading.equalTo(leadingAvatarImageView.snp.trailing).offset(cellMessageContainerEdge.left)
            make.trailing.lessThanOrEqualTo(trailingAvatarImageView.snp.leading).offset(-16)
            make.top.equalTo(cellMessageContainerEdge.top)
            make.bottom.equalTo(-cellMessageContainerEdge.bottom)
        }
        
        
        setUpMessageContainerView()
    }
    
    func setUpMessageContainerView(){
        messageContainerView.addSubview(messageTopContainerView)
        messageContainerView.addSubview(messageCenterContainerView)
        messageContainerView.addSubview(messageBottomContainerView)
        
        
        messageTopContainerView.snp.makeConstraints { make in
            make.leading.top.trailing.equalTo(0)
        }
        messageCenterContainerView.snp.makeConstraints { make in
            make.top.equalTo(messageTopContainerView.snp.bottom)
            make.leading.trailing.equalTo(0)
        }
        
        messageBottomContainerView.snp.makeConstraints { make in
            make.top.equalTo(messageCenterContainerView.snp.bottom)
            make.leading.trailing.bottom.equalTo(0)
        }
        
        //添加工具栏
        messageBottomContainerView.addSubview(msgToolView)
        msgToolView.snp.makeConstraints { make in
            make.leading.trailing.top.bottom.equalTo(0)
            make.height.equalTo(msgToolView.viewHeight)
        }
        
    }
    
    func setUpBottomContainerView() {
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
    }
    
    // 点击触发事件
    override func handleTapGesture(_ gesture: UIGestureRecognizer) {
//        let touchLocation = gesture.location(in: self)
//        switch true {
//        case messageContainerView.frame
//                .contains(touchLocation) && !cellContentView(canHandle: convert(touchLocation, to: messageContainerView)):
//            delegate?.didTapMessage(in: self)
//        case cellTopLabel.frame.contains(touchLocation):
//            delegate?.didTapCellTopLabel(in: self)
//    case cellDateLabel.frame.contains(touchLocation):
//      delegate?.didTapMessageBottomLabel(in: self)
//        default:
//            delegate?.didTapBackground(in: self)
//        }
    }
    
    /// Handle long press gesture, return true when gestureRecognizer's touch point in `messageContainerView`'s frame
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        let touchPoint = gestureRecognizer.location(in: self)
        guard gestureRecognizer.isKind(of: UILongPressGestureRecognizer.self) else { return false }
        return messageContainerView.frame.contains(touchPoint)
    }

    //设置更新内容
    func configure(
        with message: MessageType,
        at indexPath: IndexPath,
        in messagesCollectionView: MessagesCollectionView,
        dataSource: MessagesDataSource,
        and sizeCalculator: TSLayoutSizeCalculator)
    {
        guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
            return
        }
        
        //是否是当前用户发送的消息
        let fromCurrentSender = dataSource.isFromCurrentSender(message: message)
        if fromCurrentSender {
            leadingAvatarImageView.isHidden = true
            let cellMessageContainerEdge = TSLayoutSizeCalculator.cellMessageContainerTraingEdge
            messageContainerView.snp.remakeConstraints { make in
                make.leading.greaterThanOrEqualTo(cellMessageContainerEdge.left)
                make.trailing.equalTo(-cellMessageContainerEdge.right)
                make.top.equalTo(cellMessageContainerEdge.top)
                make.bottom.equalTo(-cellMessageContainerEdge.bottom)
            }
        }else{
            leadingAvatarImageView.isHidden = false
            let cellMessageContainerEdge = TSLayoutSizeCalculator.cellMessageContainerLeadingEdge
            messageContainerView.snp.remakeConstraints { make in
                make.leading.equalTo(leadingAvatarImageView.snp.trailing).offset(cellMessageContainerEdge.left)
                make.trailing.lessThanOrEqualTo(-cellMessageContainerEdge.right)
                make.top.equalTo(cellMessageContainerEdge.top)
                make.bottom.equalTo(-cellMessageContainerEdge.bottom)
            }
        }
        
        messageContainerView.backgroundColor = displayDelegate.backgroundColor(for: message,at: indexPath,in: messagesCollectionView)
        handleTopContainerViewChanged(message: message,messagesCollectionView: messagesCollectionView,dataSource: dataSource)
    }
    
    func handleTopContainerViewChanged(
        message: MessageType,
        messagesCollectionView: MessagesCollectionView,
        dataSource: MessagesDataSource
    ) {
        topContainerView.removeAllSubviews()
        delegate = messagesCollectionView.messageCellDelegate
        
        if let msgModel = message as? TSChatMessage {
            if let uiBaseModel = msgModel.appendDict[.topView] as? TSChatMessageUIBaseModel {
                let modelView = uiBaseModel.view
                topContainerView.addSubview(modelView)
                modelView.snp.makeConstraints { make in
                    make.leading.trailing.top.bottom.equalTo(0)
                    make.height.equalTo(uiBaseModel.height)
                }
            }
        }
        
        
        handelMsgToolView(message: message, dataSource: dataSource)
    }
    
    
    
    
    
    func handelMsgToolView(message: MessageType,dataSource: MessagesDataSource){
        if let msgModel = message as? TSChatMessage,let chatVC = dataSource as? TSChatViewController{
    
            if msgModel.sendState.isResult {
                var isHiddenReload = true

                let isLast = Self.kIsChatLast(message: message, dataSource: dataSource)
                
                //重试只在显示在最后一个 cell,历史记录中,不能显示重试
                if isLast == true , chatVC.viewModel.uiStyle != .history {
                    isHiddenReload = false
                }
                
                //成功显示复制,失败显示重试
                msgToolView.isShowRefresh = !isHiddenReload
                msgToolView.isOnlyShowRefresh = (msgModel.sendState.reslutSuccess == false)
                
                var isHidden = true
                if msgModel.messageType == TSChatMessageMsgType.aiRobotResponse,
                   msgModel.sendState.isResult{
                    //是机器人的回答,且回答已经结束,就可以显示工具栏了
                    isHidden = false
                }
                msgToolView.snp.updateConstraints { make in
                    make.height.equalTo(isHidden ? 0 : msgToolView.viewHeight)
                }
            }else{
                msgToolView.snp.updateConstraints { make in
                    make.height.equalTo(0)
                }
            }
        }
    }
    
    
    
    /// Handle `ContentView`'s tap gesture, return false when `ContentView` doesn't needs to handle gesture
    func cellContentView(canHandle _: CGPoint) -> Bool {
        false
    }
}






extension TSMessageContentCell {

    func isLastCell(in collectionView: UICollectionView) -> Bool {
        if let indexPath = collectionView.indexPath(for: self),
           let dataSource = collectionView.dataSource {
            let itemCount = dataSource.collectionView(collectionView, numberOfItemsInSection: indexPath.section)
            return indexPath.item == itemCount - 1
        }
        return false
    }
    
    static func kIsChatLast(message: MessageType,dataSource: MessagesDataSource)->Bool{
        if let chatVC = dataSource as? TSChatViewController,
           let msg = message as? TSChatMessage
        {
            let array = chatVC.messageList
            // 判断对象是否在数组中是最后一个元素
            if let index = array.firstIndex(where: { $0 === msg }), index == array.count - 1 {
                return true
            }
        }
        
        return false
    }

}


