//
//  TSRecollectionCell.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/7.
//


import RealmSwift
class TSRecollectionCell: TSBaseCollectionCell {
    var buttonTapped:((String)->Void)?
    var operation:TSGenerateBasePhotoOperation?
    var dataModel:TSActionInfoModel = TSActionInfoModel(){
        didSet {
            self.updataActionInfoModelView(model: dataModel)
            if let operation = TSGenerateBasePhotoOperationQueue.shared.findOperation(uuid: dataModel.uuid) as? TSGenerateBasePhotoOperation {
                DispatchQueue.main.async {
                    operation.currentActionInfoModelChanged = { [weak self] actionInfoModel in
                        guard let self = self else { return }
                        DispatchQueue.main.async {
                            self.updataActionInfoModelView(model: actionInfoModel)
                        }
                    }
                    operation.processProgressChanged = { [weak self] progress in
                        guard let self = self else { return }
                        generateView.setProgress(progress: progress)
                    }
                    self.operation = operation
                }
            }else{
                self.operation?.currentActionInfoModelChanged = nil
                self.operation = nil
            }
        }
    }
    
    lazy var generateView: TSGennerateCellView = {
        let generateView = TSGennerateCellView()
        generateView.isHidden = true
        generateView.clickHandel = { [weak self] index in
            guard let self = self else { return }
            if index == 0 { // 退出
                buttonTapped?("cancel")
            }else if index == 2 { //敏感内容
                buttonTapped?("delete")
            }else if index == 1 {
//                if kJudgeVipFreeType(vipFreeNumType: .aiGenerate){ return }
                if TSGenerateBasePhotoOperationQueue.shared.isAvailability {
                    let generatePTPOperation = TSGenerateBasePhotoOperationQueue.shared.creatOperation(uuid: dataModel.uuid)
                    generatePTPOperation.isSaveProcessToDB = true
                    generatePTPOperation.creatImage(oldModel: dataModel){ complete in }
                    generateView.setProgress(progress: 0)
                }else{
                    if let window = WindowHelper.getCurrentWindow() {
                        kTextToastShared.show(atView: window,text: String(format: "%d task is processing".localized, 1)){
                            TSRecollectionVC.showPosition()
                        }
                    }
                }
            }
        }
    
        return generateView
    }()
    
    
    lazy var exampleView: UIView = {
        let exampleView = UIView()
        exampleView.backgroundColor = "#232323".uiColor.withAlphaComponent(0.3)
        exampleView.cornerRadius = 10.0
        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
        return exampleView
    }()
    
    
    lazy var showImageView: UIImageView = {
        let showImageView = UIImageView.createImageView(contentMode: .scaleAspectFill)
        showImageView.backgroundColor = .gray
        return showImageView
    }()
    
    
    lazy var bgImageView: UIImageView = {
        let imageView = UIImageView.createImageView(image:.recollectionItemBg,contentMode: .scaleToFill)
        return imageView
    }()

    lazy var frontImageView: UIImageView = {
        let imageView = UIImageView.createImageView(image:.recollectionItemFront,contentMode: .scaleToFill)
        return imageView
    }()
    
    lazy var textLabel: UILabel = {
        let textLabel = UILabel.createLabel(font: .font(name: .CoveredByYourGrace,size: 14,weight: .bold),textColor: "#3D3D3D".uiColor,numberOfLines: 2)
        return textLabel
    }()
    
    

//    lazy var videoIconImageView: UIImageView = {
//        let videoIconImageView = UIImageView.createImageView(image:.videoIcon,contentMode: .scaleToFill,autoMirrored:false)
//        videoIconImageView.isHidden = true
//        return videoIconImageView
//    }()
    
    @objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
        // 确保只在手势开始时触发一次
        guard gestureRecognizer.state == .began else { return }
        buttonTapped?("delete")
    }
    
    override func creatUI() {
        
        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
        longPressRecognizer.minimumPressDuration = 0.5 // 设置最小长按时间（秒）
        contentView.addGestureRecognizer(longPressRecognizer)

        bgContentView.addSubview(bgImageView)
        bgContentView.addSubview(showImageView)
        bgContentView.addSubview(frontImageView)
        bgContentView.addSubview(textLabel)
        bgContentView.addSubview(exampleView)
        
        bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        showImageView.snp.makeConstraints { make in
            make.top.equalTo(13.0)
            make.leading.equalTo(10)
            make.trailing.equalTo(-10)
            make.bottom.equalTo(-40*kDesignScale)
        }
        
        frontImageView.snp.makeConstraints { make in
            make.top.leading.equalTo(-6)
            make.width.equalTo(53)
            make.height.equalTo(36)
        }
        
        textLabel.snp.makeConstraints { make in
            make.leading.equalTo(10)
            make.trailing.equalTo(0)
            make.bottom.equalTo(-2)
            make.height.equalTo(28*kDesignScale)
        }
        
        exampleView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.leading.equalTo(8)
            make.height.equalTo(20)
        }
        
//        contentView.addSubview(videoIconImageView)
//        videoIconImageView.snp.makeConstraints { make in
//            make.top.equalTo(8)
//            make.leading.equalTo(8)
//            make.width.height.equalTo(20)
//        }
        
        contentView.addSubview(generateView)
        generateView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension TSRecollectionCell {
    func updataActionInfoModelView(model:TSActionInfoModel){
        
        if model.modelType == .example {
            model.actionStatus = .success
        }
        showImageView.image = nil
        //dePrint("updataActionInfoModelView model.actionStatus 收到 = \(model.actionStatus)")
        switch model.actionStatus {
        case .pending,.running:
            bgContentView.isHidden = true
            generateView.isHidden = false
            generateView.setProgress(progress: model.percent*kPercentScale)
            generateView.locationLabel.text = model.request.inputText
        case .success:
            bgContentView.isHidden = false
            generateView.isHidden = true
//            videoIconImageView.isHidden = true
            if model.modelType == .example {
                exampleView.isHidden = false
                showImageView.image = UIImage(named: model.response.resultUrl)
            }else{
                exampleView.isHidden = true
                
//                videoIconImageView.isHidden = !model.isVideo
//                if dataModel.isVideo {
//                    videoIconImageView.isHidden = false
//                    showImageView.setAsyncImage(urlString: model.videoPreviewUrlString,contentMode: .scaleAspectFill,backgroundColor: .white.withAlphaComponent(0.1))
//                }else {
                    showImageView.setAsyncImage(urlString: model.response.resultUrl,contentMode: .scaleAspectFill,backgroundColor: .white.withAlphaComponent(0.1))
//                }
            }
            
            textLabel.text = model.request.inputText
            
        case .failed:
            bgContentView.isHidden = true
            generateView.isHidden = false
            generateView.locationLabel.text = model.request.inputText
            if model.upImageURLExpired { //任务已经过期了
                generateView.setTaskExpired()
            }else{
                generateView.setFailText(text: model.response.codeErrorMsg, refresh: !model.response.sensitiveError)
            }
            
        }
        
    }
}
