//
//  PhotosDetailViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/9.
//

import Foundation
import Photos
import SnapKit

class HomePhotosDetailViewController : BaseViewController {
    private var headerHeight : CGFloat = 98
    
    private var deletedPhotos : PHFetchResult<PHAsset>?
    
    private var currentHeaderView: HomePhotosDetailCustomHeaderView?
    
    
    private var deleteViewBottomConstraint: Constraint?
    
    var mediaType : PhotsFileType? {
        didSet {
            if mediaType == PhotsFileType.videos {
                self.trashSubView.tipLabel.text = "The video in the trash can"
            }else {
                self.trashSubView.tipLabel.text = "The photo in the trash can"
            }
        }
    }
    
    var imageCache = NSCache<NSString, UIImage>()
    
    
    private var videoDetailNavView:VideoDetaiNavView?
    
    var resourceData : [AssetModel] = []
    
    // 排序
    var currentSort : ResouceSortType = .latest
    
    // 当前页面选中的
    var selectedModel : [AssetModel] = [] {
        didSet{
            DispatchQueue.main.async {
                if self.selectedModel.count == 0{
                    self.deleteButtonView.deleteButton.setTitle("Delete", for: .normal)
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.deleteViewBottomConstraint?.update(offset: safeHeight + 78)
                    }
//                    self.collectionView.frame = CGRect(x: marginLR, y: self.videoDetailNavView!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.videoDetailNavView!.height)
                }else if self.selectedModel.count == 1{
                    self.deleteButtonView.deleteButton.setTitle("Delete \(self.selectedModel.count) Photo", for: .normal)
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.deleteViewBottomConstraint?.update(offset: 0)
                    }
//                    self.collectionView.frame = CGRect(x: marginLR, y: self.videoDetailNavView!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.videoDetailNavView!.height - 78 - safeHeight)
                }else{
                    self.deleteButtonView.deleteButton.setTitle("Delete \(self.selectedModel.count) Photos", for: .normal)
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.deleteViewBottomConstraint?.update(offset: 0)
                    }
//                    self.collectionView.frame = CGRect(x: marginLR, y: self.videoDetailNavView!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.videoDetailNavView!.height - 78 - safeHeight)
                }
                
                
                if self.selectedModel.count > 0 {
                    self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
                }else{
                    self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
                    self.deleteButtonView.deleteButton.setTitle("Delete", for: .normal)
                }
            }
        }
    }
    
    
    
    lazy var defaultImageView : UIImageView = {
        let defaultImageView = UIImageView()
        defaultImageView.image = UIImage(named: "img_photo__home_defpage")
        defaultImageView.isHidden = true
        return defaultImageView
    }()
    lazy var defaultTipLabel : UILabel = {
        let label = UILabel()
        label.text = "There are no new files to process"
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        label.textAlignment = .center
        label.isHidden = true
        return label
    }()
    
    
    lazy var collectionView:UICollectionView = {
        
        let layout = WaterfallMutiSectionFlowLayout()
        layout.delegate = self
        let sview:UICollectionView = UICollectionView.init(frame: CGRect(x: marginLR, y: self.videoDetailNavView!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.videoDetailNavView!.height - safeHeight),  collectionViewLayout: layout)
        
        sview.register(HomePhotosDetailCollectionCell.self, forCellWithReuseIdentifier: "HomePhotosDetailCollectionCell")
        sview.register(HomePhotosDetailCustomHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomePhotosDetailCustomHeaderView")
        sview.register( UICollectionReusableView.self,forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,withReuseIdentifier: "footerID")
        
        sview.dataSource = self
        sview.delegate = self
        sview.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            sview.contentInsetAdjustmentBehavior = .never
        }
        sview.backgroundColor = .clear
        return sview
        
    }()
    
    lazy var deleteButtonView : HomeDetailDeleteView = {
        let view = HomeDetailDeleteView()
        view.addTopShadow()
        return view
    }()
    
    
    lazy var trashSubView : TrashSubView = {
        let view = TrashSubView()
        view.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
        view.isHidden = true
        return view
    }()
    
    
    func setUI(){
        
        videoDetailNavView = VideoDetaiNavView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: statusBarHeight + 44))
        self.view.addSubview(videoDetailNavView!)
        
        
        videoDetailNavView?.snp.makeConstraints({ make in
            make.top.centerX.width.equalToSuperview()
            make.height.equalTo(statusBarHeight + 44)
        })
        
        self.videoDetailNavView?.selectAllCallBack = {[weak self] choose in
            
            guard let self  else {return}
            if choose == true {
                self.selectedModel = self.resourceData
            }else{
                self.selectedModel.removeAll()
            }
            DispatchQueue.main.async {
                
                UIView.transition(with: self.collectionView, duration: 0.3, options: .transitionCrossDissolve, animations: {
                    self.collectionView.reloadData()
                }, completion: nil)
                
                if self.selectedModel.count > 0 {
                    self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
                    
                }else{
                    self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
                    self.deleteButtonView.deleteButton.setTitle("Delete", for: .normal)
                }
            }
            
        }
        self.videoDetailNavView?.startSelectCallBack = {[weak self] choose in
            guard let self  else {return}
//            if !choose {
                
//            }
            DispatchQueue.main.async {
                self.selectedModel.removeAll()
                UIView.transition(with: self.collectionView, duration: 0.3, options: .transitionCrossDissolve, animations: {
                    self.collectionView.reloadData()
                }, completion: nil)
                
                if self.selectedModel.count > 0 {
                    self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
                    
                }else{
                    self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
                    self.deleteButtonView.deleteButton.setTitle("Delete", for: .normal)
                }
            }
        }
        
        
        
        self.view.insertSubview(collectionView, at: 0)
        
        self.view.addSubview(self.deleteButtonView)
        self.deleteButtonView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(78 + safeHeight)
            self.deleteViewBottomConstraint = make.bottom.equalToSuperview().offset(safeHeight + 78).constraint
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(marginLR)
            make.top.equalTo(self.videoDetailNavView!.snp.bottom)
            make.bottom.equalToSuperview()
        }
        
        self.view.addSubview(self.defaultImageView)
        self.defaultImageView.snp.makeConstraints { make in
            make.width.height.equalTo(180)
            make.top.equalTo(262)
            make.centerX.equalToSuperview()
        }
        self.view.addSubview(self.defaultTipLabel)
        self.defaultTipLabel.snp.makeConstraints { make in
            make.width.equalToSuperview()
            make.height.equalTo(28)
            make.top.equalTo(self.defaultImageView.snp.bottom).offset(-30)
            make.centerX.equalToSuperview()
        }
        self.setDefaultPage()
    }
    
    
    /// 是否添加垃圾桶数据
    func addTrashView(){
        DispatchQueue.main.async {
            self.trashSubView.removeFromSuperview()
            self.view.addSubview(self.trashSubView)
            self.trashSubView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview().offset(0)
                make.height.equalTo(78 + safeHeight)
            }
            self.trashSubView.type = self.mediaType == PhotsFileType.Other ? TrashTypeEnum.other : TrashTypeEnum.shot
            // 判断垃圾桶有没有数据
            let array = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: self.mediaType == PhotsFileType.Other ? TrashTypeEnum.other : TrashTypeEnum.shot)
            self.trashSubView.resourceCountlabel.text = String(array.count)
            self.trashSubView.isHidden = array.count <= 0
            self.videoDetailNavView?.startSelectButton.isHidden = array.count > 0 || self.resourceData.count <= 0
            self.deleteButtonView.isHidden = array.count > 0
            
            // 改变collection的位置

//            if array.count > 0 {
//                self.collectionView.frame = CGRect(x: marginLR, y: self.videoDetailNavView!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.videoDetailNavView!.height - 78 - safeHeight)
//            }else{
//                self.collectionView.frame = CGRect(x: marginLR, y: self.videoDetailNavView!.height, width: self.view.width - 2 * marginLR, height: self.view.height - self.videoDetailNavView!.height)
//            }
            self.videoDetailNavView?.startSelectButton.isHidden = (self.resourceData.count <= 0)
            
        }
    }
    
    
    //设置空白页
    func setDefaultPage(){
        DispatchQueue.main.async {
            if PhotoManager.shared.permissionStatus == .denied{
                self.loadPermissView()
            }else{
                if self.resourceData.count == 0 {
                    self.defaultImageView.isHidden = false
                    self.defaultTipLabel.isHidden = false
                    self.currentHeaderView?.filterButton.isHidden = true
                    self.videoDetailNavView?.startSelectButton.isHidden = true
                    self.deleteButtonView.isHidden = true
                }else{
                    self.defaultImageView.isHidden = true
                    self.defaultTipLabel.isHidden = true
                    self.currentHeaderView?.filterButton.isHidden = false
                    self.videoDetailNavView?.startSelectButton.isHidden = false
                    self.deleteButtonView.isHidden = false
                }
            }
            self.addTrashView()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        self.navigationController?.navigationBar.isHidden = true
        // 添加垃圾桶功能
        
        setUI()
        showTipsVC()
        
        
        
        self.deleteButtonView.deleteCallBack = {
            self.deleteButtonAction()
        }
        
        self.trashSubView.presentTashDetailViewClickCallBack = {[weak self] in
            guard let self else {return}
            // 进入垃圾桶详情页面
            DispatchQueue.main.async {
                let vc : TrashViewController = TrashViewController()
                vc.currentPage = self.mediaType == PhotsFileType.Other ? 2 : 3
                vc.dissmisCallBack = {
                    self.getCurrentPageData {
                        self.collectionView.reloadData()
                    }
                    self.addTrashView()
                    self.setDefaultPage()
                }
                self.present(vc, animated: true)
            }
        }
        self.trashSubView.clearTashDataCallBack = {[weak self] in
            guard let self else {return}
            DispatchQueue.main.async {
                self.addTrashView()
            }
           
        }
        
        self.addListener()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    func showTipsVC(){
        
        guard let mediaType = mediaType else{
            return
        }
        
        guard TipsManager.getLoadStauts(mediaType) == false else{
            return
        }
        if mediaType == .screenshots{
            let vc = TipsScreenShotController()
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }else{
            let vc = TipsVideoPhotoController()
            vc.type = .photo
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }
        
        TipsManager.saveLoadStatus(mediaType)
        
    }
    
    // MARK:系统方法
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required init(mediaType: PhotsFileType) {
        self.mediaType = mediaType
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 重新设置下数据源
        self.getCurrentPageData {
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
            self.setDefaultPage()
        }
    }
    
    
    
    // MARK: 数据操作 - 主要方法
    
    /// 获取当前页面数据
    /// - Parameter completed: 完成回调
    func getCurrentPageData(completed:@escaping ()->Void){
        
        PhotoManager.shared.reloadTrashAndKeep()
        
        var data = self.mediaType == .Other ? PhotoManager.shared.filterOtherModels : PhotoManager.shared.filterScreenShotModels
        
        // 过滤掉垃圾桶数据
        data = self.filterSigtonTrashData(array: data)
        self.selectedModel = self.filterSigtonTrashData(array: self.selectedModel)
        
        // 过滤掉保留列表数据
        data = self.filterKeepListData(array: data)
        self.selectedModel = self.filterKeepListData(array: self.selectedModel)
        
        self.resourceData = data
        self.sortByType(sortType: self.currentSort)
        completed()
    }
    
    
    // MARK: 数据操作 - 辅助方法
    
    /// 过滤垃圾桶数据 - 当前页面数据本身就是已经过滤了垃圾桶数据库的数据了，所以只需要过滤掉单利中的数据
    /// - Parameter array: 当前数据
    /// - Returns: 过滤后的数据
    func filterSigtonTrashData(array : [AssetModel]) -> [AssetModel]{
        let type = self.mediaType == PhotsFileType.Other ? TrashTypeEnum.other : TrashTypeEnum.shot
        // 从单利拿数据
        let data : [AssetModel] = Singleton.shared.trashData[type] ?? []
        return array.filter({!data.map({$0.localIdentifier}).contains($0.localIdentifier)})
    }
    
    
    /// 过滤保留列表数据
    /// - Parameter array: 原数据
    /// - Returns: 过滤后的数据
    func filterKeepListData(array : [AssetModel]) -> [AssetModel]{
        let data = KeepListManager.getAllKeepListData()
        if data.count > 0 {
            return array.filter({!data.map({$0.localIdentifier}).contains($0.localIdentifier)})
        }
        return array
    }
    
    
    
    
    func getImageFromCache(model: AssetModel,completed:@escaping (UIImage)->Void){
        let cachedImage = self.imageCache.object(forKey: model.localIdentifier as NSString)
        if cachedImage != nil {
            completed(cachedImage!)
        }
        
        
        let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [model.localIdentifier], options: nil)
        let assetsArray = fetchResult.objects(at: IndexSet(0..<fetchResult.count))
        let options = PHImageRequestOptions()
        options.isNetworkAccessAllowed = true
        options.isSynchronous = false
        if let first = assetsArray.first{
            PHImageManager.default().requestImage(for: first, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: options) { (image, info) in
                completed(image ?? UIImage())
            }
        }
    }
}




extension HomePhotosDetailViewController:WaterfallMutiSectionDelegate,UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.resourceData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomePhotosDetailCollectionCell", for: indexPath) as! HomePhotosDetailCollectionCell
        cell.resourceIdent = self.resourceData[indexPath.row]
        cell.saveSizeView.isHidden = mediaType != .Other
        
        // 这里做缓存
        cell.backImageView.image = UIImage()
        self.getImageFromCache(model: self.resourceData[indexPath.row]) {[weak self] image in
            guard self != nil else {return}
            DispatchQueue.main.async {
                cell.backImageView.image = image
            }
        }
        cell.currentOrder = indexPath.row
        if self.selectedModel.contains(where: { $0.localIdentifier == self.resourceData[indexPath.row].localIdentifier }) {
            cell.choose = true
        }else{
            cell.choose = false
        }
        if let view = self.videoDetailNavView {
            cell.selectImageView.isHidden = !view.startSelectButton.isSelected
            cell.extensionView.isHidden = !view.startSelectButton.isSelected
        }
        
        cell.cellCallBack = {[weak self] ident,order in
            guard let self else {return}
            DispatchQueue.main.async {
                // 这里还需要判断下当前cell 是不是被选中了，选中了就不跳转左滑右滑动页面
                if self.videoDetailNavView?.startSelectButton.isSelected == false {
                    // 点击之后跳转详情页面
                    if self.mediaType == .screenshots {
                        let vc = PhotoRemoveViewController(data: self.resourceData,currentIndex: indexPath.row,mediaType: .shot)
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                    if self.mediaType == .Other {
                        let vc = PhotoRemoveViewController(data: self.resourceData,currentIndex: indexPath.row,mediaType: .other)
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else {
                    // 跳转PMSHow页面
                    // 点击之后跳转详情页面
                    let vc = PMShowImgVideoController()
                    vc.state = .similarPhotos
                    vc.currentIdx = 0
                    vc.oldPageIndexPath = indexPath
                    let dataSource = ImageSeletedCollectionItem()
                    dataSource.isSeleted = cell.choose
                    dataSource.id = ident
                    // 获取image
                    dataSource.image = PhotoManager.shared.getImageFromAssetID(id: ident.localIdentifier)
                    vc.homeDataSource = [dataSource]
                    
                    vc.backOrgPageCallBack = {index,data in
                        if let data = data{
                            if let item = data.first{
                                if let selected =  item.isSeleted {
                                    if let index = index {
                                        if selected == true {
                                            self.selectedModel.append(self.resourceData[index.row])
                                        }else {
                                            self.selectedModel.removeAll(where: {$0.localIdentifier == self.resourceData[index.row].localIdentifier})
                                        }
                                        DispatchQueue.main.async {
                                            if let tempCell = collectionView.cellForItem(at: index) as? HomePhotosDetailCollectionCell {
                                                tempCell.choose = selected
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
            }
        }
        cell.clickCallBack = {[weak self] click,order in
            guard let self else {return}
            if click == true {
                self.selectedModel.append(self.resourceData[order])
            }else{
                self.selectedModel.removeAll { $0.localIdentifier == self.resourceData[order].localIdentifier }
            }
            self.vibrate()
        }
        return cell
        
    }
    
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        return itemWidth
    }
    
    func columnNumber(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> Int {
        
        return 2
    }
    
    func lineSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 8
    }
    
    func interitemSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 11
    }
    func spacingWithLastSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 点击之后跳转详情页面
        
        
    }
    func referenceSizeForHeader(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSize (width: self.collectionView.width, height: headerHeight)
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HomePhotosDetailCustomHeaderView", for: indexPath) as! HomePhotosDetailCustomHeaderView
            // 记录当前的 headerView
            header.countLabel.attributedText = header.getAttrText(fullText: "\(self.resourceData.count) Photos")
            header.modelTitlelabel.text = self.mediaType?.rawValue
            currentHeaderView = header
            header.filterButton.isHidden = (self.resourceData.count <= 0)
            header.countLabel.isHidden = (self.resourceData.count <= 0)
            header.sortViewSubmitCallBack = {[weak self] filterModel in
                guard let self else {return}
                PhotoManager.shared.reloadTrashAndKeep()
                var dataS : [AssetModel] = []
                if self.mediaType == .Other{
                    dataS = PhotoManager.shared.filterOtherModels
                }else {
                    dataS = PhotoManager.shared.filterScreenShotModels
                }
                let tempData =  self.filterDataByDate(orgModels: dataS  , startDate: filterModel.startDate, endDate: filterModel.endDate)
                // 重新更新下数据源
                self.resourceData = tempData
                self.sortByType(sortType: filterModel.sortType)
                self.currentSort = filterModel.sortType
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            }
            
            return header
        }else{
            let footer = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: "footerID",
                for: indexPath
            )
            
            return footer
        }
    }
    
    func referenceSizeForFooter(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSizeMake(ScreenW, 90)
    }
    
    func filterDataByDate(orgModels : [AssetModel], startDate:Date? ,endDate : Date?)->[AssetModel]{
        var array = orgModels
        if startDate != nil {
            array = array.filter({$0.createDate >= startDate!})
        }
        if endDate != nil {
            array = array.filter({$0.createDate <= endDate!})
        }
        return array
    }
    
    /// 对当前页面资源排序（注意这里获取的资源是image）
    /// - Parameter sortType: 排序类型
    func sortByType(sortType:ResouceSortType){
        switch sortType {
        case .largest:
            self.resourceData = self.resourceData.sorted { $0.assetSize > $1.assetSize }
            break
        case .smallest:
            self.resourceData = self.resourceData.sorted { $0.assetSize < $1.assetSize }
            break
        case .latest:
            self.resourceData = self.resourceData.sorted { $0.createDate > $1.createDate }
            break
        case .oldest:
            self.resourceData = self.resourceData.sorted { $0.createDate < $1.createDate }
            break
        }
    }
    
    // 显示弹出框
    func showPopView(popView: AdvTipDeleteView){
        self.view.showBlur()
        self.view.addSubview(popView)
    }
    
    
    func deleteButtonAction(){
        if selectedModel.count <= 0 {
            return
        }
        
        // 首先看是否订阅
        if IAPManager.share.isSubscribed == false {
            // 没有订阅
            let view : AdvTipDeleteView = AdvTipDeleteView(frame: self.view.bounds)
            view.dataSource = self.selectedModel
            
            // 获取当前免费次数
            let freeCount = ADManager.shared.defaultFreeTimes
            // 当免费次数用完以后，无论删除多少都需要弹出广告
            if freeCount <= 0 {
                HomePayViewController.show {
                    if IAPManager.share.isSubscribed == false{
                        // 弹出单个删除类型
                        view.deleteType = .deletePhotoOne
                        view.getOtherInfoByType(type: .Other)
                        self.showPopView(popView: view)
                    }else {
                        self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
                    }
                }
            }else {
                // 获取次数对应的删除照片数量
                var freeDeleteCount = ADManager.shared.advDeleteResouceDic[freeCount]!
                let tempArray = self.selectedModel
                if freeCount > 1 {
                    // 如果是前两次，可以免费删除5张照片
                    if tempArray.count > freeDeleteCount {
                        // 弹出多个删除类型
                        HomePayViewController.show {
                            if IAPManager.share.isSubscribed == false{
                                view.deleteType = .deletePhotosMore
                                view.freeDeleteCount = freeDeleteCount
                                view.getOtherInfoByType(type: .Other)
                                self.showPopView(popView: view)
                            }else {
                                self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
                            }
                        }
                    }else {
                        // 如果小于直接删除
                        HomePayViewController.show {
                            self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
                        }
                    }
                    
                }else{
                    // 如果免费次数等于1，也就是第三次。看照片删除的数量
                    // 如果当前删除的照片大于5
                    if tempArray.count > 5 {
                        freeDeleteCount = 5
                        // 弹出多个删除类型
                        HomePayViewController.show {
                            if IAPManager.share.isSubscribed == false{
                                view.deleteType = .deletePhotosMore
                                view.freeDeleteCount = freeDeleteCount
                                view.getOtherInfoByType(type: .Other)
                                self.showPopView(popView: view)
                            }else{
                                self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
                            }
                        }
                    }else if tempArray.count > 1 && tempArray.count <= 5  {
                        // 如果是1张到5张之间，那么免费的张数是当前张数减一
                        freeDeleteCount = tempArray.count - 1
                        // 弹出多个删除类型
                        HomePayViewController.show {
                            if IAPManager.share.isSubscribed == false{
                                view.deleteType = .deletePhotosMore
                                view.freeDeleteCount = freeDeleteCount
                                view.getOtherInfoByType(type: .Other)
                                self.showPopView(popView: view)
                            }else{
                                self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
                            }
                        }
                    }else{
                        // 如果只是一张，直接删除
                        HomePayViewController.show {
                            self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
                        }
                    }
                }
            }
            view.deleteButtonClickCallback = {isMore,deleteCount in
                self.view.hideBlur()
                if deleteCount < 0 {
                    return
                }
                if isMore == true {
                    if IAPManager.share.isSubscribed == false {
//                        self.popAdverTisement()
//                        // 广告看完再结束
//                        AdvManager.shared.finisedCallBack = {
//                            self.deleteAction(count: deleteCount,isAfterAdv: true)
//                        }
                        ADManager.shared.showRewardedInterstitialAd(from: self.mediaType?.rawValue ?? "") {
                            self.deleteAction(count: deleteCount,isAfterAdv: true)
                        } showFailBlock: { error in
                            
                        }
                    }else{
                        self.deleteAction(count: deleteCount,isAfterAdv: true)
                    }
                } else {
                    self.deleteAction(count: deleteCount,isAfterAdv: false)
                }
            }
        }else{
            self.deleteAction(count: self.selectedModel.count,isAfterAdv: false)
        }
        
        
        
    }
    
    /// 弹出广告
    func popAdverTisement(){
       // AdvManager.shared.showRewardedInterstitialAd(vc: self,from:self.mediaType?.rawValue ?? ""
    }
    func deleteAction(count:Int,isAfterAdv:Bool){
        
        // 删除当前选择
        let tempArray = Array(self.selectedModel.prefix(count))
        self.selectedModel = tempArray
        let allIdent = self.selectedModel.map{ $0.localIdentifier }
        let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: allIdent, options: nil)
        let fileSize = FileTool().calculateTotalAssetSize(fetchResult: fetchResult)
        PMLoadingHUD.share.show()
        PHPhotoLibrary.shared().performChanges ({
            PHAssetChangeRequest.deleteAssets(fetchResult as NSFastEnumeration)
        }){ success, error in
            
            if(success){
                print("删除文件成功")
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    PMLoadingHUD.share.disMiss()
                    
                    if isAfterAdv == false {
                        self.updateFreeTimes()
                    }
                    self.showDeleteSuccess(fileCount: allIdent.count, fileSize: fileSize)
                    self.updateCurrentPageWhenDeleteAny()
                }
                
            }else {
                PMLoadingHUD.share.disMiss()
                if let error = error {
                    print("删除文件时出错: \(error.localizedDescription)")
                }
            }
            
            
        }
    }
    
    func updateFreeTimes(){
        // 删除成功后更新次数
        if var times =  UserDefaults.standard.object(forKey: "saveAdvTimes") as? Int{
            if times > 0 {
                // 如果免费次数大于0
                times = times - 1
                UserDefaults.standard.set(times, forKey: "saveAdvTimes")
            }
        }
    }
    
    // 删除成功页面
    func showDeleteSuccess(fileCount:Int,fileSize:Int64){
        DispatchQueue.main.async {
            let vc = DelSuccessViewController()
            vc.delType = fileCount > 1 ? "photos" : "photo"
            vc.fileSzie = fileSize
            vc.fileCount = fileCount
            vc.modalPresentationStyle = .fullScreen
            vc.closeCall = { [weak self] in
                guard let self = self else { return }
                SystemCommentManager.showCommentPage(self.view)
            }
            self.present(vc, animated: true)
        }
    }
    
    func updateCurrentPageWhenDeleteAny(){
        for item in self.selectedModel {
            // 移除当前数据
            self.resourceData.removeAll{ $0.localIdentifier == item.localIdentifier }
            
        }
        // 更新下头部数量
        DispatchQueue.main.async {
            if self.currentHeaderView != nil {
                self.currentHeaderView?.countLabel.attributedText = self.currentHeaderView?.getAttrText(fullText: "\(self.resourceData.count) Photos")
            }
        }
        
        // 清理下缓存数据
        // PhotoDataManager.manager.removeDataWhenDeleteInPage(data: self.selectedModel)
        PhotoManager.shared.removeDataWhenDeleteInPage(data: self.selectedModel) {
            //删除完成刷新数据
        }
        // 更新页面
        DispatchQueue.main.async {
            // 删除完成之后，移除下当前选择的数据
            self.selectedModel.removeAll()
            self.deleteButtonView.deleteButton.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
            self.deleteButtonView.deleteButton.setTitle("Delete", for: .normal)
            
            UIView.transition(with: self.collectionView, duration: 0.3, options: .transitionCrossDissolve, animations: {
                self.collectionView.reloadSections(IndexSet(integer: 0))
            }, completion: nil)
        }
        setDefaultPage()
        
    }
    
    
    private func addListener(){
        NotificationCenter.default.addObserver(forName: TrashDefaultView.jumpToPhotosDetailPageName, object: nil, queue: .main) {  [weak self] notification in
            guard let self = self,
            let type = notification.userInfo?["type"] as? String else { return }
            if let targetVC = self.navigationController?.viewControllers.first(where: { $0 is HomeViewController }) as? HomeViewController {
                self.navigationController?.popToViewController(targetVC, animated: false)
                let vc:HomePhotosDetailViewController = HomePhotosDetailViewController(mediaType: type == "Other" ? PhotsFileType.Other : PhotsFileType.screenshots)
                targetVC.navigationController?.pushViewController(vc, animated: true)
            }
        }
        NotificationCenter.default.addObserver(forName: TrashDefaultView.jumpToVideosDetailPageName, object: nil, queue: .main) { [weak self] notification in
            guard let self else {return}
            if let targetVC = self.navigationController?.viewControllers.first(where: { $0 is HomeViewController }) as? HomeViewController {
                self.navigationController?.popToViewController(targetVC, animated: false)
                let vc:HomeVideoDetailController = HomeVideoDetailController()
                targetVC.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    
    
}
