//
//  CCSpaceAlbumPopView.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/2/25.
//

import UIKit
import Photos
import ImageIO
import CoreFoundation
import UIKit
import Photos
import ImageIO
import CoreGraphics
import MobileCoreServices
import AVKit



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




private let Back_Height:CGFloat = KHZSize(700)


class CCSpaceAlbumPopView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var selectedFileType:SelectedFileType = .all
    
    var collectionView: UICollectionView!
    var fetchResult: PHFetchResult<PHAsset>!
    var photos: [UIImage] = []
    
    var selectedImageHandler: ((Data) -> Void)?
    var selectedVideoHandler: ((URL) -> Void)?
    
    lazy var menuView: CCPopMenuView = {
        //数据源（icon可不填）
        let popData = [/*(icon:"saoyisao",title:"扫一扫"),*/
                       (icon:"",title:"空间照片"),
                       (icon:"",title:"空间视频"),
                       (icon:"",title:"全部")]
        
        //设置参数
        let parameters:[CCPopMenuConfigure] = [
            .PopMenuTextColor(UIColor.white),
            .popMenuItemHeight(30),
            .PopMenuTextFont(KFont_Medium(10)),
            .PopMenuBackgroudColor(UIColor(hexString: "#383739"))
        ]
        
        
        //init  (test随机生成点位置，注意：arrow点是基于屏幕的位置)
        let pointOnScreen = filtersButton.convert(filtersButton.center, to: KWindow)
        let popMenu = CCPopMenuView(menuWidth: 90, arrow: pointOnScreen, datas: popData,configures: parameters)
        return popMenu
    }()
    
    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(KMain_Color, 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
    }()
    
    lazy var topLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.clear
        label.font = KFont_Medium(18)
        label.textColor = UIColor(hexString: "#ffffff")
        label.text = "空间相簿"
        return label
    }()
    
    lazy var filtersButton: UIButton = {
        let button = UIButton.init()
        button.backgroundColor = .green
        button.setImage(UIImage(named: "filters_button"), for: .normal)
//        button.setTitle("取消", for: .normal)
//        button.setTitleColor(KMain_Color, for: .normal)
//        button.titleLabel?.font = KFont_Medium(16)
//        button.contentHorizontalAlignment = .center
        button.addTarget(self, action: #selector(filtersButtonAction), for: .touchUpInside)
        
        return button
    }()
    
    
    let AlbumIdentifierCell: String = "CCSpaceAlbumCell"

    lazy var listCollectView:UICollectionView = {
        //1.流布局
        let collectionLayout = UICollectionViewFlowLayout()
        //2, 设置每个item的大小
        //        collectionLayout.itemSize = CGSize(width: KHZSize(48), height: KHZSize(24))
        //3.垂直和水平滚动
        collectionLayout.scrollDirection = .vertical
        
        //6.定义collectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionLayout)
        //7.注册collectionViewCell
        collectionView.register(CCSpaceAlbumCell.self, forCellWithReuseIdentifier: AlbumIdentifierCell)
        
        //10.设置代理
        collectionView.delegate = self
        collectionView.dataSource = self
        
        //11.设置分页效果
//        collectionView.isPagingEnabled = true
        
        //隐藏滑动条
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = UIColor.white
        return collectionView
    }()
    
    
    
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        self.addSubview(backView)
        
        backView.addSubview(topView)
        topView.addSubview(cancelButton)
        topView.addSubview(topLabel)
        topView.addSubview(filtersButton)
        
        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)
        }
        
        topLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(topView.snp.centerY)
            make.centerX.equalTo(topView.snp.centerX)
        }
        
        filtersButton.snp.makeConstraints { (make) in
            make.trailing.equalTo(topView.snp.trailing).offset(-16)
            make.centerY.equalTo(topView.snp.centerY)
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
        
        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)
            
        }
        
        fetchPhotos()
        show()
    }
    
    //MARK: - 显示/隐藏
    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()
        }
    }
    
    
    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()
        }
    }


    // PHAsset.fetchAssets(with: .image, options: fetchOptions)
    // PHAsset.fetchAssets(with: fetchOptions)
    func fetchPhotos() {
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        
        
        if selectedFileType == .image {
            fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        }else if selectedFileType == .video {
            fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
        }
        
        
        for index in 0..<fetchResult.count {
            let asset = fetchResult.object(at: index)
            
            
            if selectedFileType == .all {
                
            }else if selectedFileType == .image {
                
                if asset.mediaType == .image {
                    let imageData = getImageData(for: asset)
                    guard let image = UIImage(data: imageData!) else { return }
                    self.photos.append(image)
                }
                
            }else if selectedFileType == .video {
//                if asset.mediaType == .video {
//                    
//                    //获取视频第一帧画面 AVAsset
//                    let generator = AVAssetImageGenerator(asset: asset)
//                    generator.appliesPreferredTrackTransform = true
//                    var actualTime:CMTime = CMTimeMake(value: 0,timescale: 0)
//                    let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 1)
//                    let imageRef = try? generator.copyCGImage(at: time, actualTime: &actualTime)
//                    do {
//                        let image = UIImage(cgImage: imageRef)
//                        self.photos.append(image)
//                    }
//                    
//                }
            }
            
            
        }
        
        
    }
    
    //检查是否为空间视频
    func isSpatialVideo(asset: AVAsset) -> Bool {
            let metadata = asset.metadata(forFormat: AVMetadataFormat.quickTimeMetadata)
            let isSpatialVideo = metadata.contains { item in
                if let identifier = item.identifier?.rawValue {
                    return identifier == "mdta/com.apple.quicktime.spatial.format-version"
                }
                return false
            }
            return isSpatialVideo
    }

    func isSSVideo(asset:AVAsset)async throws->Bool{
        
        let userDataItems = try await asset.loadMetadata(for:.quickTimeMetadata)
        let spacialCharacteristics = userDataItems.filter { $0.identifier?.rawValue == "mdta/com.apple.quicktime.spatial.format-version" }
        if spacialCharacteristics.count == 0 {
            return false
        }
        return true
    }
    
    // MARK: - action
    @objc func cancelAction() {
        hide()
    }
    @objc func filtersButtonAction() {
        filtersButton.layoutIfNeeded()
        topView.layoutIfNeeded()
        
        menuView.show()
        
        //click
        menuView.didSelectMenuBlock = { [weak self](index:Int)->Void in
            print("block select \(index)")
            
            if index == 0 {
                //image
                self?.selectedFileType = .image
            }else if index == 1 {
                //video
                self?.selectedFileType = .video
            }else if index == 2 {
                //all
                self?.selectedFileType = .all
            }
            
//            fetchPhotos()
//            listCollectView.reloadData()
            
        }
    }
    

    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CCSpaceAlbumCell", for: indexPath) as! CCSpaceAlbumCell
        cell.imageView.image = photos[indexPath.item]
        
        let frameCount = getFrameCount(for: indexPath.item)
        cell.frameCountLabel.isHidden = frameCount <= 1
        cell.frameCountLabel.text = "\(frameCount)"
        
        
        
        
        // 获取选中的视频资源
        let asset = fetchResult.object(at: indexPath.item)
        //返回图片
        if asset.mediaType == .image {
            
        }else if asset.mediaType == .video {
            
        }
        
        
        
        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 asset = fetchResult.object(at: indexPath.item)
        //返回图片
        if asset.mediaType == .image {
            //选择的是图片
            let requestOptions = PHImageRequestOptions()
            requestOptions.isSynchronous = true
            requestOptions.deliveryMode = .highQualityFormat
            let imageData = self.getImageData(for: asset)
            // 关闭
            if Thread.isMainThread {
                self.hide()
                if let imageData = imageData {
                    self.selectedImageHandler?(imageData)
                }
            }else{
                DispatchQueue.main.async {
                    self.hide()
                    if let imageData = imageData {
                        self.selectedImageHandler?(imageData)
                    }
                }
            }
        }else if asset.mediaType == .video {
            //选择的是video
            self.getVideoURL(from: asset) { url in
                
                
                if Thread.isMainThread {
                    self.hide()
                        self.selectedVideoHandler?(url)
                    
                }else{
                    DispatchQueue.main.async {
                        self.hide()
                            self.selectedVideoHandler?(url)
                    }
                }
             }
        }
    }

    //MARK: - 获取视频url
    private func getVideoURL(from asset: PHAsset, completion: @escaping (URL) -> 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)
                    }
                }
            } else {
                
            }
    }
    
    //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().requestImageData(for: asset, options: requestOptions) { (data, _, _, _) in
            //            imageData = data
            //        }
            
            PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) { data, dataUTI, imagePropertyOrientation, info in
                imageData = data
            }
        }
        
        
        return imageData
    }
    
    
    //MARK: - 解析文件包含了几张图从而判断是否是空间图片
    private func getFrameCount(for index: Int) -> Int {
        let asset = fetchResult.object(at: index)
        if let imageData = getImageData(for: asset) {
            if let cgImageSource = CGImageSourceCreateWithData(imageData as CFData, nil) {
                return CGImageSourceGetCount(cgImageSource)
            }
        }
        return 0
    }
    
    
    
    
    func convertCGImageToCFData(cgImage: CGImage) -> CFData? {
        let data = CFDataCreateMutable(kCFAllocatorDefault, 0)
        
        if let data = data {
            if let destination = CGImageDestinationCreateWithData(data, kUTTypePNG, 1, nil) {
                CGImageDestinationAddImage(destination, cgImage, nil)
                CGImageDestinationFinalize(destination)
            }
        }
        
        return data
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}




class CCSpaceAlbumCell: 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 = .red
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 12)
        label.layer.cornerRadius = 8
        label.clipsToBounds = 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)
        
        imageView.translatesAutoresizingMaskIntoConstraints = false
        frameCountLabel.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)
        ])
    }
}
