//
//  TSPhotoToPhotoVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/25.
//

class TSPhotoToPhotoVC: TSBaseVC {
    lazy var viewModel:TSPhotoToPhotoVM = {
        let vm = TSPhotoToPhotoVM()
        vm.isCanGennerateBlock = { [weak self] isCan in
            guard let self = self else { return }
            submitBtn.isEnabled = isCan
        }
        return vm
    }()
    
    lazy var collectionComponent: TSCollectionViewComponent = {
        let layout = UICollectionViewFlowLayout()
        let cp = TSCollectionViewComponent(frame: CGRect.zero, layout: layout, attributes: [:])
        cp.collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: k_Height_TabBar, right: 0)
        
        //点击 cell中的某个按钮
        cp.itemActionHandler = { [weak self] cellCp, indexPath in
            guard let self = self else { return }
            if indexPath == IndexPath(item: 0, section: 0) {

                if let text = cellCp as? String{
                    if text == "add" {//选择图片
                        photoPickerManager.pickSinglePhoto { [weak self] image in
                            guard let self = self else { return }
                            if let image = image {
                                viewModel.upLoadImage = image
                                cp.collectionView.reloadSections(IndexSet(integer: 0))
//                                viewModel.uploadImage()
                            }
                        }
                    }else if text == "delete"{//删除图片
                        viewModel.upLoadImage = nil
                        cp.collectionView.reloadSections(IndexSet(integer: 0))
                    }
                }
            }else if let model = cellCp as? TSPTPStyleModel ,indexPath == IndexPath(item: 0, section: 1) {
                //选择了某个样式
                viewModel.selectedPTPStyleModel = model
            }
        }
        
        cp.sectionActionHandler = { [weak self] cellCp, indexPath in
            guard let self = self else { return }
            if let cmd = cellCp as? String, cmd == "delete"  {
                showCustomAlert(message: "Are you sure to delete".localized, deleteHandler:  {
                    self.viewModel.removeAllHistoryList()
                    self.collectionComponent.clear()
                    self.collectionComponent.reloadView(with: self.viewModel.colDataArray)
                })
            }
        }
        
        cp.itemDidSelectedHandler = { [weak self] (object, indexPath) in
            guard let self = self else { return }
            if indexPath.section == 0{
                return
            }
            
            if let sections = viewModel.colDataArray.safeObj(At: indexPath.section) as? TSGenmojiCoLSectionModel{
                var dataModelArray:[TSGenmojiModel] = []
                for itemModel in sections.items {
                    dataModelArray.append(itemModel.dataModel)
                }
                
                let browseVC = TSPTPBrowseVC()
                browseVC.dataModelArray = dataModelArray
                browseVC.currentIndex = indexPath.item
                kPresentModalVC(target: self, modelVC: browseVC,transitionStyle: .crossDissolve)
            }


        }

        return cp
    }()
    
    
    lazy var submitBtn: UIButton = {
        let submitBtn = kCreateNormalSubmitBtn(title: getVipText()) { [weak self]  in
            guard let self = self else { return }
            uploadImage()
        }
        submitBtn.cornerRadius = 24.0
        submitBtn.isEnabled = false
        return submitBtn
    }()


    lazy var photoPickerManager: TSPhotoPickerManager = {
        let photoPickerManager = TSPhotoPickerManager(viewController: self)
        return photoPickerManager
    }()
    
    override func createView() {
    
        addNormalNavBarView()
        setPageTitle("AI Photo Generator".localized)
        
        contentView.addSubview(collectionComponent.collectionView)
        collectionComponent.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        collectionComponent.clear()
        collectionComponent.reloadView(with:viewModel.colDataArray)
        
//        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickCollectionView))
//        tapGesture.cancelsTouchesInView = false // 确保不影响其他点击事件
//        collectionComponent.collectionView.addGestureRecognizer(tapGesture)
        
        contentView.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { make in
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(48)
        }
        
    }
    
    override func dealThings() {
        NotificationCenter.default.addObserver(self, selector: #selector(vipInfoChanged), name: .kPurchaseDidChanged, object: nil)
    }
    
    @objc func vipInfoChanged() {
        kExecuteOnMainThread {
            //submitBtn
            self.submitBtn.setTitle(self.getVipText(), for: .normal)
        }
    }
    
    @objc func clickCollectionView() {
        view.endEditing(true)
    }

}

extension TSPhotoToPhotoVC {

    func uploadImage(){
        
        generateImage()
        return
        
//        if let upLoadImageUrl = viewModel.upLoadImageUrl, upLoadImageUrl.contains("http"){
//            generateImage()
//            return
//        }
//        
//        viewModel.uploadImage { [weak self] progress in
//            guard let self = self else { return }
//            let progressInt = Int(progress * 100)
//            let string = "\(progressInt)%"
//            TSToastShared.showProgress(progress: progress, status: string, containerView: self.view)
//        } completion: { [weak self]  data, error in
//            TSToastShared.hideLoading()
//            guard let self = self else { return }
//            if let error = error {
//                TSToastShared.showToast(text: error.localizedDescription)
//            }else{
//                if let string = data as? String {
//                    viewModel.upLoadImageUrl = string
//                    generateImage()
//                }
//            }
//        }
    }
    
    func generateImage() {
        
        //判断 vip
        if kJudgeVip(externalBool: kPurchaseDefault.freeNumAvailable(type: .picToPic) == false, vc: self) { [weak self] in
            guard let self = self else { return }
        }{ return }
        
        guard let prompt = viewModel.selectedPTPStyleModel?.prompt else { return }
        guard let imageText = viewModel.selectedPTPStyleModel?.imageText else { return }
//        guard let imageUrl = viewModel.upLoadImageUrl else { return }
//        guard imageUrl.contains("http") else { return }
        guard let upLoadImage = viewModel.upLoadImage else { return }
//        imageUrl = "https://be-aigc.oss-cn-shanghai.aliyuncs.com/f7e22b4e-45dc-41d7-91d4-4876c771f189.png"
        
        let gennerateVC = TSPTPGeneratorVC(prompt: prompt,promptSort: imageText , imageUrl: "",upLoadImage: upLoadImage) { [weak self] model in
            guard let self = self else { return }
            if viewModel.saveModel(model:model) {
                collectionComponent.clear()
                collectionComponent.reloadView(with:viewModel.colDataArray)
            }else{
                collectionComponent.reloadData()
            }
            
            vipInfoChanged()
        }
        
        kPresentModalVC(target: self, modelVC: gennerateVC,transitionStyle: .crossDissolve)
    }
    
    
    func getVipText()->String{
        if kPurchaseDefault.isVip {
            return "Generate"
        }
        return "Generate (\(kPurchaseDefault.freeNum(type: .picToPic)))"
    }
}

