//
//  TSSmallIconBrowseVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/19.
//

private let cellId = "TSSmallIconBrowseCell"
class TSSmallIconBrowseVC: TSBottomAlertVC {

    
    var dataModelArray = [TSGenmojiModel]()
    var currentImage:UIImage?
    var currentIndex:Int = 0 {
        didSet{
            reloadUI()
        }
    }
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView.createCommon(delegate: self, cellReuseIds: [cellId])
        collectionView.isPagingEnabled = true
        collectionView.isHidden = true
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.minimumInteritemSpacing = 0
            flowLayout.minimumLineSpacing = 0
            flowLayout.itemSize = CGSize(width: k_ScreenWidth, height: 200)
            flowLayout.scrollDirection = .horizontal
        }
        return collectionView
    }()
    
    
    lazy var leftBtn: UIButton = {
        let leftBtn = UIButton.createButton(image: UIImage(named: "page_left")){ [weak self]  in
            guard let self = self else { return }
            self.collectionView.scrollToItem(at:  IndexPath(item: self.currentIndex+1, section: 0), at: .left, animated: true)
        }
        return leftBtn
    }()
    
    lazy var rightBtn: UIButton = {
        let rightBtn = UIButton.createButton(image: UIImage(named: "page_right")){ [weak self]  in
            guard let self = self else { return }
            self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex+1, section: 0), at: .left, animated: true)
        }
        return rightBtn
    }()
        
    override func createView() {
        super.createView()
        submitBtn.isHidden = true
    
        bottomView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(0)
            make.top.equalTo(80)
            make.height.equalTo(200)
        }
        
        bottomView.addSubview(leftBtn)
        leftBtn.snp.makeConstraints { make in
            make.leading.equalTo(17)
            make.top.equalTo(160)
            make.width.height.equalTo(40)
        }
        
        bottomView.addSubview(rightBtn)
        rightBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-18)
            make.top.equalTo(160)
            make.width.height.equalTo(40)
        }
        
        kDelayMainShort {
            self.collectionView.isHidden = false
            self.collectionView.reloadData()
            self.collectionView.setContentOffset(CGPoint(x: CGFloat(self.currentIndex) * self.collectionView.frame.size.width, y: 0), animated: false)
        }
    }
    
    
    @objc override func clickCancelBtn(){
        if let image = currentImage{
            UIDevice.copyImage(image: image)
            kSavePhotoSuccesswShared.show(atView: self.view,text: "Copy Successfully".localized,showViewBtn:false)
//            closePage()
        }
    }
    
    @objc override func clickConfirmBtn(){
        if let image = currentImage{
            PhotoManagerShared.saveImageToAlbum(image) { success, error in
                if success {
                    kSavePhotoSuccesswShared.show(atView: self.view)
//                    self.closePage()
                }else{
                    debugPrint(error)
                }
            }
        }
    }
}


extension TSSmallIconBrowseVC {
    
    func reloadUI() {
        
        //判断前后是否还有,以此来确定左右翻页按钮
        var isHiddenLeft = false
        var isHiddenRight = false
        if currentIndex == 0 {
            isHiddenLeft = true
        }else if currentIndex >= dataModelArray.count {
            isHiddenRight = true
        }else if dataModelArray.count == 1{
            isHiddenLeft = true
            isHiddenRight = true
        }
        
        leftBtn.isHidden = isHiddenLeft
        rightBtn.isHidden = isHiddenRight
    }
}

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

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

    private func resetIndexWithOffset(_ scrollView: UIScrollView) {
        let item = Int((scrollView.contentOffset.x / scrollView.bounds.width).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! TSSmallIconBrowseCell
        
//        debugPrint("collectionView cellForItemAt=\(indexPath)")
        
        if let model = dataModelArray.safeObj(At: indexPath.item){
            cell.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl){[weak self] image in
                guard let self = self else { return }
                currentImage = image
            }
        }

        return cell
    }
    
    
//    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        
//        debugPrint("collectionView didEndDisplaying=\(indexPath)")
//        
//        if let cell = cell as? TSSmallIconBrowseCell {
//            cell.stopPlayLive()
//        }
//    }
//    
//    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath){
//        
//        debugPrint("collectionView willDisplay=\(indexPath)")
//        
//        if let cell = cell as? TSSmallIconBrowseCell {
//            cell.stratPlayLive()
//        }
//    }
}
