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

import Foundation
import UIKit
import Photos

private let Back_Height:CGFloat = KHZSize(700)

class CCSpaceAlbumFilterPopView2: UIView {
    var selectedImageHandler: ((Data,PHAsset) -> Void)?
    var selectedVideoHandler: ((URL,PHAsset) -> Void)?
    var selectedFileType:SelectedFileType = .all {
        didSet{
            filterOffset = 0
            reloadData()
        }
    }
    
    var dataSource:[CCSpaceAlbumFliterModel] = []
    var filterOffset = 0//筛选内容的当前下标
    let filterLimit = 80//一次性获取的内容数量
    
    
    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("取消", for: .normal)
        button.setTitleColor(UIColor(red: 165.0/255, green: 137.0/255, blue: 1, alpha: 1), for: .normal)
        button.titleLabel?.font = 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: ["全部","图片","视频"])
        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;
        return sbtn
    }()
    
    
    
    
    //MARK: - 释放销毁
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: - 通知 进入前台
    @objc func appEnterForeground(notification:Notification) {
        
    }
    
    
    
    
    
    //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(32)
            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)
            
        }
        
        reloadData()
    }
    
    
    @objc func cancelAction() {
        hide()
    }
    
    func hide() {
        UIView.animate(withDuration: 0.5, 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.5, 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()
        loadMoreData(offset: filterOffset)
    }
    
    func loadMoreData(offset:Int) {
        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 format = "mediaType=%d"
//                let mt = PHAssetMediaType.init(rawValue: self.selectedFileType.rawValue)!
//                fetchOptions.predicate = NSPredicate(format: format,
//                                                     argumentArray: [mt])
//            }
            let fetchResult_asset = PHAsset.fetchAssets(in: sac, options: fetchOptions)
            var count = 0
            switch self.selectedFileType {
            case .all:
                for i in offset ..< fetchResult_asset.count {
                    let asset = fetchResult_asset.object(at: i)
                    addImageFromAsset(asset: asset)
                    count += 1
                    if count >= filterLimit {
                        break
                    }
                }
                break
            case .image:
                for i in offset ..< fetchResult_asset.count {
                    let asset = fetchResult_asset.object(at: i)
                    if asset.mediaType == .image {
                        addImageFromAsset(asset: asset)
                        count += 1
                        if count >= filterLimit {
                            break
                        }
                    }
                    
                }
                break
            case .video:
                for i in offset ..< fetchResult_asset.count {
                    let asset = fetchResult_asset.object(at: i)
                    if asset.mediaType == .video {
                        addImageFromAsset(asset: asset)
                        count += 1
                        if count >= filterLimit {
                            break
                        }
                    }
                    
                }
                break
            }
            
        }
        
        self.listCollectView.reloadData()
    }
    
    
    func addImageFromAsset(asset:PHAsset){
        //处理模型
        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = false//设置成同步回调
        requestOptions.deliveryMode = .highQualityFormat
        print("asset mediatype:\(asset.mediaType)")
        PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) {[weak self] data, dataUTI, imagePropertyOrientation, info in
            let photoImage:UIImage = UIImage(data: data!)!
            //创建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()
        }
    }
}



//MARK: - extension 扩展

extension CCSpaceAlbumFilterPopView2:UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    
    // MARK: - 把秒数转换成时分秒（00:00:00）格式
    ///
    /// - Parameter second: 秒数
    /// - Returns: String
    func transToHourMinSec(second: Int) -> String {
        let allTime: Int = second
        var hours = 0
        var minutes = 0
        var seconds = 0
        var hoursText = ""
        var minutesText = ""
        var secondsText = ""
        
        hours = allTime / 3600
        hoursText = hours > 9 ? "\(hours)" : "0\(hours)"
        
        minutes = allTime % 3600 / 60
        minutesText = minutes > 9 ? "\(minutes)" : "0\(minutes)"
        
        seconds = allTime % 3600 % 60
        secondsText = seconds > 9 ? "\(seconds)" : "0\(seconds)"
        
        if hoursText == "00" {
            return "\(minutesText):\(secondsText)"
        }else{
            return "\(hoursText):\(minutesText):\(secondsText)"
        }
        
        
    }
    
    
    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 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]
        
        cell.imageView.image = model.image
        
        if model.assetType == .image {

            cell.frameCountLabel.text = "空间"
            cell.frameCountLabel.isHidden = false
            cell.timeLabel.isHidden = true
        }else if model.assetType == .video {
            
            let time:Double =  Double(model.itemAsset!.duration)
//            let timeStr:String = ZZHHelper.formatVideoTime(second:Int(time))
            let timeStr:String = self.transToHourMinSec(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 {
//                self.hide()
                if let imageData = imageData {
                    self.selectedImageHandler?(imageData,asset)
                }
            }else{
                DispatchQueue.main.async {
//                    self.hide()
                    if let imageData = imageData {
                        self.selectedImageHandler?(imageData,asset)
                    }
                }
            }
        }else if asset.mediaType == .video {
            //选择的是video
            self.getVideoURL(from: asset) { url,avasset in
                
                if Thread.isMainThread {
//                    self.hide()
                        self.selectedVideoHandler?(url,asset)
                    
                }else{
                    DispatchQueue.main.async {
//                        self.hide()
                            self.selectedVideoHandler?(url,asset)
                    }
                }
             }
        }
    }
    
    //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
            }
        }
        
        print(".....:\(imageData)")
        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 {
                
            }
    }
}
