//
//  TSGeneralPosterBrowseVC.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/22.
//

private let cellId = "TSGeneralPosterBrowseCell"
class TSGeneralPosterBrowseVC: TSBaseVC {
    
    var dataModelArray = [TSActionInfoModel]()
    var currentImage:UIImage?{
        let cell = collectionView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? TSGeneralPhotoBrowseCell
        var image = cell?.netWorkImageView.image
        image = image?.pngImage
        return image
    }
    
    var currentModel:TSActionInfoModel?{
        if let model = dataModelArray.safeObj(At: currentIndex){
            return model
        }
        return nil
    }
    
    lazy var contactsTool: TSContactsTool = {
        let contactsTool = TSContactsTool(targetVC: self)
        return contactsTool
    }()
    
    var currentIndex:Int = 0
    
    lazy var previewView:UIImageView = {
        let callPreview = UIImageView.createImageView(imageName: "poster_call_bg",contentMode: .scaleAspectFill)
        return callPreview
    }()


    lazy var collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: k_ScreenWidth, height: k_ScreenHeight)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        collectionView.scrollsToTop = false
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        collectionView.register(TSGeneralPosterBrowseCell.self, forCellWithReuseIdentifier: cellId)
        collectionView.isPagingEnabled = true

        return collectionView
    }()
    
    
    
    override func createView() {

        setNavBarViewHidden(true)
        
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        contentView.addSubview(previewView)
        previewView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        let setButton = kCreateNormalSubmitBtn(title: "Set Now".localized, frame: CGRectMake(0, 0, 200, 48),action: { [weak self]  in
            guard let self = self else { return }
            clickDone()
        })
        contentView.addSubview(setButton)
        setButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 10)
            make.width.equalTo(setButton.width)
            make.height.equalTo(setButton.height)
        }
        
        let closeBtn = UIButton.createButton(image: UIImage(named: "close_gray")){[weak self]  in
            guard let self = self else { return }
            clickClosePage()
        }
        contentView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.leading.equalTo(11)
            make.top.equalTo(4+k_Height_StatusBar)
            make.width.height.equalTo(36)
        }

    }
    
    override func dealThings() {
        collectionView.reloadData()
        DispatchQueue.main.async {//将滚动操作放到主队列的下一个 RunLoop 中执行，确保 UICollectionView 已经完成布局和数据加载。
            self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex, section: 0), at: .bottom, animated: false)
        }
    }
}


extension TSGeneralPosterBrowseVC {
    @objc func clickClosePage(){
        self.pop()
    }
        
    @objc func clickDone(){
        if let currentModel = currentModel{
            TSCommonTool.fetchImageWithCache(from: currentModel.response.resultUrl) {[weak self] image, error in
                guard let self = self else { return }
                if let image = image{
                    PhotoManagerShared.saveImageToAlbum(image) { success, error in
                        if success {
                            kSavePhotoSuccesswShared.show(atView:self.view)
                        }else{
                            debugPrint(error)
                        }
                    }
                }else{
                    kShowToastDataMissing()
                }
            }
        }else{
            kShowToastDataMissing()
        }
    }
}

//MARK: UICollectionViewDataSource
extension TSGeneralPosterBrowseVC:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        resetIndexWithOffset(scrollView)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        resetIndexWithOffset(scrollView)
    }

    private func resetIndexWithOffset(_ scrollView: UIScrollView) {
        let item = Int((scrollView.contentOffset.y / scrollView.bounds.height).rounded())
        currentIndex = item
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataModelArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TSGeneralPosterBrowseCell
        if let model = dataModelArray.safeObj(At: indexPath.item){
            cell.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFill)
        }
        return cell
    }
    
}

class TSGeneralPosterBrowseCell : TSBaseCollectionCell{

    lazy var netWorkImageView : UIImageView = {
        let netWorkImageView = UIImageView()
        return netWorkImageView
    }()
    
    override func creatUI() {
        bgContentView.addSubview(netWorkImageView)
        netWorkImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}
