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

import MessageKit
import UIKit
import SwiftyMarkdown
class TSTextMessageContentCell: TSMessageContentCell {
    var messageLabel: UILabel = {
        let label = UILabel.createLabel(font: .font(size: 16),numberOfLines: 0)
        label.lineBreakMode = .byWordWrapping
        return label
    }()
    
    lazy var activityIndicator: UIActivityIndicatorView = {
        activityIndicator = UIActivityIndicatorView(style: .medium)
        activityIndicator.color = .white
        activityIndicator.isHidden = true
        return activityIndicator
    }()
    
    
    
    lazy var refreshBtn: UIButton = {
        let refresh = UIButton.createButton(image: UIImage(named: "aichat_refresh")) { [weak self]  in
            guard let self = self else { return }
            
            
        }
        return refresh
    }()
    
    lazy var bottomToolView: UIView = {
        bottomToolView = UIView()
        bottomToolView.isHidden = true
        return bottomToolView
    }()
    
    
    
    override func prepareForReuse() {
        super.prepareForReuse()
    }
    
    override func setupSubviews() {
        super.setupSubviews()
        
        let labelEdge = TSTextLayoutSizeCalculator.cellMessagelabelEdge
        messageContainerView.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { make in
            make.edges.equalTo(labelEdge)
            make.width.height.equalTo(0)
        }
        
        messageContainerView.addSubview(activityIndicator)
        activityIndicator.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(12)
            make.width.height.equalTo(24.0)
        }
        
        
        bottomToolView.addSubview(refreshBtn)
        refreshBtn.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.bottom.equalTo(-9)
            make.width.height.equalTo(20)
        }
        
        
        
    }
    
    override func configure(
        with message: MessageType,
        at indexPath: IndexPath,
        in messagesCollectionView: MessagesCollectionView,
        dataSource: MessagesDataSource,
        and sizeCalculator: TSLayoutSizeCalculator)
    {
        super.configure(with: message, at: indexPath, in: messagesCollectionView, dataSource: dataSource, and: sizeCalculator)
        guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
            return
        }
        
        //更新frame
        let calculator = sizeCalculator as? TSTextLayoutSizeCalculator
        let labelFrame = calculator?.messageLabelSize(for: message, at: indexPath,fromCurrentSender: dataSource.isFromCurrentSender(message: message)) ?? TSTextLayoutSizeCalculator.cellMessagelabelMinSize
        messageLabel.snp.updateConstraints { make in
            make.width.equalTo(labelFrame.width)
            make.height.equalTo(labelFrame.height)
        }
        

        if let msgModel = message as? TSChatMessage {
            //显示旋转的动画
            switch msgModel.sendState {
            case .start:
                startAnimating()
            case .progress(_):
                stopAnimating()
            case .success(_):
                stopAnimating()
            case .failed(_):
                stopAnimating()
            default:
                stopAnimating()
            }
        }
    
        //给 label 赋值
        let textMessageKind = message.kind
        switch textMessageKind {
        case .text(let text), .emoji(let text):
            let textColor = displayDelegate.textColor(for: message, at: indexPath, in: messagesCollectionView)
            messageLabel.textColor = textColor
            messageLabel.text = text
//            debugPrint("text赋值")
        case .attributedText(let text):
            messageLabel.text = text.string
            messageLabel.attributedText = text
//            debugPrint("attributedText赋值")
            
//            extractAndPrintSubstring(from: messageLabel.text ?? "", to: text.string)
        default:
            break
        }
    }
    
    
    func extractAndPrintSubstring(from sourceString: String, to targetString: String) {
        // 查找 sourceString 在 targetString 中的结束位置
        if let range = targetString.range(of: sourceString) {
            // 获取 sourceString 在 targetString 中的结束位置
            let startIdx = range.upperBound
            // 提取从该位置到 targetString 结束的子字符串
            let extractedSubstring = targetString[startIdx...]
            
            // 将提取的子字符串逐个字符输出
            var string = sourceString
            for character in extractedSubstring {
//                print(character)
                string = string + String(character)
                messageLabel.text = string
                messageLabel.attributedText = kMDAttributedString(text: string)
            }
        } else {
            print("未找到 sourceString")
            messageLabel.text = targetString
            messageLabel.attributedText = kMDAttributedString(text: targetString)
        }
    }
    
    func startAnimating() {
        activityIndicator.isHidden = false
        activityIndicator.startAnimating()
    }
    
    func stopAnimating() {
        activityIndicator.isHidden = true
        activityIndicator.stopAnimating()
    }
}
