//
//  TrashViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/11.
//

import UIKit

class TrashViewController: BaseViewController {
    
    var dissmisCallBack:()->Void = {}

    
    var source:[TrashTypeEnum] = [.video,.other,.shot]
    var contentH:CGFloat = 0
    var contentScrollView:UIScrollView!
    lazy var delBtn : UIButton = {
        let button = UIButton()
        button.setTitle("Delete", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        button.setImage(UIImage(named: "pm-home-Frame-del"), for: .normal)
        button.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        button.layer.cornerRadius = 20
        button.addTarget(self, action: #selector(delBtnAction), for: .touchUpInside)
        return button
    }()
    
    var currentType:TrashTypeEnum = .other
    let pageCount = 3 // 总页数
    var currentPage = 1 {
        didSet{
            self.setDelButtonUI()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
        getTrashDataAndRefreshPage()
        setContentOffSet()
    }
    
    
    /// 获取垃圾桶数据
    private func getTrashDataAndRefreshPage(){
        for item in self.source {
            let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: item)
            for view in self.contentScrollView.subviews {
                if view.isKind(of: TrashContenView.self){
                    let tempView = view as! TrashContenView
                    if tempView.trashType == item{
                        tempView.mediaType = item
                        tempView.dataSource = data
                    }
                }
            }
        }
        // 将所有数据获取完成之后，重新刷新下删除按钮
        setDelButtonUI()
       
    }
    
    // 在第一次进去的时候执行一次
    private func setContentOffSet(){
        self.contentScrollView.contentOffset = CGPointMake(ScreenW * CGFloat(self.currentPage - 1), 0)
    }
    
    
    func configUI(){
        view.backgroundColor = .white
        contentScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: contentH))
        contentScrollView.contentSize = CGSize(width: ScreenW * CGFloat(self.source.count), height: view.height)
        contentScrollView.isPagingEnabled = true
        contentScrollView.showsHorizontalScrollIndicator = false
        contentScrollView.showsVerticalScrollIndicator = false
        contentScrollView.bounces = false
        contentScrollView.delegate = self
        contentScrollView.backgroundColor = UIColor.white
        view.addSubview(contentScrollView)
        
        
        view.addSubview(self.delBtn)
        
        self.delBtn.snp.makeConstraints { make in
            make.bottom.equalTo(-17)
            make.left.right.equalToSuperview().inset(55)
            make.height.equalTo(40)
        }
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage.init(named: "icon_close_bottom"), for: .normal)
        view.addSubview(closeBtn)
        
        closeBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(12)
            make.size.equalTo(18)
        }
        
        contentScrollView.addSubview(videoView)
        contentScrollView.addSubview(otherView)
        contentScrollView.addSubview(shotView)
        
    
        videoView.deleteButton = self.delBtn
        otherView.deleteButton = self.delBtn
        shotView.deleteButton = self.delBtn
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        let viewWidth = self.view.bounds.width
        let viewHeight = self.view.bounds.height
        contentH = viewHeight - 108
        contentScrollView.frame = CGRect(x: 0, y: 34, width: viewWidth, height: contentH)
        contentScrollView.contentSize = CGSize(width: viewWidth * CGFloat(self.source.count), height: contentH)
        videoView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: contentH)
        otherView.frame = CGRect(x: viewWidth, y: 0, width: viewWidth, height: contentH)
        shotView.frame = CGRect(x: viewWidth*2, y: 0, width: viewWidth, height: contentH)
    }
    
    lazy var videoView:TrashContenView = {
        let videoView = TrashContenView()
        videoView.trashType = .video
        videoView.callback = { idx in
            UIView.animate(withDuration: 0.2) {
                self.contentScrollView.contentOffset = CGPoint(x: Int(self.view.width) * idx, y: 0)
                self.currentPage = idx + 1
            }
        }
        return videoView
    }()
    
    lazy var otherView:TrashContenView = {
        let otherView = TrashContenView()
        otherView.trashType = .other
        otherView.callback = { idx in
            UIView.animate(withDuration: 0.2) {
                self.contentScrollView.contentOffset = CGPoint(x: Int(self.view.width) * idx, y: 0)
                self.currentPage = idx + 1
            }
        }
        return otherView
    }()
    
    lazy var shotView:TrashContenView = {
        let shotView = TrashContenView()
        shotView.trashType = .shot
        shotView.callback = { idx in
            UIView.animate(withDuration: 0.2) {
                self.contentScrollView.contentOffset = CGPoint(x: Int(self.view.width) * idx, y: 0)
                self.currentPage = idx + 1
            }
        }
        return shotView
    }()
    
}

extension TrashViewController:UIScrollViewDelegate{
    
    func scrollViewDidScroll(_ scrollView: UIScrollView){
        let offset = scrollView.contentOffset.x
        print("滑动距离",offset)

        let model = TrashPageScrollModel.init(offset: offset,page: currentPage)
        NotificationCenter.default.post(name: .trashPageScroll, object: model)
    }
    
    // 当用户手指离开屏幕且滚动减速停止时调用
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        print("当前页: \(currentPage + 1)/\(pageCount)")
        self.currentPage = currentPage + 1
    }
    
    // 当使用 setContentOffset 或 scrollToRect 等方法触发的滚动动画结束时调用
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        let currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        print("当前页: \(currentPage + 1)/\(pageCount)")
        self.currentPage = currentPage + 1
       
    }
    
    
    @objc func delBtnAction(){
        
        let info = self.getTypeByCurrentPage(pageIndex: currentPage)
        let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: info.0)
        if data.count <= 0 {
            return
        }
        
        // 首先看是否订阅
        if IAPManager.share.isSubscribed == false {
            // 没有订阅
            let view : AdvTipDeleteView = AdvTipDeleteView(frame: self.view.bounds)
            view.dataSource = data
            
            // 获取当前免费次数
            let freeCount = ADManager.shared.defaultFreeTimes
            Print("免费次数----\(freeCount)")
            // 当免费次数用完以后，无论删除多少都需要弹出广告
            if freeCount <= 0 {
                HomePayViewController.show {
                    if IAPManager.share.isSubscribed == false{
                        // 弹出单个删除类型
                        view.deleteType = self.currentType == .video ? .deleteVideoOne : .deletePhotoOne
                        view.getOtherInfoByType(type: self.currentType == TrashTypeEnum.video ? PhotsFileType.videos : PhotsFileType.Other)
                        self.showPopView(popView: view)
                    }else {
                        self.delMethod(needUpdateFreeTimes: true)
                    }
                }
            }else {
                // 获取次数对应的删除照片数量
                var freeDeleteCount = ADManager.shared.advDeleteResouceDic[freeCount]!
                let tempArray = data
                if freeCount > 1 {
                    // 如果是前两次，可以免费删除5张照片
                    if tempArray.count > freeDeleteCount {
                        // 弹出多个删除类型
                        HomePayViewController.show {
                            if IAPManager.share.isSubscribed == false{
                                view.deleteType = self.currentType == .video ? .deleteVideosMore : .deletePhotosMore
                                view.freeDeleteCount = freeDeleteCount
                                view.getOtherInfoByType(type: self.currentType == TrashTypeEnum.video ? PhotsFileType.videos : PhotsFileType.Other)
                                self.showPopView(popView: view)
                            }else {
                                self.delMethod(needUpdateFreeTimes: true)
                            }
                        }
                    }else {
                        // 如果小于直接删除
                        HomePayViewController.show {
                            self.delMethod(needUpdateFreeTimes: true)
                        }
                    }
                    
                }else{
                    // 如果免费次数等于1，也就是第三次。看照片删除的数量
                    // 如果当前删除的照片大于5
                    if tempArray.count > 5 {
                        freeDeleteCount = 5
                        // 弹出多个删除类型
                        HomePayViewController.show {
                            if IAPManager.share.isSubscribed == false{
                                view.deleteType = self.currentType == .video ? .deleteVideosMore : .deletePhotosMore
                                view.freeDeleteCount = freeDeleteCount
                                view.getOtherInfoByType(type: self.currentType == TrashTypeEnum.video ? PhotsFileType.videos : PhotsFileType.Other)
                                self.showPopView(popView: view)
                            }else{
                                self.delMethod(needUpdateFreeTimes: true)
                            }
                        }
                    }else if tempArray.count > 1 && tempArray.count <= 5  {
                        // 如果是1张到5张之间，那么免费的张数是当前张数减一
                        freeDeleteCount = tempArray.count - 1
                        // 弹出多个删除类型
                        HomePayViewController.show {
                            if IAPManager.share.isSubscribed == false{
                                view.deleteType = self.currentType == .video ? .deleteVideosMore : .deletePhotosMore
                                view.freeDeleteCount = freeDeleteCount
                                view.getOtherInfoByType(type: self.currentType == TrashTypeEnum.video ? PhotsFileType.videos : PhotsFileType.Other)
                                self.showPopView(popView: view)
                            }else{
                                self.delMethod(needUpdateFreeTimes: true)
                            }
                        }
                    }else{
                        // 如果只是一张，直接删除
                        HomePayViewController.show {
                            self.delMethod(needUpdateFreeTimes: true)
                        }
                    }
                }
            }
            view.deleteButtonClickCallback = {[weak self] isMore,deleteCount in
                guard let self = self else { return }
                self.view.hideBlur()
                if deleteCount < 0 {
                    return
                }
                let info = self.getTypeByCurrentPage(pageIndex: self.currentPage)
                let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: info.0)
                if data.count <= 0 {
                    return
                }
                if isMore == true {
                    if IAPManager.share.isSubscribed == false {
                       // self.popAdverTisement()
                        // 广告看完再结束
//                        AdvManager.shared.finisedCallBack = {
//                            let tempArray = Array(data.prefix(deleteCount))
//                            TrashDataManager.clearTrashData(mediaType: info.0,data: tempArray) {
//                                info.1.dataSource.removeAll(where: {tempArray.map({$0.localIdentifier}).contains($0.localIdentifier)})
//                                self.showDeleteSuccess(array: tempArray)
//                            }
//                        }
                        ADManager.shared.showRewardedInterstitialAd(from: ADShowTypeEnum.Trash.name) {
                            let tempArray = Array(data.prefix(deleteCount))
                            TrashDataManager.clearTrashData(mediaType: info.0,data: tempArray) {
                                info.1.dataSource.removeAll(where: {tempArray.map({$0.localIdentifier}).contains($0.localIdentifier)})
                                self.showDeleteSuccess(array: tempArray)
                            }
                        } showFailBlock: { _ in
                            
                        }

                    }else{
                        let tempArray = Array(data.prefix(deleteCount))
                        TrashDataManager.clearTrashData(mediaType: info.0,data: tempArray) {
                            info.1.dataSource.removeAll(where: {tempArray.map({$0.localIdentifier}).contains($0.localIdentifier)})
                            self.showDeleteSuccess(array: tempArray)
                        }
                    }
                    
                } else {
                    let tempArray = Array(data.prefix(deleteCount))
                    TrashDataManager.clearTrashData(mediaType: info.0,data: tempArray) {
                        self.updateFreeTimes()
                        info.1.dataSource.removeAll(where: {tempArray.map({$0.localIdentifier}).contains($0.localIdentifier)})
                        self.showDeleteSuccess(array: tempArray)
                    }
                }
            }
        }else{
            self.delMethod(needUpdateFreeTimes: true)
        }
    }
    
    /// 弹出广告
    func popAdverTisement(){
       // AdvManager.shared.showRewardedInterstitialAd(vc: self,from: "trash")
    }
    
    // 显示弹出框
    func showPopView(popView: AdvTipDeleteView){
        self.view.showBlur()
        self.view.addSubview(popView)
    }
    
    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(array:[AssetModel]){
        var tempSize = 0.0
        for item in array {
            tempSize = tempSize + item.assetSize
        }
        
        DispatchQueue.main.async {
            let vc = DelSuccessViewController()
            vc.delType = array.count > 1 ? "photos" : "photo"
            vc.fileSzie = Int64(tempSize)
            vc.fileCount = array.count
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }
    }
    
    func delMethod(needUpdateFreeTimes:Bool){
        let info = self.getTypeByCurrentPage(pageIndex: currentPage)
        let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: info.0)
        if data.count > 0 {
            TrashDataManager.clearTrashData(mediaType: info.0,data: []) {
                if needUpdateFreeTimes {
                    self.updateFreeTimes()
                }
                info.1.dataSource.removeAll()
                self.showDeleteSuccess(array: data)
            }
        }
    }
    
    private func getTypeByCurrentPage(pageIndex : Int)->(TrashTypeEnum,TrashContenView){
        if self.currentPage == 1 {
            return (TrashTypeEnum.video,self.videoView)
        }
        if self.currentPage == 2 {
            return (TrashTypeEnum.other,self.otherView)
        }
        if self.currentPage == 3 {
            return (TrashTypeEnum.shot,self.shotView)
        }
        return (TrashTypeEnum.video,self.videoView)
    }
    
   private func setDelButtonUI(){
       let info = self.getTypeByCurrentPage(pageIndex: currentPage)
       let data : [AssetModel] = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: info.0)
       let type : TrashTypeEnum = info.0
       DispatchQueue.main.async {
           if self.delBtn == nil{
               return
           }
           self.delBtn.isHidden = data.count <= 0
           if data.count <= 0{
               self.delBtn.setTitle("Delete", for: .normal)
               self.delBtn.backgroundColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
           }else {
               self.delBtn.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
               if type == .video{
                   self.delBtn.setTitle("Delete \(data.count) \(self.getUnits(type:type,data:data))", for: .normal)
               }else {
                   self.delBtn.setTitle("Delete \(data.count) \(self.getUnits(type:type,data:data))", for: .normal)
               }
           }
       }
    }
    
    // 获取单位复数
    private func getUnits(type:TrashTypeEnum,data: [AssetModel])->String{
        if data.count > 1 {
            return type == .video ? "videos" : "photos"
        }else {
            return type == .video ? "video" : "photo"
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.dissmisCallBack()
    }
}
