//
//  TSAIRintoneHistoryCell.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/6.
//
import Combine
import SwipeCellKit
class TSAIRintoneHistoryCell: SwipeCollectionViewCell  {
    
    public var colComponent:TSCollectionViewComponent?
    public var colAttributes:[String : Any]?

    override init(frame: CGRect) {
        super.init(frame: frame)
        creatUI()
        dealThings()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    static let cellID = "TSAIRintoneHistoryCell"

    lazy var setRingBtn: TSUIExpandedTouchButton = {
        let setRingBtn = TSUIExpandedTouchButton()
        setRingBtn.setUpButton(image: UIImage(named: "ai_setRing_icon")){[weak self]  in
            guard let self = self else { return }
            actionHandler(any: "SetNow")
        }
        setRingBtn.setImage(UIImage(named: "ai_setRing_icon"), for: .normal)
        return setRingBtn
    }()
    
    lazy var ringView: TSRingToneCellView = {
        let ringToneView = TSRingToneCellView()
        ringToneView.backgroundColor = .clear
        ringToneView.clickPlayHandel = { [weak self] isplay in
            guard let self = self else { return }
            
            if playSelf{
                if TSBusinessAudioPlayer.shared.isLoading{
                    return
                }

                if TSBusinessAudioPlayer.shared.isPlaying{
                    TSBusinessAudioPlayer.shared.stop()
                }else{
                    TSBusinessAudioPlayer.shared.playUrlString(modelUrlString,indexPath: indexPath)
                }
                
            }else{
                TSBusinessAudioPlayer.shared.playUrlString(modelUrlString,indexPath: indexPath)
            }
            
           
            
        }
        return ringToneView
    }()
    
    
    lazy var exampleView: UIView = {
        let exampleView = UIView()
        exampleView.backgroundColor = "#7E57F4".uiColor
        
        let textLabel = UILabel.createLabel(
            text: "Example".localized,
            font: .font(size: 12),
            textColor: .white
        )
        
        exampleView.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.top.edges.equalTo(UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6))
        }
        
        kDelayMainShort {
            exampleView.makeCorner([.topLeft,.bottomLeft], radius: 10)
        }
        return exampleView
    }()
    
    
    lazy var vipView: UIImageView = {
        let vipView = UIImageView.createImageView(imageName: "ring_vip")
        vipView.isHidden = true
        return vipView
    }()
    
    var model:TSActionInfoModel?{
        didSet{
            guard let model = model else { return }
            ringView.timeLab.text = Float(model.request.duration).floatToMinuteSecond()
            ringView.nameLab.text = model.response.title
            ringView.setCoverImageView(urlString: model.response.coverUrl)
            exampleView.isHidden = model.modelType != .example
            vipView.isHidden = true
            
            self.changePlayerState(state: TSBusinessAudioPlayer.shared.currentPlayerState)
        }
    }
    
    var ringModel:TSRingModel?{
        didSet{
            guard let ringModel = ringModel else { return }
            ringView.timeLab.text = Float(ringModel.duration).floatToMinuteSecond()
            ringView.nameLab.text = ringModel.title
            ringView.setCoverImageView(urlString: "")
            exampleView.isHidden = true
            vipView.isHidden = !ringModel.vip
            self.changePlayerState(state: TSBusinessAudioPlayer.shared.currentPlayerState)
        }
    }
    
    
    override var isSelected: Bool{
        didSet{
            debugPrint("isSelected = \(isSelected),indexPath = \(indexPath)")
//            ringView.isloading = isSelected
//            if isSelected, self.ringView.isPlay == false{
//                
//                if let model = model{
//                    TSBusinessAudioPlayer.shared.playUrlString(model.response.musicUrl)
//                }else if let ringModel = ringModel{
//                    TSBusinessAudioPlayer.shared.playUrlString(ringModel.audioUrl)
//                }
//                
//            }else{
//                TSBusinessAudioPlayer.shared.stop()
//                backgroundColor = .cardColor
//            }
        }
    }

        
    var playSelf:Bool{
        return TSBusinessAudioPlayer.shared.isPlayURLString(string: modelUrlString,indexPath: indexPath)
    }

    var modelUrlString:String{
        var urlString:String = ""
        if let model = model{
            urlString = model.response.musicUrl
        }else if let ringModel = ringModel{
            urlString = ringModel.audioUrl
        }
        return urlString
    }

    func creatUI() {
        cornerRadius = 16.0
        backgroundColor = .cardColor
  
        contentView.addSubview(exampleView)
        exampleView.snp.makeConstraints { make in
            make.trailing.equalToSuperview()
            make.top.equalTo(0)
            make.height.equalTo(20)
        }
  
        contentView.addSubview(ringView)
        ringView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    
        contentView.addSubview(setRingBtn)
        setRingBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalTo(-16)
            make.width.height.equalTo(20)
        }
        
        contentView.addSubview(vipView)
        vipView.snp.makeConstraints { make in
            make.top.trailing.equalTo(0)
            make.width.height.equalTo(24)
        }
        

    }
    
    func dealThings(){
        NotificationCenter.default.addObserver(forName: .kBusinessAudioStateChange, object: nil, queue: nil) { notification in
            if let userInfo = notification.userInfo as? [String: TSBusinessAudioPlayer.PlayerState], let state = userInfo["PlayerState"] {
                kExecuteOnMainThread {
                    self.changePlayerState(state: state)
                }
            }
        }
    }
    
    
    func changePlayerState(state:TSBusinessAudioPlayer.PlayerState){
//        if self.isSelected == false {
//        if self.modelIsSelected == false {
            if playSelf == false {
            self.ringView.isPlay = false
            backgroundColor = .cardColor
            return
        }
        
        switch state {
        case .loading(let progress):
            if progress == 0.0 {
                self.ringView.isloading = true
            }else if progress == 1.0 {
                self.ringView.isloading = false
            }
        case .play:
            self.ringView.isPlay = true
            backgroundColor = "#3C213F".uiColor
        case .stop:
            self.ringView.isloading = false
            self.ringView.isPlay = false
            backgroundColor = .cardColor
        default:
            break
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    var indexPath:IndexPath? {
        guard let collectionView = self.superview as? UICollectionView else {
//            print("Cell 的 indexPath 无法获取 UICollectionView")
            return nil
        }
        
        if let indexPath = collectionView.indexPath(for: self) {
//            print("Cell 的 indexPath: \(indexPath)")
            return indexPath
        } else {
//            print("Cell 的 indexPath 无法获取")
            return nil
        }
    }
}

extension TSAIRintoneHistoryCell : TSComponentView {
    
    func renderView(with object: Any?, component: TSCollectionViewComponent, attributes: [String : Any]?) {
        self.colComponent = component
        self.colAttributes = attributes
        
        
        if let itemModel = object as? TSColVVMItemModel{
            if let dataModel = itemModel.dataModel as? TSRingModel{
                ringModel = dataModel
            }
        }

    }
    
//    public var indexPath:IndexPath?{
//        if let attributes = colAttributes , let IndexPath = attributes[kIndexPath] as? IndexPath{
//            return IndexPath
//        }
//        return nil
//    }
//    
    public var itemActionHandler: ((Any?, IndexPath) -> Void)?{
        if let colComponent = colComponent,let itemActionHandler = colComponent.itemActionHandler {
            return itemActionHandler
        }
        return nil
    }
    
    public func actionHandler(any:Any?){
        if let sectionActionHandler = itemActionHandler ,let indexPath = indexPath{
            sectionActionHandler(any,indexPath)
        }
    }
}
