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

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

    
    var dataModelArray = [TSGenmojiModel]()
    var currentImage:UIImage?{
        let cell = collectionView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? TSSmallIconBrowseCell
        var image = cell?.netWorkImageView.image
        image = image?.pngImage
        return image
    }
    var currentModel:TSGenmojiModel?{
        if let model = dataModelArray.safeObj(At: currentIndex){
            return model
        }
        return nil
    }
    
    
    var currentIndex:Int = 0 {
        didSet{
            reloadUI()
        }
    }
    
    lazy var collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        collectionView.register(TSSmallIconBrowseCell.self, forCellWithReuseIdentifier: 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 JudgeVip(){
            return
        }
  
        if let image = currentImage{
            UIDevice.copyImage(image: image)
            kSavePhotoSuccesswShared.show(atView: self.view,text: "Copy Successfully".localized,showViewBtn:false)
//            closePage()
        }else{
            kShowToastDataMissing()
        }
    }
    
    @objc override func clickConfirmBtn(){
        
        if JudgeVip(){
            return
        }
        
        if let image = currentImage{
            PhotoManagerShared.saveImageToAlbum(image) { success, error in
                if success {
                    kSavePhotoSuccesswShared.show(atView: self.view)
//                    self.closePage()
                }else{
                    debugPrint(error)
                }
            }
        }else{
            kShowToastDataMissing()
        }
    }
    
    
    func JudgeVip() -> Bool {
        return kJudgeVip(externalBool: currentModel?.response.vip ?? false , vc: self, closePageBlock: nil)
    }
}


extension TSSmallIconBrowseVC {
    
    func reloadUI() {
        
        //判断前后是否还有,以此来确定左右翻页按钮
        var isHiddenLeft = false
        var isHiddenRight = false
        if dataModelArray.count == 1{
            isHiddenLeft = true
            isHiddenRight = true
        }else if currentIndex == 0 {
            isHiddenLeft = true
        }else if currentIndex+1 >= dataModelArray.count {
            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
        if let model = dataModelArray.safeObj(At: indexPath.item){
            cell.netWorkImageView.setAsyncImage(urlString: model.response.resultUrl,placeholder: kPlaceholderImage)
            cell.vipImageView.isHidden = !model.response.vip
        }
        return cell
    }
    
    
//    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        if let cell = cell as? TSSmallIconBrowseCell {
//            currentImage = cell.netWorkImageView.image
//        }
//    }
//    
//    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath){
//        
//        debugPrint("collectionView willDisplay=\(indexPath)")
//        
//        if let cell = cell as? TSSmallIconBrowseCell {
//            cell.stratPlayLive()
//        }
//    }
}
