//
//  CCSpaceAlbumFilterPopView2.swift
//  SwiftProject
//
//  Created by aaa on 2024/3/22.
//

import Foundation
import UIKit
import Photos
import SVProgressHUD
private let Back_Height:CGFloat = KHZSize(700)

enum SelectedFileType : Int {
    case all
    case image
    case video
}



//MARK: - Cell
class CCSpaceAlbumFliterCollectionCell: UICollectionViewCell {
    
    let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    let frameCountLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.backgroundColor = UIColor(hexString: "#383739")
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 12)
        label.layer.cornerRadius = 8
        label.adjustsFontSizeToFitWidth = true
        label.layer.masksToBounds = true
        return label
    }()
    
    let timeLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.backgroundColor = UIColor(hexString: "#000000",alpha:0.7)
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 12)
        label.layer.cornerRadius = 2
        label.adjustsFontSizeToFitWidth = true
        label.layer.masksToBounds = true
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }
    
    private func setupViews() {
        addSubview(imageView)
        addSubview(frameCountLabel)
        addSubview(timeLabel);
        
        imageView.translatesAutoresizingMaskIntoConstraints = false
        frameCountLabel.translatesAutoresizingMaskIntoConstraints = false
        timeLabel.translatesAutoresizingMaskIntoConstraints = false
        
        
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: topAnchor),
            imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
            
            frameCountLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8),
            frameCountLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
            frameCountLabel.widthAnchor.constraint(equalToConstant: 40),
            frameCountLabel.heightAnchor.constraint(equalToConstant: 20),
            
            timeLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4),
            timeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4),
            timeLabel.widthAnchor.constraint(equalToConstant: 40),
            timeLabel.heightAnchor.constraint(equalToConstant: 20)
        ])
    }
}



//MARK: - Model
enum AssetType : Int {
    case image
    case video
    case all
}
class CCSpaceAlbumFliterModel: NSObject {
    
    /// 1 image   2 video   3 gif
    var assetType:AssetType?
    var itemAsset :PHAsset?
    var astLocalIdentifier :String?
    var image: UIImage?//照片或者视频第一帧
    /** 是否被用户勾选 */
    var isSelected :Bool?
    /** 当前元素 被选中之后的标号 */
    var currentItemSelectedFlage: String?
    var videoTimeLength:Int?
    
    static func initWithAssetType(assetType:AssetType,asset:PHAsset,image:UIImage,localIdentifier:String) -> CCSpaceAlbumFliterModel {
        let model = CCSpaceAlbumFliterModel()
        model.assetType = assetType
        model.itemAsset = asset
        model.astLocalIdentifier = localIdentifier
        model.image = image
        
        return model
    }
}





class CCSpaceAlbumFilterPopView2: UIView {
    var selectedImageHandler: ((Data,PHAsset) -> Void)?
    var selectedVideoHandler: ((URL,PHAsset) -> Void)?
    var selectedFileType:SelectedFileType = .all {
        didSet{
            reloadData()
        }
    }
    
    var dataSource:[CCSpaceAlbumFliterModel] = []
    let filterLimit = 36//一次性获取的内容数量
    var isLoadingMoreData = false//标识是否正在加载更多的数据
    var shouldLoadDataCount = 0//标识本次总的加载数据是多少条
    
    lazy var backView: UIView = {
        let imageView = UIView(frame: CGRectMake(0, KScreenHeight + 10 , KScreenWidth, Back_Height))
        imageView.backgroundColor = UIColor(hexString: "#1F1E20")
        imageView.addCorner(conrners: [.topLeft,.topRight], radius: 12.0)
        return imageView
    }()
    
    lazy var topView: UIView = {
        let imageView = UIView(frame: CGRectMake(0, 0, backView.frame.size.width, 58))
        imageView.backgroundColor = .clear
        return imageView
    }()
    
    lazy var cancelButton: UIButton = {
        let button = UIButton.init()
        button.setTitle(NSLocalizedString("取消", comment: ""), for: .normal)
        button.setTitleColor(UIColor(red: 165.0/255, green: 137.0/255, blue: 1, alpha: 1), for: .normal)
        button.titleLabel?.font =  UIFont.systemFont(ofSize: 16)//KFont_Medium(16)
//        button.titleLabel?.adjustsFontSizeToFitWidth = true
        button.contentHorizontalAlignment = .center
        button.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        
        return button
    }()
    
    
 
    
    
    let AlbumIdentifierCell: String = "CCSpaceAlbumFliterCollectionCell"

    lazy var listCollectView:UICollectionView = {
        //1.流布局
        let collectionLayout = UICollectionViewFlowLayout()
        //3.垂直和水平滚动
        collectionLayout.scrollDirection = .vertical
        
        //6.定义collectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionLayout)
        //7.注册collectionViewCell
        collectionView.register(CCSpaceAlbumFliterCollectionCell.self, forCellWithReuseIdentifier: AlbumIdentifierCell)
        
        //10.设置代理
        collectionView.delegate = self
        collectionView.dataSource = self

        //隐藏滑动条
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = UIColor.black
        return collectionView
    }()
    
    lazy var segmentBtn:UISegmentedControl = {
        let sbtn = UISegmentedControl.init(items: [NSLocalizedString("全部", comment: ""),NSLocalizedString("图片", comment: ""),NSLocalizedString("视频", comment: "")])
        sbtn.addTarget(self, action: #selector(filterAction(btn:)), for: .valueChanged)
        sbtn.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white], for: .normal)
        sbtn.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.black], for: .selected)
        sbtn.selectedSegmentIndex = 0
        sbtn.selectedSegmentTintColor = UIColor(red: 165.0/255, green: 137.0/255, blue: 1, alpha: 1)
        return sbtn
    }()
    
    
    
    
    //MARK: - 释放销毁
    deinit {
        print("ccspacealbumfilterpopview2....deinit....")
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: - 通知 进入前台
    @objc func appEnterForeground(notification:Notification) {
        reloadData()
    }
    
    
    
    
    
    //MARK: - UI action 视图
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.addObserver(self, selector: #selector(appEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        self.addSubview(backView)
        
        backView.addSubview(topView)
        topView.addSubview(cancelButton)
        topView.addSubview(segmentBtn)
        backView.addSubview(listCollectView)
        
        
        cancelButton.snp.makeConstraints { (make) in
            make.leading.equalTo(topView.snp.leading).offset(16)
            make.centerY.equalTo(topView.snp.centerY)
            make.width.equalTo(56)
            make.height.equalTo(24)
        }
        

        segmentBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(40)
            make.width.equalTo(200)
        }
        
 
        listCollectView.snp.makeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom)
            make.leading.equalTo(backView.snp.leading)
            make.trailing.equalTo(backView.snp.trailing)
            make.bottom.equalTo(backView.snp.bottom)
            
        }
        
        let pstatus = PHPhotoLibrary.authorizationStatus(for: PHAccessLevel.readWrite)
        switch pstatus {
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization(for: PHAccessLevel.readWrite) {[weak self] status in
                DispatchQueue.main.async {
                    switch status {
                    case .authorized,.limited:
                        self?.reloadData()
                        break
                    default:
                        SVProgressHUD.showError(withStatus: NSLocalizedString("无法访问相册，请前往设置中开发访问授权", comment: ""))
                        break
                    }
                }
            }
            break
        case .restricted:
            break
        case .denied:
            SVProgressHUD.showError(withStatus: NSLocalizedString("无法访问相册，请前往设置中开发访问授权", comment: ""))
            break
        case .authorized,.limited:
            reloadData()
            break
        default:
            break
        }
    }
    
    
    @objc func cancelAction() {
        hide()
    }
    
    func hide() {
        UIView.animate(withDuration: 0.25, animations: { [self] in
            self.listCollectView.alpha = 0
            self.backView.frame = CGRect.init(x: 0, y: KScreenHeight + 10 , width: KScreenWidth, height: Back_Height)
        }) { (isFinished) in
            self.removeFromSuperview()
        }
    }
    
    func show() {
        UIView.animate(withDuration: 0.25, animations: {
            self.listCollectView.alpha = 1.0
            self.backView.frame = CGRect.init(x: 0, y: KScreenHeight - Back_Height, width: KScreenWidth, height: Back_Height)
        }) { (isFinished) in
            
            self.listCollectView.reloadData()
        }
    }
    
    @objc func filterAction(btn:UISegmentedControl) {
        print("xuan zhong ....\(btn.selectedSegmentIndex)")
        self.selectedFileType = SelectedFileType(rawValue: btn.selectedSegmentIndex)!
    }
    
    func listReloadData(){
        DispatchQueue.main.async {
            self.listCollectView.reloadData()
        }
    }
    
    //MARK: - Data action 数据
    func reloadData(){
        print("重新装载数据。。。")
        self.dataSource.removeAll()
        self.listCollectView.reloadData()
        loadMoreData(offset: 0)
    }
    
    func loadMoreData(offset:Int) {
        print("loadMoreData。。。")
        isLoadingMoreData = true
        let fetchResult_collection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.any, options: nil);
        //筛选空间相册
        var spatialAC:PHAssetCollection?
        fetchResult_collection.enumerateObjects { ac, index, stop in
            if ac.assetCollectionType == .smartAlbum ,
               ac.assetCollectionSubtype.rawValue == 1000000217{
                spatialAC = ac
                stop.pointee = true
            }
        }
        
        //从相册中再次筛选资产类型
        if let sac = spatialAC {
            let fetchOptions = PHFetchOptions()
            //ascending 为YES时，按照照片的创建时间升序排列;为NO时，则降序排列
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            if self.selectedFileType != .all {
                let predicate = NSPredicate(format: "mediaType = %d",
                                            self.selectedFileType.rawValue)
                fetchOptions.predicate = predicate
            }
            let fetchResult_asset = PHAsset.fetchAssets(in: sac, options: fetchOptions)
            guard offset < fetchResult_asset.count else {//确保筛选有数据
                self.isLoadingMoreData = false
                return
            }
            
            shouldLoadDataCount = min(fetchResult_asset.count - offset, filterLimit)
            var count = 0
            for i in offset ..< fetchResult_asset.count {
                let asset = fetchResult_asset.object(at: i)
                addImageFromAsset(asset: asset)
                count += 1
                if count >= filterLimit {
                    break
                }
            }
        }
        else {
            isLoadingMoreData = false
        }
        
        self.listCollectView.reloadData()
    }
    
    
    func addImageFromAsset(asset:PHAsset){
        //处理模型
        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = false//设置成同步回调
        requestOptions.deliveryMode = .highQualityFormat
        PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) {[weak self] data, dataUTI, imagePropertyOrientation, info in
            if let hasData = data {
                let photoImage:UIImage = UIImage(data: hasData)!
                //创建model
                let model = CCSpaceAlbumFliterModel.initWithAssetType(assetType: AssetType.init(rawValue: asset.mediaType.rawValue-1)!, asset: asset,image:photoImage, localIdentifier: asset.localIdentifier)
                self?.dataSource.append(model)
                self?.listReloadData()
                self?.shouldLoadDataCount = (self?.shouldLoadDataCount ?? 0) - 1
                if (self?.shouldLoadDataCount ?? 0) <= 0 {
                    self?.isLoadingMoreData = false
                }
                
            }
            
        }
    }
}



//MARK: - extension 扩展

extension CCSpaceAlbumFilterPopView2:UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let contentOffset = scrollView.contentOffset
        let contentSize = scrollView.contentSize
        let frameSize = scrollView.frame.size

        // 判断是否滑动到底部
        if contentOffset.y + frameSize.height >= contentSize.height {
            // 此时 collectionView 即将滑动到底部
            guard self.isLoadingMoreData == false else {
                print("正在加载中，等加载完毕在装载更多。。。。")
                return
            }
            self.loadMoreData(offset: self.dataSource.count)
        }
    }
    
  
    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AlbumIdentifierCell, for: indexPath) as! CCSpaceAlbumFliterCollectionCell
        
        
        let model:CCSpaceAlbumFliterModel = dataSource[indexPath.item]
//        let s = UIScreen.main.scale
//        cell.imageView.image = model.image?.preparingThumbnail(of: CGSize(width: cell.imageView.size.width*s, height: cell.imageView.size.height*s))
        
        cell.imageView.image = model.image
        if model.assetType == .image {

            cell.frameCountLabel.text = NSLocalizedString("空间", comment: "")
            cell.frameCountLabel.isHidden = true
            cell.timeLabel.isHidden = true
        }else if model.assetType == .video {
            
            let time:Double =  Double(model.itemAsset!.duration)
            let timeStr:String = ZZHHelper.formatVideoTime(second:Int(time))
            cell.frameCountLabel.isHidden = true
            cell.timeLabel.isHidden = false
            cell.timeLabel.text = timeStr
        }
        
        return cell
    }

    // MARK: - UICollectionViewDelegateFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (collectionView.bounds.width - 4)/3
        return CGSize(width: width, height: width)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let model:CCSpaceAlbumFliterModel = self.dataSource[indexPath.item]
        
        guard let asset = model.itemAsset else { return }
        //返回图片
        if asset.mediaType == .image {
            //选择的是图片
            let imageData = getImageData(for: asset)
            
            // 关闭
            if Thread.isMainThread {
//
                if let imageData = imageData {
                    self.selectedImageHandler?(imageData,asset)
                }
                self.hide()
            }else{
                DispatchQueue.main.async {
//
                    if let imageData = imageData {
                        self.selectedImageHandler?(imageData,asset)
                    }
                    self.hide()
                }
            }
        }else if asset.mediaType == .video {
            //选择的是video
            self.getVideoURL(from: asset) {[weak self] url,avasset in
                
                if Thread.isMainThread {
//
                    self?.selectedVideoHandler?(url,asset)
                    self?.hide()
                    
                }else{
                    DispatchQueue.main.async {
//
                        self?.selectedVideoHandler?(url,asset)
                        self?.hide()
                    }
                }
             }
        }
    }
    
    //MARK: - 获取图片data
    private func getImageData(for asset: PHAsset) -> Data? {
        var imageData: Data?
        if asset.mediaType == .image {
            let requestOptions = PHImageRequestOptions()
            requestOptions.isSynchronous = true//设置成同步回调
            requestOptions.deliveryMode = .highQualityFormat
            PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) { data, dataUTI, imagePropertyOrientation, info in
                imageData = data
            }
        }
        return imageData
    }
    
    private func getVideoURL(from asset: PHAsset, completion: @escaping (URL,AVURLAsset) -> Void) {
            if asset.mediaType == .video {
                let requestOptions = PHVideoRequestOptions()
                requestOptions.isNetworkAccessAllowed = true
                //异步的
                PHImageManager.default().requestAVAsset(forVideo: asset, options: requestOptions) { (avAsset, _, _) in
                    if let avAsset = avAsset as? AVURLAsset {
                        let mediaURL = avAsset.url
                        completion(mediaURL,avAsset)
                    }
                }
            } else {
                
            }
    }
}
