//
//  TSTextPicGennerateVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/20.
//

class TSTextPicGennerateVC: TSBottomAlertVC {
    
    var imageModel:TSGenmojiModel?
    var complete:((TSGenmojiModel)->Void)
    var aiText:String

    init(aiText: String,complete:@escaping ((TSGenmojiModel)->Void)) {
        self.aiText = aiText
        self.complete = complete
        super.init()
    }
    
    var viewModel:TSTextPicGennerateVM = TSTextPicGennerateVM()
    @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
        
        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)
//        netWorkImageView.snp.makeConstraints { make in
//            make.top.equalTo(94)
//            make.centerX.equalToSuperview()
//            make.width.equalTo(249*kDesignScale)
//            make.height.equalTo(441*kDesignScale)
//        }
        
        let netWorkImageViewW = k_ScreenWidth - 120.0
        let netWorkImageViewH = netWorkImageViewW/kTextWHScale
        netWorkImageView.snp.makeConstraints { make in
            make.top.equalTo(90)
            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()
        if let model = imageModel {
            complete(model)
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    
    
    
    //重试
    @objc override func clickSubmitBtn(){
        viewModel.creatImageEmoji(text:aiText)
    }
    
//    @objc override func clickCancelBtn(){
//        if let image = getSuccessImage() {
//            UIDevice.copyImage(image: image)
//            kSavePhotoSuccesswShared.show(atView: self.view,text: "Copy Successfully".localized,showViewBtn:false)
//        }
//    }
    
    //保存功能
    @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.creatImageEmoji(text: self.aiText)
        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 TSTextPicGennerateVC {
    
    
    func getSuccessImage()->UIImage?{
        if let image = netWorkImageView.image {
            return image.pngImage
        }
        return nil
    }
    
}
extension TSTextPicGennerateVC {
    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
//        cancelBtn.isHidden = true
//        xBtn.isHidden = false
        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
//        cancelBtn.isHidden = true
//        confirmBtn.isHidden = true
//        xBtn.isHidden = false
        isClickTheBlankClosePage = true
        regenerateBtn.isHidden = true
        netWorkImageView.isHidden = true
    }
    
    func showSuccess(model:TSGenmojiModel){
        generateInView.isHidden = true
        generateInView.isRotating = false
        submitBtn.isHidden = true
        bigSaveBtn.isHidden = false
//        cancelBtn.isHidden = true
//        confirmBtn.isHidden = false
//        xBtn.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: .textGeneratePic)
    }
}
