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

import Foundation
import Photos
import SnapKit

class HomeVideoDetailController :BaseViewController {
    
    private var headerHeight : CGFloat = 98 + 90
    
    private var currentHeaderView: HomeVideoDetailCustomHeaderView?
    
    private var deleteViewBottomConstraint: Constraint?
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    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) Video", 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)
                }else{
                    self.deleteButtonView.deleteButton.setTitle("Delete \(self.selectedModel.count) Videos", 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 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(HomeVideoDetailCell.self, forCellWithReuseIdentifier: "HomeVideoDetailCell")
        sview.register(HomeVideoDetailCustomHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomeVideoDetailCustomHeaderView")
        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.tipLabel.text = "The video in the trash can"
        view.type = .video
        view.isHidden = true
        return view
    }()
    
    lazy var defaultImageView : UIImageView = {
        let defaultImageView = UIImageView()
        defaultImageView.image = UIImage(named: "img_vedio_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
    }()
    
    // MARK: 数据操作 - 主要方法
    
    /// 获取当前页面数据
    /// - Parameter completed: 完成回调
    func getCurrentPageData(completed:@escaping ()->Void){
        
        PhotoManager.shared.reloadTrashAndKeep()
        
        var data = PhotoManager.shared.filterVideoModels
        
        // 过滤掉垃圾桶数据
        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()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: 数据操作 - 辅助方法
    
    /// 过滤垃圾桶数据 - 当前页面数据本身就是已经过滤了垃圾桶数据库的数据了，所以只需要过滤掉单利中的数据
    /// - Parameter array: 当前数据
    /// - Returns: 过滤后的数据
    func filterSigtonTrashData(array : [AssetModel]) -> [AssetModel]{
        // 从单利拿数据
        let data = Singleton.shared.trashData[TrashTypeEnum.video] ?? []
        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 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
        }
        self.view.addSubview(self.defaultImageView)
        self.defaultImageView.snp.makeConstraints { make in
            make.width.height.equalTo(180)
            make.top.equalTo(262)
            make.centerX.equalToSuperview()
        }
        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()
        }
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(marginLR)
            make.top.equalTo(self.videoDetailNavView!.snp.bottom)
            make.bottom.equalToSuperview()
        }
        setDefaultPage()
        
    }
    
    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 = 1
                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()
    }
    
    /// 是否添加垃圾桶数据
    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)
            }
            // 判断垃圾桶有没有数据
            let array = TrashDataManager.getCurrentMediaTypeTrashData(mediaType:TrashTypeEnum.video)
            self.trashSubView.resourceCountlabel.text = String(array.count)
            self.trashSubView.isHidden = array.count <= 0
            self.deleteButtonView.isHidden = array.count > 0
            self.videoDetailNavView?.startSelectButton.isHidden = array.count > 0 || self.resourceData.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)
//            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 重新设置下数据源
        self.getCurrentPageData {
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
            self.setDefaultPage()
        }
    }
    
    func showTipsVC(){
        
        guard TipsManager.getLoadStauts(.videos) == false else{
            return
        }
        let vc = TipsVideoPhotoController()
        vc.type = .video
        vc.modalPresentationStyle = .fullScreen
        self.present(vc, animated: true)
        
        TipsManager.saveLoadStatus(.videos)
    }
}


extension HomeVideoDetailController: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: "HomeVideoDetailCell", for: indexPath) as! HomeVideoDetailCell
        
        cell.resourceIdent = self.resourceData[indexPath.row]
        cell.currentOrder = indexPath.row
//        cell.backImageView.image = nil
        if self.selectedModel.contains(where: { $0.localIdentifier == cell.resourceIdent!.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.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 }
            }
        }
        cell.cellCallBack = {[weak self] ident,order in
            guard let self else {return}
            
            // 获取视频的图片
            PhotoManager.shared.getVideoImageByIdent(ident: ident) { image in
                // 点击之后跳转详情页面
                if self.videoDetailNavView?.startSelectButton.isSelected == false {
                    let vc = PhotoRemoveViewController(data: self.resourceData,currentIndex: indexPath.row,mediaType: .video)
                    self.navigationController?.pushViewController(vc, animated: true)
                }else {
                    let vc = PMShowImgVideoController()
                    vc.oldPageIndexPath = indexPath
                    vc.state = .similarVideos
                    vc.currentIdx = 0
                    let dataSource = ImageSeletedCollectionItem()
                    dataSource.isSeleted = cell.choose
                    dataSource.id = ident
                    dataSource.image = image
                    // 表示这个是视频
                    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
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    vc.getVideoURLFromLocalIdentifier(localIdentifier: ident.localIdentifier) { url, error in
                        if url != nil{
                            DispatchQueue.main.async {
                                vc.url = url
                                self.navigationController?.pushViewController(vc, animated: true)
                            }
                        }else{
                            let alert = UIAlertController(title: nil, message: "ICloud video cannot be viewed", preferredStyle: .alert)
                            self.present(alert, animated: true, completion: nil)
                            
                            // 2 秒后关闭弹窗
                            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                                alert.dismiss(animated: true, completion: nil)
                            }
                        }
                    }
                }
               
            } errorHandler: {
                DispatchQueue.main.async {
                    let alert = UIAlertController(title: nil, message: "Get Video image failure", preferredStyle: .alert)
                    self.navigationController?.present(alert, animated: true)
                    
                    // 1秒之后消失
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        alert.dismiss(animated: true, completion: nil)
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
            
        }
        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: "HomeVideoDetailCustomHeaderView", for: indexPath) as! HomeVideoDetailCustomHeaderView
            // 记录当前的 headerView
            currentHeaderView = header
            header.compressionTipView.reloadData()
            header.sizeLabel.attributedText = header.getAttrText(fullText: "\(self.resourceData.count) Videos")
            header.sizeLabel.isHidden = (self.resourceData.count <= 0)
            header.filterButton.isHidden = (self.resourceData.count <= 0)
            header.compressionTipView.isHidden = (PhotoManager.shared.permissionStatus != .authorized)
            header.sortViewSubmitCallBack = {[weak self] filterModel in
                guard let self else {return}
                PhotoManager.shared.reloadTrashAndKeep()
                let dataS : [AssetModel] = PhotoManager.shared.filterVideoModels
                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 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
    }
    
    
    // 显示弹出框
    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: .videos)
                        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: .videos)
                                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: .videos)
                                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: .videos)
                                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 = {[weak self] isMore,deleteCount in
                guard let self = self else { return }
                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.deleteAction(count: deleteCount,isAfterAdv: true)
                        } showFailBlock: { _ 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 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 popAdverTisement(){
       // AdvManager.shared.showRewardedInterstitialAd(vc: self,from: "video_delete")
    }
    
    func deleteAction(count:Int,isAfterAdv:Bool){
        let tempArray = Array(self.selectedModel.prefix(count))
        self.selectedModel = tempArray
        // 删除当前选择
        let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: self.selectedModel.map{$0.localIdentifier}, options: nil)
        let fileSize = FileTool().calculateTotalAssetSize(fetchResult: fetchResult)
        PMLoadingHUD.share.show()
        
        CATransaction.begin()
        CATransaction.setCompletionBlock {
            PHPhotoLibrary.shared().performChanges ({
                PHAssetChangeRequest.deleteAssets(fetchResult as NSFastEnumeration)
            }){ success, error in
                if(success){
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                        PMLoadingHUD.share.disMiss()
                        print("删除文件成功")
                        
                        if isAfterAdv == false {
                            self.updateFreeTimes()
                            
                        }
                        self.showDeleteSuccess(fileCount: self.selectedModel.count, fileSize: fileSize)
                        // 移除当前总数据源的数据
                        self.updateCurrentPageWhenDeleteAny()
                    }
                }else {
                    PMLoadingHUD.share.disMiss()
                    if let error = error {
                        print("删除文件时出错: \(error.localizedDescription)")
                    }
                }
            }
        }
        CATransaction.commit()
        
    }
    
    // 删除成功页面
    func showDeleteSuccess(fileCount:Int,fileSize:Int64){
        DispatchQueue.main.async {
            let vc = DelSuccessViewController()
            vc.delType = fileCount > 1 ? "videos" : "video"
            vc.fileSzie = fileSize
            vc.fileCount = fileCount
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
            vc.closeCall = { [weak self] in
                guard let self = self else { return  }
                // 如果是看广告删除的，且还有免费次数
                SystemCommentManager.showCommentPage(self.view)
            }
        }
    }
    
    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.deleteButton.isHidden = true
                }else{
                    self.defaultImageView.isHidden = true
                    self.defaultTipLabel.isHidden = true
                    self.currentHeaderView?.filterButton.isHidden = false
                    self.videoDetailNavView?.startSelectButton.isHidden = false
                    self.deleteButtonView.deleteButton.isHidden = false
                }
            }
            self.addTrashView()
            
        }
    }
    
    func updateCurrentPageWhenDeleteAny(){
        
        for item in self.selectedModel {
            // 移除当前数据
            self.resourceData.removeAll{ $0.localIdentifier == item.localIdentifier }
        }
        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)
            
            if self.currentHeaderView != nil {
                self.currentHeaderView?.sizeLabel.attributedText = self.currentHeaderView?.getAttrText(fullText: "\(self.resourceData.count) Videos")
            }
            
            UIView.transition(with: self.collectionView, duration: 0.3, options: .transitionCrossDissolve, animations: {
                self.collectionView.reloadData()
            }, completion: nil)
        }
        
        setDefaultPage()
    }
    
    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
        }
    }
    
    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)
            }
        }
    }
    
}
