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

private let cellId = "TSGeneralPhotoBrowseCell"
class TSGeneralPhotoBrowseVC: 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 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(TSGeneralPhotoBrowseCell.self, forCellWithReuseIdentifier: cellId)
        collectionView.isPagingEnabled = true
        return collectionView
    }()
    
    
    
    override func createView() {

        setNavBarViewHidden(true)
        

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


extension TSGeneralPhotoBrowseVC {
    @objc func clickClosePage(){
        self.pop()
    }
        
    @objc func clickDone(){
        getCurrentImage { [weak self] image in
            guard let self = self else { return }
            contactsTool.setContactsAvatar(avatarImage: image) { data, error in
                if error == nil {
                    kSavePhotoSuccesswShared.show(atView: self.view,showViewBtn: false)
                }
            }
        }
    }

    func getCurrentImage(imageBlock:@escaping (UIImage)->Void) {
        if let currentModel = currentModel{
            TSCommonTool.fetchImageWithCache(from: currentModel.response.resultUrl) { image, error in
                if let image = image{
                    imageBlock(image)
                }else{
                    kShowToastDataMissing()
                }
            }
        }else{
            kShowToastDataMissing()
        }
    }
}

//MARK: UICollectionViewDataSource
extension TSGeneralPhotoBrowseVC: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! TSGeneralPhotoBrowseCell
        if let model = dataModelArray.safeObj(At: indexPath.item){
            cell.previewView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFill)
            cell.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFill)
            cell.islandView.showImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage,contentMode: .scaleAspectFill)
        }
        return cell
    }
    
}

class TSGeneralPhotoBrowseCell : TSBaseCollectionCell{
    
    
    lazy var previewView:UIImageView = {
        let callPreview = UIImageView.createImageView(imageName: "",contentMode: .scaleAspectFill)
        let blurEffect = createBlurEffectView(style: .dark)
        callPreview.addSubview(blurEffect)
        blurEffect.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return callPreview
    }()

    lazy var islandView : TSTSIslandView = {
        let islandView = TSTSIslandView()
        islandView.nameLab.text = "baby"
        return islandView
    }()
    
    lazy var netWorkImageView : UIImageView = {
        let netWorkImageView = UIImageView()
        netWorkImageView.cornerRadius = 155
        return netWorkImageView
    }()
    
    override func creatUI() {
     
        bgContentView.addSubview(previewView)
        previewView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        bgContentView.addSubview(netWorkImageView)
        netWorkImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(310)
            make.height.equalTo(310)
        }

        bgContentView.addSubview(islandView)
        islandView.snp.makeConstraints { make in
            make.top.equalTo(k_Nav_Height+10)
            make.centerX.equalToSuperview()
            make.width.equalTo(islandView.width)
            make.height.equalTo(islandView.height)
        }
    }
}
