//
//  TrashSubView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/13.
//

import UIKit

class TrashSubView: UIView {
    
    var type : TrashTypeEnum?
    
    var clearTashDataCallBack : ()->Void = {}
    
    var presentTashDetailViewClickCallBack : ()->Void = {}
    
    lazy var resourceCountlabel : UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 24, weight: .semibold)
        label.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
        return label
    }()
    lazy var tipLabel : UILabel = {
        let label = UILabel()
        label.text = "The photo in the trash can"
        label.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
        label.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
        label.numberOfLines = 0
        return label
    }()
    
    lazy var emptyButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "pm-home-Frame-del"), for: .normal)
        button.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        button.setTitle("Empty Trash", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
        button.layer.cornerRadius = 19
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(emptyButtonAction), for: .touchUpInside)
        return button
    }()

    override func layoutSubviews() {
        super.layoutSubviews()
        self.setShadow(cornerRadius: 0, sColor: UIColor.colorWithHex(hexStr: "#1475B9"), offset: CGSizeMake(3, -1),opacity: 0.15)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
//        self.addTopShadow()
        // 给当前视图添加手势
        addTapGestureToSelf()
        
        // 添加UI
        addUIViews()
        setUILocation()
    }
    
    private func addUIViews(){
        self.addSubview(self.resourceCountlabel)
        self.addSubview(self.tipLabel)
        self.addSubview(self.emptyButton)
    }
    
    private func setUILocation(){
        self.resourceCountlabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(28)
            make.height.equalTo(22)
        }
        self.tipLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(17)
            make.bottom.equalToSuperview().offset(-17 - safeHeight)
            make.left.equalTo(self.resourceCountlabel.snp.right).offset(11)
//            make.width.equalTo(200)
            make.right.equalTo(emptyButton.snp.left).offset(-5)
        }
        self.emptyButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-9)
            make.height.equalTo(38)
            make.top.equalToSuperview().offset(20)
            make.width.equalTo(145)
        }
    }
    
    private func addTapGestureToSelf(){
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(tapHandle))
        self.addGestureRecognizer(tap)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension TrashSubView {
    @objc func emptyButtonAction(){
        if let vc = self.responderViewController(){
            let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: self.type)
            if data.count <= 0 {
                return
            }
            
            // 首先看是否订阅
            if IAPManager.share.isSubscribed == false {
                // 没有订阅
                let view : AdvTipDeleteView = AdvTipDeleteView(frame: vc.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.type == .video ? .deleteVideoOne : .deletePhotoOne
                            view.getOtherInfoByType(type: self.type == 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.type == .video ? .deleteVideosMore : .deletePhotosMore
                                    view.freeDeleteCount = freeDeleteCount
                                    view.getOtherInfoByType(type: self.type == 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.type == .video ? .deleteVideosMore : .deletePhotosMore
                                    view.freeDeleteCount = freeDeleteCount
                                    view.getOtherInfoByType(type: self.type == 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.type == .video ? .deleteVideosMore : .deletePhotosMore
                                    view.freeDeleteCount = freeDeleteCount
                                    view.getOtherInfoByType(type: self.type == 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 }
                    if let vc = self.responderViewController() {
                        vc.view.hideBlur()
                    }
                   
                    if deleteCount < 0 {
                        return
                    }
                    let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: self.type)
                    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: self.type,data: tempArray) {
//                                    self.clearTashDataCallBack()
//                                    self.showDeleteSuccess(array: tempArray)
//                                }
//                            }
                            ADManager.shared.showRewardedInterstitialAd(from: ADShowTypeEnum.Trash.name) {
                                let tempArray = Array(data.prefix(deleteCount))
                                TrashDataManager.clearTrashData(mediaType: self.type,data: tempArray) {
                                    self.clearTashDataCallBack()
                                    self.showDeleteSuccess(array: tempArray)
                                }
                            } showFailBlock: { _ in
                                
                            }

                        }else{
                            let tempArray = Array(data.prefix(deleteCount))
                            TrashDataManager.clearTrashData(mediaType: self.type,data: tempArray) {
                                self.clearTashDataCallBack()
                                self.showDeleteSuccess(array: tempArray)
                            }
                        }
                        
                    } else {
                        let tempArray = Array(data.prefix(deleteCount))
                        TrashDataManager.clearTrashData(mediaType: self.type,data: tempArray) {
                            self.clearTashDataCallBack()
                            self.showDeleteSuccess(array: tempArray)
                            self.updateFreeTimes()
                        }
                    }
                }
            }else{
                self.delMethod(needUpdateFreeTimes: true)
            }
        }
        
    }
    // 删除成功页面
    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.responderViewController()?.present(vc, animated: true)
        }
    }
    @objc func tapHandle(){
        self.presentTashDetailViewClickCallBack()
    }
    
    
    // MARK: 广告相关
    
    func delMethod(needUpdateFreeTimes:Bool){
    
        let data = TrashDataManager.getCurrentMediaTypeTrashData(mediaType: self.type)
        if data.count > 0 {
            TrashDataManager.clearTrashData(mediaType: self.type,data: []) {
                if needUpdateFreeTimes {
                    self.updateFreeTimes()
                }
                self.clearTashDataCallBack()
                self.showDeleteSuccess(array: data)
            }
        }
    }
    /// 弹出广告
    func popAdverTisement(){
        if let vc = self.responderViewController() {
           // AdvManager.shared.showRewardedInterstitialAd(vc: vc,from: "trash")
        }
        
    }
    
    // 显示弹出框
    func showPopView(popView: AdvTipDeleteView){
        self.responderViewController()?.view.showBlur()
        self.responderViewController()?.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")
            }
        }
    }
}
