//
//  TSAIPhotoImageCell.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/5.
//

class TSAIPhotoImageCell: TSBaseCollectionCell {
    
    
    var model:TSActionInfoModel?
    var style = TSColVVMStyple.posterHistory
    
    lazy var showImageView: UIImageView = {
        let showImageView = UIImageView.createImageView(imageName:"",contentMode: .scaleAspectFill)
        showImageView.backgroundColor = .gray
        return showImageView
    }()
    
    lazy var exampleView: UIView = {
        let exampleView = UIView()
        exampleView.backgroundColor = "#232323".uiColor.withAlphaComponent(0.3)
        
        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))
        }
        exampleView.isHidden = true
        exampleView.cornerRadius = 10.0
        return exampleView
    }()
    
    lazy var generateView: TSImageGenerateView = {
        let generateView = TSImageGenerateView()
        generateView.isHidden = true
        generateView.refreshHandel = { [weak self]  in
            guard let self = self else { return }
            guard let oldModel = model else { return }
            
            if style == .posterHistory {
                TSGeneratePosterOperationQueue.shared.creatOperation(uuid: oldModel.uuid).creatPoster(oldModel: oldModel, prompt: oldModel.request.prompt, promptSort: oldModel.request.promptSort)
            }else if style == .photoHistory {
                TSGeneratePhotoOperationQueue.shared.creatOperation(uuid: oldModel.uuid).creatPhoto(oldModel: oldModel, prompt: oldModel.request.prompt, promptSort: oldModel.request.promptSort)
            }
            
        }
        return generateView
    }()
    
    
    override func creatUI() {
        contentView.clipsToBounds = true
        contentView.addSubview(showImageView)
        showImageView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.leading.equalTo(0)
            make.trailing.bottom.equalTo(0)
        }
        
        if self.bounds.size.width == self.bounds.size.height {
            contentView.layer.cornerRadius = self.bounds.size.width/2
        }else{
            contentView.layer.cornerRadius = 16
        }
        
        contentView.addSubview(exampleView)
        exampleView.snp.makeConstraints { make in
            make.bottom.equalTo(-8)
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
        }
        
        contentView.addSubview(generateView)
        generateView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    override func renderView(with object: Any?, component: TSCollectionViewComponent, attributes: [String : Any]?) {
        super.renderView(with: object, component: component, attributes: attributes)
        if let itemModel = object as? TSColVVMItemModel{
            if let model = itemModel.dataModel as? TSActionInfoModel{
                self.model = model
                style = itemModel.style
                generateView.style = style
                if itemModel.style == .posterHistory {
                    if let rintoneOperation = TSGeneratePosterOperationQueue.shared.findOperation(uuid: model.uuid) as? TSGeneratePosterOperation {
                        DispatchQueue.main.async {
                            rintoneOperation.currentActionInfoModelChanged = { [weak self] actionInfoModel in
                                guard let self = self else { return }
                                DispatchQueue.main.async {
                                    self.updataActionInfoModelView(model: actionInfoModel)
                                }
                            }
                        }
                    }
                }else if itemModel.style == .photoHistory {
                    if let rintoneOperation = TSGeneratePhotoOperationQueue.shared.findOperation(uuid: model.uuid) as? TSGeneratePhotoOperation {
                        DispatchQueue.main.async {
                            rintoneOperation.currentActionInfoModelChanged = { [weak self] actionInfoModel in
                                guard let self = self else { return }
                                DispatchQueue.main.async {
                                    self.updataActionInfoModelView(model: actionInfoModel)
                                }
                            }
                        }
                    }
                }
                updataActionInfoModelView(model: model)
            }
        }
    }
    
    func updataActionInfoModelView(model:TSActionInfoModel){
        
        if model.modelType == .example {
            model.actionStatus = .success
        }
        dePrint("updataActionInfoModelView model.actionStatus 收到 = \(model.actionStatus)")
        switch model.actionStatus {
        case .pending,.running:
            generateView.isHidden = false
            generateView.setProgress(progress: model.percent)
        case .success:
            generateView.isHidden = true
            
            showImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFill)
            exampleView.isHidden = model.modelType == .example ? false : true
            
        case .failed:
            generateView.isHidden = false
            generateView.setFail()
        }
  
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        showImageView.image = nil
    }
    
}

class TSImageGenerateView:TSBaseView {
    
    var refreshHandel:(()->Void)?
    var style = TSColVVMStyple.posterHistory
    lazy var infoLabel: UILabel = {
        let infoLabel = UILabel.createLabel(font: .font(size: 12),textColor: .white,textAlignment: .center,numberOfLines: 0)
        return infoLabel
    }()
    
    lazy var refreshBtn: TSUIExpandedTouchButton = {
        let refreshBtn = TSUIExpandedTouchButton()
        refreshBtn.setUpButton(image: UIImage(named: "refresh_white")){[weak self]  in
            guard let self = self else { return }
            refreshHandel?()
        }
        refreshBtn.isHidden = true
        return refreshBtn
    }()
    
    
    override func creatUI() {
        backgroundColor = .cardColor

        contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickContentView)))
        
        let bgImageView = UIImageView.createImageView(imageName: "ringPhotoBg",contentMode: .scaleAspectFill)
        contentView.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(infoLabel)
        infoLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()//.offset(10)
            make.leading.equalTo(8)
            make.trailing.equalTo(-8)
        }
        
        contentView.addSubview(refreshBtn)
        refreshBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(infoLabel.snp.bottom).offset(8)
            make.width.height.equalTo(20.0)
        }
        
    }
    
    @objc func clickContentView() {
        if refreshBtn.isHidden == false{
            refreshHandel?()
        }
    }
    func setProgress(progress:Float) {
        refreshBtn.isHidden = true
        let progressInt = Int(progress*100)
        
        if style == .posterHistory {
            infoLabel.text = "Working on your contact poster\(progressInt)%..."
        }else if style == .photoHistory {
            infoLabel.text = "Working on your contact photo\(progressInt)%..."
        }
        infoLabel.textColor = "#E961F6".uiColor
//        infoLabel.applyGradient(colors: ["#E961F6".uiColor,"#7E57F4".uiColor])
    }
    
    func setFail(){
        setProgress(progress: 0.0)
        infoLabel.text = "Generation Failed".localized
        infoLabel.textColor = .white
        refreshBtn.isHidden = false
    }
}
