//
//  TSAIPhotoGeneratorVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/6/11.
//

import Kingfisher
class TSAIPhotoGeneratorVC: TSAIPhotoGeneratoBaserVC {
    var generatorModel:TSAIListPhotoGeneratorModel
    init(generatorModel:TSAIListPhotoGeneratorModel,infoModel:TSActionInfoModel? = nil,complete:@escaping ((TSActionInfoModel)->Void)) {
        self.complete = complete
        self.generatorModel = generatorModel
        super.init()
        self.infoModel = infoModel
    }
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var complete:((TSActionInfoModel)->Void)
    var backstageBlock:(()->Void)?
    
    
    var progressState = TSProgressState.none
    
    var uuidString:String = UUID().uuidString
    var operation:TSGenerateBaseOperation?
    var isNeedSavePhoto:Bool {
        if isSavePhotoMark == false,let _ = infoModel {
            return true
        }
        return false
    }
    
//    var viewModel: TSAIListPhotoGeneratorBaseVM!

    lazy var generateInView : TSGeneratorView = {
        let generateInView = TSGeneratorView()
        generateInView.isUploadImage = false
        generateInView.animationView.setText(time: String(format: "～ %d mins".localized, 2), info: "Lots of cats are traveling right now, so this might take a bit.".localized)
        generateInView.clickErrorBlock = { [weak self] style in
            guard let self = self else { return }
            
            switch style {
            case .netWorkError:
                clickRegenerateBtn()
            default:
                self.dismiss(animated: false, completion: nil)
                break
            }
        }
        generateInView.clickBackstageBlock = { [weak self]  in
            guard let self = self else { return }
            clickBackstageBtn()
        }
        generateInView.clickCloseBlock = { [weak self]  in
            guard let self = self else { return }
            closePage()
        }
        return generateInView
    }()

    override func createView() {
        self.view.backgroundColor = .clear
        super.createView()
        navRightBtn.isHidden = true
        contentView.isHidden = true
        view.addSubview(generateInView)
        generateInView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    @objc func clickBackstageBtn() {
        self.operation?.backstageGeneration()
        NotificationCenter.default.post(name: .kAIPhotoDataChanged, object: nil)
        backstageBlock?()
        self.dismiss(animated: true, completion: nil)
    }
    
    override func closePage() {
    
        if progressState.isResult {
            if isNeedSavePhoto{
                TSCustomAlertController.show(in: self, config: TSCustomAlertController.AlertConfig(
                    message: "You haven't saved the photo yet. Are you sure to quit?".localized,
                    messageColor: .white,
                    messageFont: .systemFont(ofSize: 16),
                    
                    cancelTitle: "Quit".localized,
                    cancelColor: .white,
                    
                    confirmTitle: "Save".localized,
                    confirmColor: .themeColor,
                    
                    cancelAction: { [weak self]  in
                        guard let self = self else { return }
                        print("用户点击了Leave")
                        cancelDidmiss()
                    },
                    confirmAction: { [weak self]  in
                        guard let self = self else { return }
                        print("用户点击了Stay")
                        clickSaveBtn()
                    }
                ))
            }else{
                cancelDidmiss()
            }
        }else{
            TSCustomAlertController.show(in: self, config: TSCustomAlertController.AlertConfig(
                message: "As you leave, your task will be interrupted and no result.".localized,
                messageColor: .white,
                messageFont: .systemFont(ofSize: 16),
                
                cancelTitle: "Leave".localized,
                cancelColor: .white,
                
                confirmTitle: "Wait".localized,
                confirmColor: .themeColor,
                
                cancelAction: { [weak self]  in
                    guard let self = self else { return }
                    print("用户点击了Leave")
                    
                    if let model = infoModel{
                        TSRMShared.aiListDB.deleteListModel(id: model.id)
                        NotificationCenter.default.post(name: .kAIPhotoDataChanged, object: nil)
                    }
        
                    cancelDidmiss()
                },
                confirmAction: {
                    print("用户点击了Stay")
                }
            ))
        }
    }

    func cancelDidmiss(){
        operation?.cancel()
        self.dismiss(animated: true, completion: nil)
    }
    //重新生成
    @objc func clickRegenerateBtn(){
//        if generatorModel.generatorStyle == .creatVideo {
//            if kPurchaseBusiness.kJudgeVip(externalBool: true, vc: self){ return } //判断 vip
//        }else{
            if kPurchaseBusiness.kJudgeVipFreeType(vipFreeNumType: .general){ return }//判断 vip
//        }
        generatorOperation()
    }

    override func dealThings() {
        self.uuidString = UUID().uuidString
        generatorOperation()
    }
    
    func generatorOperation() {
        
        if let model = self.infoModel{
            if model.actionStatus == .failed{
                generatorCreatRing(oldModel: model)
            }else if model.response.resultUrl.count > 0 {
                upDateView(state: .success(model), model: model)
                return
            }
        }else{
            generatorNew()
        }
    }
}
extension TSAIPhotoGeneratorVC{
    
    func generatorNew() {
        let operation:TSGenerateBasePhotoOperation = TSGenerateBasePhotoOperationQueue.shared.creatOperation(uuid: self.uuidString)
        self.operation = operation
        operation.$stateDatauPblished.receive(on: DispatchQueue.main).sink {[weak self]  (state,model) in
            guard let self = self else { return }
            self.upDateView(state: state, model: model)
        }.store(in: &cancellable)
        
        operation.uploadImage(generateStyleModel: self.generatorModel)  { [weak self] actionInfoModel in
            guard let self = self else { return }
            guard let oldModel = actionInfoModel else {return}
            generatorCreatRing(oldModel: oldModel)
        }
    }
    
    func generatorCreatRing(oldModel:TSActionInfoModel) {
        let operation:TSGenerateBasePhotoOperation = TSGenerateBasePhotoOperationQueue.shared.creatOperation(uuid: self.uuidString)
        self.operation = operation
        operation.$stateDatauPblished.receive(on: DispatchQueue.main).sink {[weak self]  (state,model) in
            guard let self = self else { return }
            self.upDateView(state: state, model: model)
        }.store(in: &cancellable)
        
        operation.creatImage(oldModel: oldModel){ [weak self]  success in
            guard let self = self else { return }
            if success {
                generateInView.setBackgroundGenerateBtnHidden(false)
            }
        }
    }
}
extension TSAIPhotoGeneratorVC {
    func getSuccessImage()->UIImage?{
        if let image = networkImageView.image {
            return image.pngImage
        }
        return nil
    }
}
extension TSAIPhotoGeneratorVC {
    func upDateView(state:TSProgressState,model:TSActionInfoModel?){
        progressState = state
        switch state {
            case .failed(let errorStr,let code):
                showError(text: errorStr,code:code)
            case .success:
                if let model = model {
                    showSuccess(model: model)
                }else{
                    showError(text: "")
                }
            case .progressString(let string):
                showProgress(text: string)
            default:
                showLoading()
        }
    }
    
    func showProgress(text:String) {
        generateInView.updateShowProgress(text: text)
        contentView.isHidden = true
    }
    
    func showLoading(){
        generateInView.updateShowLoading(text: "Processing".localized + " " + kPercentlocalized(0))
        contentView.isHidden = true
    }
    
    func showError(text:String,code:Int = 0){
        generateInView.updateShowError(text: text,code: code)
        contentView.isHidden = true
    }
    
    func showSuccess(model:TSActionInfoModel){
        contentView.isHidden = false
        generateInView.updateShowSuccess()
        infoModel = model
        if let model = infoModel {
            complete(model)
        }
    }
}
