//
//  TSPTPGeneratorVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/26.
//

class TSPTPGeneratorVC: TSBottomAlertVC {
    
    var imageModel:TSGenmojiModel?
    var complete:((TSGenmojiModel)->Void)
    
    var prompt:String
    var promptSort:String
    var imageUrl:String
    var upLoadImage:UIImage

    init(prompt:String,promptSort:String,imageUrl:String,upLoadImage:UIImage,complete:@escaping ((TSGenmojiModel)->Void)) {
        self.prompt = prompt
        self.promptSort = promptSort
        self.imageUrl = imageUrl
        self.upLoadImage = upLoadImage
        self.complete = complete
        super.init()
    }
    
    lazy var viewModel: TSPTPGeneratorVM = {
        let viewModel:TSPTPGeneratorVM = TSPTPGeneratorVM(prompt: prompt,upLoadImage:upLoadImage)
        return viewModel
    }()

    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var netWorkImageView : UIImageView = {
        let netWorkImageView = UIImageView.createImageView(imageName: "",corner: 16.0)
        netWorkImageView.isHidden = true
        return netWorkImageView
    }()
    
    
    lazy var generateInView : TSCommonloadingView = {
        let generateInView = TSCommonloadingView()
        return generateInView
    }()
    
    //大保存按钮
    lazy var bigSaveBtn: UIButton = {
        let bigSaveBtn = kCreateNormalSubmitBtn(title: "Save".localized) { [weak self]  in
            guard let self = self else { return }
            clickConfirmBtn()
        }
        bigSaveBtn.isHidden = true
        return bigSaveBtn
    }()
    
    lazy var regenerateBtn: UIButton = {
        let regenerateBtn = UIButton.createButton(
            title: "regenerate",
            image: UIImage(named: "refresh_gary"),
            backgroundColor:.white.withAlphaComponent(0.1),
            font: .font(size: 12),
            titleColor: .white.withAlphaComponent(0.6),
            corner: 8.0)
        { [weak self]  in
            guard let self = self else { return }
            clickSubmitBtn()
        }
        regenerateBtn.contentEdgeInsets = UIEdgeInsets(top: 4, left: 7, bottom: 4, right: 7)
        regenerateBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
        regenerateBtn.isHidden = true
        return regenerateBtn
    }()
    
    override func createView() {
        super.createView()
        
        bottomView.frame = CGRectMake(0, 92, k_ScreenWidth, k_ScreenHeight-92)
        cancelBtn.isHidden = true
        confirmBtn.isHidden = true
        submitBtn.isHidden = true
        
        bottomView.addSubview(bigSaveBtn)
        bigSaveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(-34)
            make.centerX.equalToSuperview()
            make.width.equalTo(329)
            make.height.equalTo(60)
        }
        
        bottomView.addSubview(generateInView)
        generateInView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        bottomView.addSubview(netWorkImageView)
        let netWorkImageViewW = k_ScreenWidth - 120.0
        let netWorkImageViewH = netWorkImageViewW/kTextWHScale
        netWorkImageView.snp.makeConstraints { make in
            make.top.equalTo(90*kDesignScale)
            make.centerX.equalToSuperview()
            make.width.equalTo(netWorkImageViewW)
            make.height.equalTo(netWorkImageViewH)
        }

        bottomView.addSubview(regenerateBtn)
        regenerateBtn.snp.makeConstraints { make in
            make.top.equalTo(netWorkImageView.snp.bottom).offset(16)
            make.centerX.equalToSuperview()
            make.height.equalTo(28)
        }
        
    }
    
    override func closePage() {
        viewModel.cancelAllRequest()
        self.dismiss(animated: true, completion: nil)
    }
    
    //重试
    @objc override func clickSubmitBtn(){
        //判断 vip
        if kJudgeVip(externalBool: kPurchaseDefault.freeNumAvailable(type: .picToPic) == false, vc: self) {[weak self] in
            guard let self = self else { return }
        }{ return }
        
        viewModel.uploadAndCreatImage()
    }
    
    //保存功能
    @objc override func clickConfirmBtn(){
        if let image = getSuccessImage() {
            PhotoManagerShared.saveImageToAlbum(image) { success, error in
                if success {
                    kSavePhotoSuccesswShared.show(atView:self.view)
                }else{
                    debugPrint(error)
                }
            }
        }
    }
    
    override func dealThings() {
        viewModel.uploadAndCreatImage()
        viewModel.$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)
    }
    
}
extension TSPTPGeneratorVC {
    
    
    func getSuccessImage()->UIImage?{
        if let image = netWorkImageView.image {
            return image.pngImage
        }
        return nil
    }
    
}
extension TSPTPGeneratorVC {
    func upDateView(state:TSProgressState,model:TSGenmojiModel?){
        switch state {
            case .failed(let errorStr):
            showError(text: errorStr)
            case .success:
                if let model = model {
                    showSuccess(model: model)
                }else{
                    showError(text: nil)
                }
            default:
                showLoading()
        }
    }
    
    func showLoading(){
        generateInView.isHidden = false
        generateInView.showLoading(text: "Generating...".localized)
        generateInView.isRotating = true
        submitBtn.isHidden = true
        confirmBtn.isHidden = true
        bigSaveBtn.isHidden = true
        isClickTheBlankClosePage = false
        regenerateBtn.isHidden = true
        netWorkImageView.isHidden = true
    }
    
    func showError(text:String?){
        let msg = "Failed to Generate, please try later".localized
        generateInView.isHidden = false
        generateInView.showError(text: msg)
        generateInView.isRotating = false
        submitBtn.isHidden = false
        bigSaveBtn.isHidden = true
        isClickTheBlankClosePage = true
        regenerateBtn.isHidden = true
        netWorkImageView.isHidden = true
    }
    
    func showSuccess(model:TSGenmojiModel){
        generateInView.isHidden = true
        generateInView.isRotating = false
        submitBtn.isHidden = true
        bigSaveBtn.isHidden = false
        imageModel = model
        isClickTheBlankClosePage = true
        regenerateBtn.isHidden = false
        
        cancelBtn.isEnabled = false
        confirmBtn.isEnabled = false
        netWorkImageView.isHidden = false
        
//        netWorkImageView.snp.updateConstraints { make in
//            make.top.equalTo(94)
//            make.centerX.equalToSuperview()
//            make.width.equalTo(249*kDesignScale)
//            make.height.equalTo(441*kDesignScale)
//        }
        
        self.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder:kPlaceholderImage){ [weak self] image in
            guard let self = self else { return }
            cancelBtn.isEnabled = true
            confirmBtn.isEnabled = true
        }
        
        kPurchaseDefault.useOnceForFree(type: .picToPic)
        if let model = imageModel {
            model.request.promptSort = promptSort
            complete(model)
        }
    }
}
