//
//  HomeInfoViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/3/25.
//

import UIKit
import Photos

class HomeInfoViewController:BaseViewController {
    
    private var type:PhotsFileType?
    
    lazy var seletedAllBtn:SelectAllButton = {
        let view = SelectAllButton()
        view.clipsToBounds = true
        view.layer.cornerRadius = 16
        view.tapCallback = {[weak self] isselect in
            self?.seletedAllBtnClick()
        }
        return view
    }()
    
    lazy var tablewView:HomeInfoView = {
        
        let cY:CGFloat = titleView.y + titleView.height
        
        let sview:HomeInfoView = HomeInfoView(frame: CGRect(x: 0, y: cY, width: view.width, height: view.height - cY), ids: ids,type: self.type,titleText: titleText)
        
        sview.titleShowHideCallBack = {[weak self] isShow in
            guard let self else {return}
            if isShow && self.titleLabel.alpha == 0 {
                UIView.animate(withDuration: 0.1) {
                    self.titleLabel.alpha = 1
                }
            }else if isShow == false && self.titleLabel.alpha == 1{
                UIView.animate(withDuration: 0.1) {
                    self.titleLabel.alpha = 0
                }
            }
        }
        
        sview.callBack = {[weak self] isSeleted in
            
            guard let self  else {return}
            
            if let cS = isSeleted as? Bool {
                
                DispatchQueue.main.async {[weak self] in
                    
                    guard let self  else {return}
                    
                    self.seletedAllBtn.isSelected = cS
//                    self.seletedAllBtn.width = cS ? 131 : 115
//                    seletedAllBtn.x = titleView.width - marginLR - seletedAllBtn.width
                }
            }
        }
        
        
        func deleteOp(imgs : [AssetModel],isAfterAdv:Bool){
            var tempStringArray : [String] = []
            for item in imgs {
                tempStringArray.append(item.localIdentifier)
            }
            let fetchs = PHAsset.fetchAssets(withLocalIdentifiers: tempStringArray, options: nil)
            let fileSize = FileTool().calculateTotalAssetSize(fetchResult: fetchs)

            PMLoadingHUD.share.show()

            PhotoManager.shared.deleteAssets(localIdentifiers: tempStringArray) {[weak self]  in
                guard let self else {return}
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    PMLoadingHUD.share.disMiss()
                    
                    // 更新免费次数
                    if isAfterAdv == false {
                        updateFreeTimes()
                    }
                    
                    self.showDeleteSuccess(fileCount: tempStringArray.count, fileSize: fileSize)
                    
                    PhotoManager.shared.removeDataWhenDeleteInPage(data: imgs)
                    
                    let new = self.ids?.removingElementsAndSmallGroups(ids: imgs.compactMap{$0.localIdentifier})
                    
                    self.ids = new
                    
                    self.tablewView.ids = self.ids
                    self.tablewView.deleteModel(array: imgs)
                    
                    
                    self.setDefaultPage()
                }
                
                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 showPopView(popView: AdvTipDeleteView){
            self.view.showBlur()
            self.view.addSubview(popView)
        }
        
        
        sview.deleteCallBack = { [weak self] array in
            guard let self = self else { return }
            
            var dealArray = array
            
            
            // 首先看是否订阅
            if IAPManager.share.isSubscribed == false {
                
                if array.count > Singleton.shared.maxDeleteCount {
                    dealArray = Array(dealArray.prefix(25))
                }
                // 没有订阅
                let view : AdvTipDeleteView = AdvTipDeleteView(frame: self.view.bounds)
            
                view.dataSource = dealArray
                
                // 获取当前免费次数
                let freeCount = ADManager.shared.defaultFreeTimes
                // 当免费次数用完以后，无论删除多少都需要弹出广告
                if freeCount <= 0 {
                    HomePayViewController.show {
                        if IAPManager.share.isSubscribed == false{
                            // 弹出单个删除类型
                            view.deleteType = .deletePhotoOne
                            view.getOtherInfoByType(type: self.type!)
                            showPopView(popView: view)
                        }else{
                            deleteOp(imgs: dealArray ,isAfterAdv: false)
                        }
                    }
                }else {
                    // 获取次数对应的删除照片数量
                    var freeDeleteCount = AdvManager.shared.advDeleteResouceDic[freeCount]!
                    let tempArray = dealArray
                    if freeCount > 1 {
                        // 如果是前两次，可以免费删除5张照片
                        if tempArray.count > freeDeleteCount {
                            // 弹出多个删除类型
                            HomePayViewController.show {
                                if IAPManager.share.isSubscribed == false{
                                    view.deleteType = .deletePhotosMore
                                    view.freeDeleteCount = freeDeleteCount
                                    view.getOtherInfoByType(type: self.type!)
                                    showPopView(popView: view)
                                }else {
                                    deleteOp(imgs: dealArray,isAfterAdv: false)
                                }
                            }
                        }else {
                            // 如果小于直接删除
                            HomePayViewController.show {
                                deleteOp(imgs: dealArray,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: self.type!)
                                    showPopView(popView: view)
                                }else {
                                    deleteOp(imgs: dealArray,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: self.type!)
                                    showPopView(popView: view)
                                }else {
                                    deleteOp(imgs: dealArray ,isAfterAdv: false)
                                }
                            }
                        }else{
                            // 如果只是一张，直接删除
                            HomePayViewController.show {
                                deleteOp(imgs: dealArray ,isAfterAdv: false)
                            }
                        }
                    }
                }
                
                
                view.deleteButtonClickCallback = {[weak self] isMore,deleteCount in
                    self?.view.hideBlur()
                    guard let self else {return}
                    if deleteCount < 0 {
                        return
                    }
                    let finalyDeleteArray = array
                    var tempArr : [AssetModel] = []
                    for item in finalyDeleteArray {
                        if tempArr.count < deleteCount {
                            tempArr.append(item)
                        }
                    }
                    if isMore == true{
                        if IAPManager.share.isSubscribed == false {
                            let currentType = self.type == .SimilarVideos ? ADShowTypeEnum.videoDdelete : ADShowTypeEnum.PhotoDelete
                            ADManager.shared.showRewardedInterstitialAd(from: currentType.name) {
                                DispatchQueue.main.async {
                                    deleteOp(imgs: tempArr,isAfterAdv: true)
                                }
                            } showFailBlock: { error in
                                
                            }
                           // self.popAdverTisement()
                            // 广告看完再结束
//                            AdvManager.shared.finisedCallBack = {
//                                DispatchQueue.main.async {
//                                    deleteOp(imgs: tempArr,isAfterAdv: true)
//                                }
//                            }
                        }else{
                            deleteOp(imgs: tempArr,isAfterAdv: true)
                        }
                    } else {
                        DispatchQueue.main.async {
                            deleteOp(imgs: tempArr,isAfterAdv: false)
                        }
                    }
                }
            }else {
                deleteOp(imgs: array ,isAfterAdv: false)
            }
        }
        
        return sview
    }()
    
    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
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14, weight: .bold)
        label.textColor = UIColor.colorWithHex(hexStr: black3Color)
        label.text = titleText
        label.alpha = 0
        label.sizeToFit()
        return label
    }()
    
    var ids: [[AssetModel]]?
    
    var titleText : String?
    
    init(ids: [[AssetModel]],type:PhotsFileType?,titleText:String) {
        self.ids = ids
        self.type = type
        self.titleText = titleText
        super.init(nibName: nil, bundle: nil)
    }
    
    /// 弹出广告
    func popAdverTisement(){
       // AdvManager.shared.showRewardedInterstitialAd(vc: self)
//        ADManager.shared.showRewardedInterstitialAd(from: "") {
//            DispatchQueue.main.async {
//                deleteOp(imgs: tempArr,isAfterAdv: true)
//            }
//        } showFailBlock: { error in
//            
//        }

    }
    
    // 由于继承自 UIViewController，必须实现这个必需的构造器
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        titleView.model.title = ""
        
        showTipsVC()
        
        self.tablewView.keepAllNoDataCallBack = {
            self.ids = []
            self.setDefaultPage()
        }
    
        configSelectAll()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        seletedAllBtn.isHidden =  (self.ids?.count ?? 0 <= 0)
    }
    
    // 删除成功页面
    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 showTipsVC(){
        
        guard let type = self.type else{
            return
        }
        
        guard TipsManager.getLoadStauts(type) == false else{
            return
        }
        
        switch type {
        case .duplicates:
            let vc = TipsDuplicatesSimilarController()
            vc.type = .duplicates
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        case .similar:
            let vc = TipsDuplicatesSimilarController()
            vc.type = .similar
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        case .videos:
            let vc = TipsVideoPhotoController()
            vc.type = .video
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        case .similarScreenshots:
            break
        case .screenshots:
            let vc = TipsScreenShotController()
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        case .SimilarVideos:
            break
        case .Other:
            let vc = TipsVideoPhotoController()
            vc.type = .photo
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }
        
        TipsManager.saveLoadStatus(type)
    }
    
    override func addViews() {
        
        super.addViews()
        
//        seletedAllBtn.x = titleView.width - marginLR - seletedAllBtn.width
//        seletedAllBtn.centerY = navCenterY
        titleView.addSubview(seletedAllBtn)
        seletedAllBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-marginLR)
            make.centerY.equalTo(titleView.backBtn.snp.centerY)
            make.height.equalTo(32)
        }
        
        titleLabel.x = titleView.backBtn.width + titleView.backBtn.x + 10
        titleLabel.centerY = navCenterY
        titleView.addSubview(titleLabel)
        
        view.addSubview(self.tablewView)
        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()
        }
        setDefaultPage()
    }
    
    //设置空白页
    func setDefaultPage(){
        
        DispatchQueue.main.async {
            if PhotoManager.shared.permissionStatus == .denied{
                self.loadPermissView()
            }else{
                if self.ids?.count == 0 {
                    if self.type == .SimilarVideos{
                        self.defaultImageView.image = UIImage(named: "img_vedio_defpage")
                    }else {
                        self.defaultImageView.image = UIImage(named: "img_photo__home_defpage")
                    }
                    self.defaultImageView.isHidden = false
                    self.defaultTipLabel.isHidden = false
                    self.seletedAllBtn.isHidden = true
                }else{
                    self.defaultImageView.isHidden = true
                    self.defaultTipLabel.isHidden = true
                    self.seletedAllBtn.isHidden = false
                }
            }
        }
    }
    
    func configSelectAll(){
        seletedAllBtn.isSelected = true
//        self.seletedAllBtn.width = seletedAllBtn.isSelected ? 131 : 115
//        seletedAllBtn.x = titleView.width - marginLR - seletedAllBtn.width
        
        self.tablewView.changeALlValue(isSeleted: seletedAllBtn.isSelected)
    }
    
    @objc func seletedAllBtnClick() {
        
        DispatchQueue.main.async {[weak self] in
            
            guard let self  else {return}
            
//            seletedAllBtn.isSelected = !seletedAllBtn.isSelected
//            self.seletedAllBtn.width = seletedAllBtn.isSelected ? 131 : 115
//            seletedAllBtn.x = titleView.width - marginLR - seletedAllBtn.width
            
            tablewView.changeALlValue(isSeleted: seletedAllBtn.isSelected)
        }
    }
    
}

extension UIViewController{
    
    func loadPermissView(_ frame:CGRect = CGRect(x: 0, y: 200+kSafeAreaInsets.top, width: ScreenW, height: 340)){
        let permissionView = Bundle.main.loadNibNamed("PMPermissionView", owner: nil)?.last as! PMPermissionView
        permissionView.frame = frame
        self.view.addSubview(permissionView)
    }
    
}

