//
//  SecretViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/3/31.
//

import UIKit
import HXPhotoPicker
import Photos


class SecretViewController: BaseViewController {

    static let psKey:String = "SecretKey"
    
    private var pass:String  {
        get {
            return SettingConfiguration.share.config.secret ?? "" //UserDefaults.standard.object(forKey: SecretViewController.psKey) as? String ?? ""
        }
    }
    
    /** 首次显示 */
    private var isShow:Bool {
        get {
            guard UserDefaults.standard.object(forKey: "SecretFirstShow") != nil else {
                UserDefaults.standard.set("1", forKey: "SecretFirstShow")
                return false
            }
            return true
        }
    }
    
    private var selectArray = NSMutableSet() {
        didSet{
            secretCollect.reloadData()
            bottomm.state = selectArray.count > 0 ? .del : .add
        }
    }
    
    var AddAction = SecretActionView()
    
    var dataSource:[String] = [] {
        didSet {
            NotDataView.isHidden = dataSource.count > 0
            secretCollect.isHidden = !(dataSource.count > 0)
            seletedAllBtn.isHidden = secretCollect.isHidden
            secretCollect.reloadData()
        }
    }
    
    fileprivate var Resource:URL = "SecretIm".document()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        APIReportManager.shared.startReport(type: .SecretSpace_show)
        _ = Resource.isDirect()
        if isShow {
            self.ShowUI()
        }else{
            let alert = SecretAlert()
            titleView.isHidden = true
            alert.callback = { [weak self] idx in
                alert.dismiss(animated: true)
                if idx == 1 {
                    let set = SecretSetViewController()
                    set.secretType = .create
                    set.Callback = { su in
                        set.dismiss(animated: true)
                        self?.ShowUI()
                    }
                    set.modalPresentationStyle = .fullScreen
                    self?.present(set, animated: true)
                }else{
                    self?.ShowUI()
                }
            }
            alert.show()
        }
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        secretLock.isSelected = !(pass.count > 1)
        if secretLock.isSelected {
            secretLock.setImage(UIImage(named: "ic_unlock_secret"), for: .normal)
        }else{
            secretLock.setImage(UIImage(named: "ic_lock_secret"), for: .normal)
        }
        self.loadData()
        self.secretCollect.reloadData()
    }
    
    @discardableResult
    private func loadData() -> [String] {
        let file:[String] = "SecretIm".contentOfDir()
        var p = 0
        var v = 0
        for i in file {
            if i.hasSuffix(".png") {
                p += 1
            }else{
                v += 1
            }
        }
        secretDesc.text = "\(p) Photos, \(v) Videos"
        dataSource = file
        return file
    }
    
    private func deleteData() -> Void {
        let DelCallBlock = { [weak self] in
            guard let self = self else { return }
            var delName:[String] = []
            for idx in self.selectArray.allObjects {
                guard let row:Int = idx as? Int else { return }
                let name = self.dataSource[row]
                delName.append(name)
            }
            "".delPhotoVideo(delName)
            if self.selectArray.count > 0 {
                self.selectArray.removeAllObjects()
            }
            Print("删除成功")
            self.dataSource = self.loadData()
            self.bottomm.state = .add
        }
//        if SettingConfiguration.share.config.removeImg {
        
        let alert = PMSecretHintsAlert()
        self.view.showBlur()
        alert.show { idx in
            if idx == 1 {
                DelCallBlock()
            }
            self.view.hideBlur()
            alert.dismiss(animated: true)
        }
//            PMAlert(messsage:"These photos or videos will be deleted from your private space" , action: ["Cancel","Delete"] , complate: {  alert, selectidx in
//                if selectidx == 1 {
//                    DelCallBlock()
//                }
//                alert.dismiss(animated: true)
//            })
//        }else{
//            DelCallBlock()
//        }
    }
    
    @objc private func lockTouch(_ sender:UIButton) -> Void {
        if pass.count > 2 {
            let set = SecretSetViewController()
            set.secretType = .del
            set.Callback = { cr in
                set.dismiss(animated: true)
            }
            set.modalPresentationStyle = .fullScreen
            self.present(set, animated: true)
        }else{
            let set = SecretSetViewController()
            set.secretType = .create
            set.Callback = { cr in
                set.dismiss(animated: true)
            }
            set.modalPresentationStyle = .fullScreen
            self.present(set, animated: true)
        }
    }
    
    private func setUI() -> Void {
        secretTL.text = "Secret Library"
        secretDesc.text = "0 Photos, 0 Videos"
        secretCollect.register(SecretFirstCell.self, forCellWithReuseIdentifier: SecretFirstCellID)
        
//        seletedAllBtn.x = titleView.width - marginLR - seletedAllBtn.width
//        seletedAllBtn.centerY = navCenterY
        titleView.addSubview(seletedAllBtn)
        seletedAllBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(marginLR)
            make.height.equalTo(32)
            make.centerY.equalTo(titleView.backBtn.snp.centerY)
        }
        
        
        secretTL.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(UIEdgeInsets(top: 72.RW(), left: 15.RW(), bottom: 0, right: 0))
            make.top.equalTo(titleView.snp.bottom).offset(10)
        }
        secretDesc.snp.makeConstraints { make in
            make.left.equalTo(secretTL.snp.left)
            make.top.equalTo(secretTL.snp.bottom).offset(12)
        }
        secretLock.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-28)
            make.centerY.equalTo(secretTL.snp.centerY)
            make.width.height.equalTo(28)
        }
        bottomm.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(68 + (cWindow?.safeAreaInsets.bottom ?? 0))
        }
        secretCollect.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalTo(secretDesc.snp.bottom).offset(16)
            make.bottom.equalTo(bottomm.snp.top).offset(-5)
        }
        NotDataView.snp.makeConstraints { make in
            make.left.right.bottom.top.equalTo(secretCollect)
        }
        loadData()
    }
    
    private lazy var NotDataView: SecretNotDataView = {
        let not = SecretNotDataView()
        not.isHidden = true
        view.addSubview(not)
        not.clipsToBounds = true
        return not
    }()
    
    private lazy var secretCollect: UICollectionView = {
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.minimumInteritemSpacing = 9;
        flowlayout.minimumLineSpacing = 12
        flowlayout.sectionInset = UIEdgeInsets()
        let col = UICollectionView(frame: CGRectZero, collectionViewLayout: flowlayout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.delegate = self;
        col.dataSource = self;
        view.addSubview(col)
        return col
    }()
    
    private lazy var secretTL: UILabel = {
        let t = UILabel()
        t.font = UIFont.boldSystemFont(ofSize: 20.RW())
        t.textColor = .colorWithHex(hexStr: "#333333")
        view.addSubview(t)
        return t
    }()

    private lazy var secretDesc: UILabel = {
        let desc = UILabel()
        desc.textColor = .colorWithHex(hexStr: "#333333")
        desc.font = UIFont.systemFont(ofSize: 14.RW())
        view.addSubview(desc)
        return desc
    }()
    
    private lazy var secretLock: UIButton = {
        let lock = UIButton(type: .custom)
        lock.addTarget(self, action: #selector(lockTouch(_:)), for: .touchUpInside)
        view.addSubview(lock)
        return lock
    }()
    
    private lazy var bottomm: SecretBottomView = {
        let b = SecretBottomView()
        view.addSubview(b)
        b.callback = { [weak self] idx in
            guard let self = self else { return }
            if idx < 0 {
                if IAPManager.share.isSubscribed == false {
                    // 添加的时候需要先弹出广告
//                    if AdvManager.shared.advTimeAfterInAPP <= 0{
//                        popAdverTisement()
//                        AdvManager.shared.finisedCallBack = {
//                            self.AddAction = SecretActionView()
//                            self.AddAction.show();
//                            self.view.showBlur()
//                            self.AddAction.callback = { idx in
//                                popAdvThenDo(idx: idx)
//                            }
//                        }
//                    }else {
//                        self.AddAction = SecretActionView()
//                        self.view.showBlur()
//                        self.AddAction.show();
//                        self.AddAction.callback = { idx in
//                            popAdvThenDo(idx: idx)
//                        }
//                    }
//                    self.AddAction = SecretActionView()
//                    self.AddAction.show();
//                    self.view.showBlur()
//                    self.AddAction.callback = { idx in
//                        popAdvThenDo(idx: idx)
//                    }
//                    
//                    AdvManager.shared.finisedCallBack = {
//                        if AdvManager.shared.adFromVC == "Secret"{
//                            self.AddAction = SecretActionView()
//                            self.AddAction.show();
//                            self.view.showBlur()
//                            self.AddAction.callback = { idx in
//                                popAdvThenDo(idx: idx)
//                            }
//                        }
//                    }

                  //  popAdverTisement()
                    
                    self.AddAction = SecretActionView()
                    self.AddAction.show();
                    self.view.showBlur()
                    self.AddAction.callback = { idx in
                        popAdvThenDo(idx: idx)
                    }
                    
                }else {
                    self.AddAction = SecretActionView()
                    self.view.showBlur()
                    self.AddAction.show();
                    self.AddAction.callback = { idx in
                        popAdvThenDo(idx: idx)
                    }
                }
            }else if idx == 0 {
                let all = self.selectArray.allObjects.sorted { a, b in
                    guard let ia = a as? Int,
                          let ib = b as? Int else { return false }
                    return ia < ib
                }
                if let idx = all.first as? Int,
                   let name = self.dataSource[idx] as? String {
                    let url = "SecretIm".document().appendingPathComponent(name)
                    if name.hasSuffix(".png") {
                        let urls =  "".af() + "/SecretIm/" + name
                        if let icon = UIImage(contentsOfFile: urls) {
                            PhoneShare([icon], parent: self)
                        }
                    }else{
                        PhoneShare([url], parent: self)
                    }
                }
            }else{
                // 删除图片的时候不弹广告和内购
                self.deleteData()
            }
            
            func popAdverTisement(){
                
               // AdvManager.shared.showInterstitialAd(vc: self,from:"Secret")
            
            }
            
            // 临时方法
            func popAdvThenDo(idx : Int){
                self.view.hideBlur()
                self.AddImagePicker(idx)
//                if AdvManager.shared.advTimeAfterInAPP <= 0{
//                    popAdverTisement()
//                    AdvManager.shared.finisedCallBack = {
//                        self.view.hideBlur()
//                        self.AddImagePicker(idx)
//                    }
//                }else {
//                    self.view.hideBlur()
//                    self.AddImagePicker(idx)
//                }
            }
        }
        return b
    }()
    
    private lazy var seletedAllBtn:SelectAllButton = {
        let view = SelectAllButton()
        view.clipsToBounds = true
        view.layer.cornerRadius = 16
        view.tapCallback = {[weak self] isselect in
            self?.seletedAllBtnClick()
        }
        return view
//        let btn:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 115, height: 32))
//        btn.addTarget(self, action: #selector(seletedAllBtnClick), for: .touchUpInside)
//        btn.backgroundColor = UIColor.colorWithHex(hexStr: "#F2F6FC")
//        btn.setImage(UIImage.init(named: "ic_check_similar"), for: .normal)
//        btn.setTitle("Select All", for: .normal)
//        btn.setImage(UIImage.init(named: "ic_close_similar"), for: .selected)
//        btn.setTitle("Unselect all", for: .selected)
//        btn.setTitleColor(UIColor.colorWithHex(hexStr: mColor), for: .normal)
//        btn.setTitleColor(UIColor.colorWithHex(hexStr: black3Color), for: .selected)
//        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold)
//        btn.addTarget(self, action: #selector(seletedAllBtnClick), for: .touchUpInside)
//        
//        btn.layer.cornerRadius = btn.height / 2
//        btn.layer.masksToBounds = true
//        btn.changBtnWithStytl(btnStyle: .defalut, margin: 8)
//        
//        return btn
    }()
    
    deinit {
        Print("释放SecretViewController")
        SecretImageCache.share.removeAllImage()
    }
    
}


extension SecretViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:SecretFirstCell = collectionView.dequeueReusableCell(withReuseIdentifier: SecretFirstCellID, for: indexPath) as! SecretFirstCell
        cell.layer.cornerRadius = 12;
        cell.clipsToBounds = true
        cell.isSelect = selectArray.contains((indexPath.row))
        cell.imageText = dataSource[indexPath.row]
        cell.callback = { [weak self] in
            self?.vibrate()
            self?.selectImgVideo(indexPath.row)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let play = PMShowImgVideoController()
        play.currentIdx = indexPath.row
        play.imageVideoPath = dataSource
        play.oldPageIndexPath = indexPath
        play.backOrgPageCallBack = {[weak self]index,data in
            guard let self else {return}
            self.selectArray = play.selectSet
            DispatchQueue.main.async{
                UIView.transition(with: self.secretCollect, duration: 0.3, options: .transitionCrossDissolve, animations: {
                    self.secretCollect.reloadData()
                }, completion: nil)
            }
        }
        self.navigationController?.pushViewController(play, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (CGRectGetWidth(collectionView.frame) - 9.1) / 2.0
        return CGSize(width: width, height: width * (223/168.0) )
    }
    
    @objc private 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
            let sets = NSMutableSet()
            if seletedAllBtn.isSelected {
                for i in 0..<dataSource.count {
                    sets.add((i))
                }
                selectArray = sets
            }else{
                selectArray = NSMutableSet()
            }
        }
    }
}

extension SecretViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate {
    
    private func ShowUI() -> Void {
        self.setUI()
        self.titleView.isHidden = false
        dataSource = self.loadData()
    }
    
    private func selectImgVideo(_ row:Int) -> Void {
        let set:NSMutableSet = NSMutableSet(set: selectArray)
        if set.contains((row)) {
            set.remove((row))
        }else{
            set.add((row))
        }
        selectArray = set
        seletedAllBtn.isSelected = selectArray.count == dataSource.count
        secretCollect.reloadData()
    }
    
    private func SecretPhotos(_ idx:Int, _ data:Any ) -> Void {
        if let asset:[PhotoAsset] = data as? [PhotoAsset] {
            var assetdels:[PHAsset] = []
            for set in asset {
                let name = set.localAssetIdentifier
                if set.mediaType == .photo {
                    set.getImage {[weak self] icon in
                        if icon != nil {
                            self?.SaveSecret(name + ".png", icon!.pngData() ?? Data())
                            self?.loadData()
                        }
                    }
                }else if set.mediaType == .video {
                    set.getVideoURL {[weak self] resltu in
                        switch resltu {
                        case .success(let assetUrl):
                            let fab = assetUrl.url
                            do {
                                let data = try Data(contentsOf: fab)
                                self?.SaveSecret(name + ".mp4", data)
                                self?.loadData()
                            }catch{
                                
                            }
                            break
                        default:
                            break
                        }
                        
                    }
                }
                assetdels.append(set.phAsset!)
            }
            if SettingConfiguration.share.config.removeImg {
                SecretPhotoManager.share.deleteAssets(assetdels)
            }
        }else{
            guard let d = data as? Data else { return }
            if idx == 0 { // image
                let name = String(format: "%ld.png", Date().timeIntervalSince1970)
                SaveSecret(name, d)
            }else{
                let name = String(format: "%ld.mp4", Date().timeIntervalSince1970)
                SaveSecret(name, d)
            }
            loadData()
        }
    }
    
    private func AddImagePicker(_ idx:Int) -> Void {
        SecretPhotoManager.share.callback = { [weak self] type,data in
            self?.SecretPhotos(type, data)
        }
        if idx == 0 {
            SecretPhotoManager.share.show(0)
        }else if idx == 1 {
            SecretPhotoManager.share.show(1)
        }else{
            
        }
    }
    
    func SaveSecret(_ name:String, _ data:Data) -> Void {
        let file = Resource.appendingPathComponent(name)
        do {
            try data.write(to: file)
        }catch{ }
    }
    
}
