//
//  TSRandomWallpaperBrowseVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/24.
//


private let topLineH = k_Height_statusBar()

class TSRandomWallpaperBrowseVC: TSBaseVC {

    private var isPanningDown: Bool?

    lazy var isPreview = false {
        didSet {
            self.previewView.isHidden = !isPreview
            self.btnsAllView.isHidden = isPreview
        }
    }
    
    var dataModel:TSRandomWallpaperDataItemModel
    
    init(dataModel: TSRandomWallpaperDataItemModel) {
        self.dataModel = dataModel
        super.init()
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var backBtn: UIButton = {
        return UIButton.createButton(image: UIImage(named: "navi_back_white"),backgroundColor: UIColor.fromHex("#111111", alpha: 0.2),corner: 16.0) { [weak self] in
            self?.pop()
        }
    }()
    
    
    
    //MARK: btnsAllView
    
    lazy var btnsAllView: UIView = {
        let btnsAllView = UIView()
        
        //版权信息按钮
        let copyrightBtn = UIButton.createButton(image: UIImage(named: "info_white"),backgroundColor: UIColor.fromHex("#111111", alpha: 0.2),corner: 16.0) { [weak self]  in
            guard let self = self else { return }
            navigationController?.pushViewController(TSRandomWallpaperCopyrightVC(), animated: true)
        }
        btnsAllView.addSubview(copyrightBtn)
        copyrightBtn.snp.makeConstraints { make in
            make.width.height.equalTo(44)
            make.trailing.equalTo(-16)
            make.top.equalTo(topLineH)
        }
        
        btnsAllView.addSubview(saveImagesToolView)
        saveImagesToolView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalTo(0)
            make.height.equalTo(k_Height_StatusBar+168)
        }
        
        //教程按钮
        let tutorialsBtn = UIButton.createButton(image: UIImage(named: "random_tutorials"),backgroundColor: UIColor.fromHex("#000000", alpha: 0.5),corner: 19.0) { [weak self]  in
            guard let self = self else { return }
            navigationController?.pushViewController(TSRandomWallpaperTutorialsVC(), animated: true)
        }
        btnsAllView.addSubview(tutorialsBtn)
        tutorialsBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(-20-39.0)
            make.bottom.equalTo(saveImagesToolView.snp.top).offset(-20)
            make.width.height.equalTo(58)
        }
        
        //预览按钮
        let previewBtn = UIButton.createButton(image: UIImage(named: "random_preview"),backgroundColor: UIColor.fromHex("#000000", alpha: 0.5),corner: 19.0) { [weak self]  in
            guard let self = self else { return }
            self.isPreview = !self.isPreview
        }
        btnsAllView.addSubview(previewBtn)
        previewBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(20+39.0)
            make.bottom.equalTo(saveImagesToolView.snp.top).offset(-20)
            make.width.height.equalTo(58)
        }
        
        

        return btnsAllView
    }()

    //缩略图view
    lazy var thumbnailView: TSRandomWallpaperBrowseSelectView = {
        let thumbnailView = TSRandomWallpaperBrowseSelectView()
        thumbnailView.items = dataModel.items
        thumbnailView.selectedCallBack = { [weak self] selectedArray in
            guard let self = self else { return }
            
            selecAllView.isSelected = selectedArray.count == 0 ? false : true
            selecAllView.selectNumLabel.text = "(\(selectedArray.count)/\(self.dataModel.items.count))"
            saveBtn.isEnabled = selecAllView.isSelected
        }
        return thumbnailView
    }()
    
    lazy var selecAllView: TSRandomWallpaperSelecAllView = {
        let selecAllView = TSRandomWallpaperSelecAllView()
        selecAllView.selectNumLabel.text = "(\(self.dataModel.items.count)/\(self.dataModel.items.count))"
        selecAllView.clickCallBack = { [weak self] in
            guard let self = self else { return }
            self.thumbnailView.clickSelectHandle()
            
        }
        return selecAllView
    }()
    
    
    lazy var saveBtn: UIButton = {
        let imageNamed = isShowVip() ? "vip_icon" : ""
        let saveBtn = TSViewTool.createNormalSubmitBtn(title: "Save All".localized,imageNamed: imageNamed) { [weak self]  in
            guard let self = self else { return }
            //判断 vip
            if self.dataModel.vip == true,PurchaseManager.default.isVip == false{
                TSPurchaseVC.show(target: self) {[weak self]  in
                    guard let self = self else { return }
                }
                return
            }
            
            //保存图片
            var imageUrlSting:[String] = [String]()
            
            if let indexArray = self.thumbnailView.collectionView.indexPathsForSelectedItems {
                for indexPath in indexArray {
                    if let item = self.dataModel.items.safeObj(At: indexPath.row),item.imageUrl.contains("http")  {
                        imageUrlSting.append(item.imageUrl)
                    }
                }
            }

            if imageUrlSting.count == 0 {
                return
            }
            
            TSToastShared.showLoading()
            
            let group = DispatchGroup()
            
            var images = [UIImage]()
            for urlString in imageUrlSting {
                group.enter()
                TSCommonTool.fetchImageWithCache(from: urlString) { image, error in
                    if let image = image {
                        images.append(image)
                    }
                    group.leave()
                }
            }
            
            group.notify(queue: .main) {
                PhotoManagerShared.saveImagesToUniqueAlbum(images: images, baseAlbumName: self.dataModel.type) { success, error in
                    kExecuteOnMainThread {
                        TSToastShared.hideLoading()
                        if success {
                            kSavePhotoSuccesswShared.show(atView: self.view)
                        } else {
                            TSToastShared.showToast(text: error?.localizedDescription ?? "Save Failure")
                        }
                    }
                }
            }
            
        }
        saveBtn.titleLabel?.font = UIFont.font(size: 14.0)
        saveBtn.cornerRadius = 16
        return saveBtn
    }()
    
    //整个保存 图片的工具栏
    lazy var saveImagesToolView: UIView = {
        let saveImagesToolView = UIView()
        let effctView = TSViewTool.createBlurEffectView(style: .light,backgroundColor: UIColor.fromHex("#000000", alpha: 0.6))
        saveImagesToolView.addSubview(effctView)
        effctView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        saveImagesToolView.addSubview(thumbnailView)
        thumbnailView.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.leading.trailing.equalTo(0)
            make.height.equalTo(100)
        }
        
        saveImagesToolView.addSubview(selecAllView)
        selecAllView.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.top.equalTo(thumbnailView.snp.bottom).offset(18)
        }
        

        saveImagesToolView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-16)
            make.top.equalTo(thumbnailView.snp.bottom).offset(12)
            make.width.equalTo(110)
            make.height.equalTo(32)
        }
        
        return saveImagesToolView
    }()
    
    
    
    //MARK: previewView
    lazy var previewView: UIView = {
        let previewView = UIView()
        previewView.isHidden = true
        
        let imageView = UIImageView.createImageView(imageName:"iPhone_lock_screen_preview")
        previewView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(onPreviewButton))
        previewView.addGestureRecognizer(tap)
        
        return previewView
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal // 横向滚动
        layout.itemSize = UIScreen.main.bounds.size // 每个 item 的大小
        layout.minimumLineSpacing = 0 // item 之间的间隔
        layout.minimumInteritemSpacing = 0 // item 之间的间隔
        let collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.backgroundColor = UIColor.black
        collectionView.register(TSRandomWallpaperBrowseCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView.isPagingEnabled = true
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    

    override func createView() {
        setNavBarViewHidden(true)
        view.backgroundColor = .clear
        contentView.addSubview(collectionView)
        contentView.addSubview(btnsAllView)
        contentView.addSubview(previewView)
        contentView.addSubview(backBtn)
    
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
  
        btnsAllView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        previewView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        backBtn.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.top.equalTo(topLineH)
            make.width.height.equalTo(44)
        }
 
        let pan = UIPanGestureRecognizer(target: self, action: #selector(onPanGesture(_:)))
        view.addGestureRecognizer(pan)
    }
    
    func isShowVip() -> Bool {
        return self.dataModel.vip
    }
}

//MARK: 点击操作
extension TSRandomWallpaperBrowseVC{

    @objc func onPreviewButton() {
        isPreview = !isPreview
    }
    
    @objc func onPanGesture(_ pan: UIPanGestureRecognizer)  {
        let trans = pan.translation(in: self.view)
        let velocity = pan.velocity(in: nil)
        
        switch pan.state {
        case .began:
            if abs(trans.x) > abs(trans.y) {
                isPanningDown = false
            }
            else if trans.y > 0 {
                isPanningDown = true
            }
            
        case .changed:
            
            switch isPanningDown {
            case .none:
                
                if abs(trans.x) > abs(trans.y) {
                    isPanningDown = false
                }
                else if trans.y > 0 {
                    isPanningDown = true
                }
                
            case .some(true):
                var viewTrans = self.view.transform
                viewTrans = viewTrans.translatedBy(x: 0, y: trans.y)
                if viewTrans.ty >= 0 {
                    self.view.transform = viewTrans
                }
                
            case .some(false):
                let newOffsetX = self.collectionView.contentOffset.x - trans.x
                if newOffsetX >= 0 &&
                    newOffsetX <= (self.collectionView.contentSize.width - self.collectionView.bounds.width) {
                    self.collectionView.contentOffset.x -= trans.x
                }
            }
            pan.setTranslation(.zero, in: pan.view)
        case .ended:
            
            switch isPanningDown {
            case .none:
                debugPrint("no thing to do ")
                self.view.transform = .identity
                
            case .some(true):
                if self.view.transform.ty > 80 ||
                    velocity.y >= 500 {
                    UIView.animate(withDuration: 0.2) { [weak self] in
                        self?.view.transform.ty = k_ScreenHeight
                    } completion: { [weak self] finished in
                        if finished {
                            self?.dismiss(animated: false)
                        }
                    }
                }
                else {
                    self.view.transform = .identity
                }
            case .some(false):
                
                let velocity = pan.velocity(in: pan.view)
                
                let page: CGFloat
                if velocity.x >= 500 {
                    page = (collectionView.contentOffset.x / collectionView.bounds.width).rounded(.down)
                }
                else if velocity.x <= 500 {
                    page = (collectionView.contentOffset.x / collectionView.bounds.width).rounded(.up)
                }
                else {
                    page = (collectionView.contentOffset.x / collectionView.bounds.width).rounded()
                }
                let newOffsetX = page * collectionView.bounds.width
                collectionView.setContentOffset(CGPoint(x: newOffsetX, y: 0), animated: true)
            }
            
            isPanningDown = nil
        case .cancelled, .failed:
            self.view.transform = CGAffineTransform.identity
            isPanningDown = nil           
        default:
            debugPrint(pan.state)
            debugPrint(pan.translation(in: self.view))
        }
    }
}


//MARK: UICollectionViewDataSource
extension TSRandomWallpaperBrowseVC: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())
//    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataModel.items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TSRandomWallpaperBrowseCell
        if let wallpaperModel = dataModel.items.safeObj(At: indexPath.item), wallpaperModel.imageUrl.count > 0 {
            cell.showImageView.setAsyncImage(urlString: wallpaperModel.imageUrl,placeholder: kWapppaperPlaceholderImage)
        }
        return cell
    }
}


class TSRandomWallpaperBrowseCell : TSBaseCollectionCell {
    
    private let showImageViewW = k_ScreenWidth - 32
    
    lazy var showImageView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    override func creatUI() {
        self.backgroundColor = UIColor.clear
        self.contentView.backgroundColor = UIColor.clear
        
        bgContentView.addSubview(showImageView)
        showImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}
