//
//  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]?
    public var cancellable: [AnyCancellable] = []
    
    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"))
        setRingBtn.setImage(UIImage(named: "ai_setRing_icon"), for: .normal)
        return setRingBtn
    }()
    
    lazy var ringView: TSRingToneCellView = {
        let ringToneView = TSRingToneCellView()
        ringToneView.cornerRadius = 0.0
        ringToneView.clickPlayHandel = { [weak self] isplay in
            guard let self = self else { return }
            clickPlay()
        }
        return ringToneView
    }()
    
    
    lazy var generateView: TSRingToneGenerateView = {
        let generateView = TSRingToneGenerateView()
        generateView.isHidden = true
        generateView.refreshHandel = { [weak self]  in
            guard let self = self else { return }
            guard let oldModel = model else { return }
            TSGenerateRintoneOperationQueue.shared.creatOperation(uuid: oldModel.uuid).creatRintone(oldModel: oldModel, prompt: oldModel.request.prompt, promptSort: oldModel.request.promptSort)
        }
        return generateView
    }()
    
    
    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{
            modelDidSet()
        }
    }

    var ringModel:TSRingModel?{
        didSet{
            ringModelDidSet()
        }
    }
     
    func creatUI() {
        cornerRadius = 16.0
        backgroundColor = .cardColor
        
        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)
        }
        
        contentView.addSubview(exampleView)
        exampleView.snp.makeConstraints { make in
            make.trailing.equalToSuperview()
            make.top.equalTo(0)
            make.height.equalTo(20)
        }
  
        contentView.addSubview(generateView)
        generateView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
    }
    
    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)
                }
            }
        }
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
//        cancellable.removeAll()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}


extension TSAIRintoneHistoryCell {
    
    func modelDidSet(){
        guard let model = model else { return }
        if let rintoneOperation = TSGenerateRintoneOperationQueue.shared.findOperation(uuid: model.uuid) as? TSGenerateRintoneOperation {
            rintoneOperation.currentActionInfoModelChanged = { [weak self] actionInfoModel in
                guard let self = self else { return }
                DispatchQueue.main.async {
                    self.updataActionInfoModelView(model: actionInfoModel)
                }
            }
        }

        updataActionInfoModelView(model: model)
        dePrint("model actionStatus 收到=\(model.actionStatus)")
    }
    
    func ringModelDidSet(){
        guard let ringModel = ringModel else { return }

        ringView.timeLab.text = Float(ringModel.duration).floatToMinuteSecond()
        ringView.nameLab.text = ringModel.title
        ringView.setCoverImageView(urlString: "")
        exampleView.isHidden = true
        generateView.isHidden = true
        vipView.isHidden = !ringModel.vip
        self.changePlayerState(state: TSBusinessAudioPlayer.shared.currentPlayerState)
    }
    
}


extension TSAIRintoneHistoryCell {
    func clickPlay() {
        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)
        }
    }
    

    func changePlayerState(state:TSBusinessAudioPlayer.PlayerState){
        if playSelf == false {
            if ringView.isPlay == true ||
                ringView.isloading == true
            {
                ringView.handelAudioPlayerStateChange(state: .stop)
            }
            return
        }
//        dePrint("changePlayerState = \(state)")
        ringView.handelAudioPlayerStateChange(state: state)
    }
    
    
    func updataActionInfoModelView(model:TSActionInfoModel){
        
        if model.modelType == .example {
            model.actionStatus = .success
        }
        
        switch model.actionStatus {
        case .pending,.running:
            generateView.isHidden = false
            generateView.setProgress(progress: model.percent)
        case .success:
            generateView.isHidden = true
            
            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)
            
        case .failed:
            generateView.isHidden = false
            generateView.setFail()
        }
    }

    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
    }
    
    
    var indexPath:IndexPath? {
        return setRingBtn.indexPath
    }
}
