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

import UIKit
import Lottie

class YHAITextMessageCell: UITableViewCell {

    static let cellReuseIdentifier = "YHAITextMessageCell"
    
    var messageClick: ((String) -> Void)?
    
    var message: YHAIChatMessage = YHAIChatMessage() {
        
        didSet {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 4.0
            
            let textColor: UIColor = message.isSelf ? .white : .mainTextColor
            let attributedText = NSAttributedString(
                string: message.body.contentText,
                attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle,
                             NSAttributedString.Key.foregroundColor: textColor,
                             NSAttributedString.Key.font: UIFont.PFSC_R(ofSize: 14)]
            )
            messageLabel.attributedText = attributedText
            rightAngleView.backgroundColor = message.isSelf ? .brandMainColor : .white
            rightAngleView.isHidden = message.getType() != .text

            if message.isSelf {
                whiteContentView.backgroundColor = .brandMainColor
                whiteContentView.snp.remakeConstraints { make in
                    make.left.greaterThanOrEqualTo(58)
                    make.right.equalTo(-20)
                    make.top.equalTo(16)
                    make.bottom.equalTo(0)
                }
                
                rightAngleView.snp.remakeConstraints { make in
                    make.top.right.equalTo(whiteContentView)
                    make.width.height.equalTo(15)
                }
                
                isNeedShowCopyView = false
                isNeedShowLoadingView = false
                
            } else {
                
                whiteContentView.backgroundColor = .white
                whiteContentView.snp.remakeConstraints { make in
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.top.equalTo(16)
                    make.bottom.equalTo(0)
                }
                
                rightAngleView.snp.remakeConstraints { make in
                    make.top.left.equalTo(whiteContentView)
                    make.width.height.equalTo(15)
                }
                
                isNeedShowCopyView = message.isDone
                isNeedShowLoadingView = !message.isDone
            }
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    var isNeedShowCopyView: Bool = false {
        didSet {
            copyContentView.isHidden = !isNeedShowCopyView
            copyContentView.snp.remakeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.top.equalTo(loadingImgView.snp.bottom).offset(16)
                make.height.equalTo(isNeedShowCopyView ? 37.0 : 0.0)
                make.bottom.equalTo(0)
            }
        }
    }
    
    var isNeedShowLoadingView: Bool = false {
        didSet {
            loadingImgView.isHidden = !isNeedShowLoadingView
            loadingImgView.snp.remakeConstraints { make in
                make.right.equalTo(-16)
                make.width.equalTo(26)
                make.height.equalTo(isNeedShowLoadingView ? 18 : 0)
                make.top.equalTo(messageLabel.snp.bottom).offset(isNeedShowLoadingView ? 6 : 0)
            }
        }
    }
    
    lazy var whiteContentView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.layer.cornerRadius = 12.0
        v.clipsToBounds = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(didMessageClicked))
        v.addGestureRecognizer(tap)
        
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didCopyTextLongGesture(_:)))
        v.addGestureRecognizer(longPress)
        return v
    }()
    
    var rightAngleView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.isHidden = true
        return v
    }()
    
    lazy var messageLabel: UILabel = {
        let lable = UILabel()
        lable.textColor = UIColor.mainTextColor
        lable.textAlignment = .left
        lable.font = UIFont.PFSC_R(ofSize: 14)
        lable.numberOfLines = 0
        return lable
    }()
    
    lazy var copyContentView: UIView = {
        let v = UIView()
        v.clipsToBounds = true
        v.isHidden = true
        
        let bgImgV = UIImageView(image: UIImage(named: "ai_chat_copy_bg"))
        v.addSubview(bgImgV)
        bgImgV.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(KScreenWidth-40)
        }
        
        let label = UILabel()
        label.textColor = UIColor.init(hex: 0x8993A2)
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.text = "以上内容由银河AI生成"
        v.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.centerY.equalToSuperview()
            make.height.equalTo(17)
        }
        
        let copyBtn = UIButton()
        copyBtn.setTitle("复制", for: .normal)
        copyBtn.titleLabel?.font = .PFSC_R(ofSize: 12)
        copyBtn.setTitleColor(.mainTextColor, for: .normal)
        copyBtn.setImage(UIImage(named: "ai_chat_msg_copy"), for: .normal)
        copyBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
        copyBtn.addTarget(self, action: #selector(didCopyTextButtonClicked), for: .touchUpInside)
        v.addSubview(copyBtn)
        copyBtn.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.centerY.equalToSuperview()
            make.height.equalTo(37)
            make.width.equalTo(82)
        }
        copyBtn.iconInLeft(spacing: 2.0)
        
        return v
    }()
    
    let loadingImgView: LottieAnimationView! = {
        let lottieView = LottieAnimationView(name: "ai_chat_loading")
        lottieView.loopMode = .loop
        lottieView.contentMode = .scaleAspectFit
        lottieView.play()
        return lottieView
    }()
    
    @objc func didCopyTextButtonClicked() {
        let text = message.body.contentText
        UIPasteboard.general.string = text
        YHHUD.flash(message: "复制成功")
    }
    
    @objc func didCopyTextLongGesture(_ sender: UIGestureRecognizer) {
        let text = message.body.contentText
        if sender.state == .began {
            UIPasteboard.general.string = text
            YHHUD.flash(message: "复制成功")
        }
    }
    
    lazy var shadowView: YHAIChatShadowView = {
        let v = YHAIChatShadowView()
        return v
    }()

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func setupUI() {
        
        selectionStyle = .none
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        contentView.addSubview(shadowView)
        contentView.addSubview(rightAngleView)
        contentView.addSubview(whiteContentView)
        whiteContentView.addSubview(messageLabel)
        whiteContentView.addSubview(loadingImgView)
        whiteContentView.addSubview(copyContentView)
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalTo(whiteContentView)
        }
        
        rightAngleView.snp.makeConstraints { make in
            make.top.left.equalTo(whiteContentView)
            make.width.height.equalTo(15)
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(20)
            make.bottom.equalTo(0)
        }
        
        messageLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(16)
        }
        
        loadingImgView.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.width.equalTo(26)
            make.height.equalTo(18)
            make.top.equalTo(messageLabel.snp.bottom).offset(6)
        }
        
        copyContentView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.top.equalTo(loadingImgView.snp.bottom).offset(16)
            make.height.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
    @objc func didMessageClicked() {
        
        UIApplication.shared.yhKeyWindow()?.endEditing(true)
        messageClick?(self.message.body.contentText)
    }
}
