import UIKit
import Photos
import AVFoundation

class HomeOtherCollectionCell: UICollectionViewCell {
    
    
    var similarFlag : Bool = false
    
    // 图片-0，视频-1，截图-2
    var mediaType : Int = 0
    
    // MARK: - Properties
    static let identifier = "HomeOtherCollectionCellID"
    
    public let imageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.layer.cornerRadius = 12
        iv.backgroundColor = .clear
        return iv
    }()
    
    private let infoBackView: UIView = {
        let iv = UIView()
        iv.clipsToBounds = true
        iv.layer.cornerRadius = 12
        iv.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
        return iv
    }()
    
    
    public var countLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 14, weight: .bold)
        label.textAlignment = .left
        return label
    }()
    
    let sizeLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 10, weight: .regular)
        label.textAlignment = .left
        return label
    }()
    
    private let moreImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.image = UIImage(named: "icon_left_setting_grey")
        iv.backgroundColor = .clear
        return iv
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 18, weight: .semibold)
        label.textColor = UIColor.colorWithHex(hexStr: black3Color)
        label.textAlignment = .left
        label.numberOfLines = 0
        return label
    }()
    
    var playImageView : UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.image = UIImage(named: "btn_play_home")
        iv.backgroundColor = .clear
        return iv
    }()
    
    lazy var playerView: SecretVideoPlayer = {
        let play = SecretVideoPlayer()
        play.isUserInteractionEnabled = false
        play.fromState = .home
        play.Radius = 16
        play.contentMode = .scaleAspectFill
        play.isLooping = true
        return play
    }()
    
    // MARK: - Lifecycle
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: Notification.Name("applicationDidBecomeActive"), object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    private func setupUI() {
        backgroundColor = .white
        self.contentView.addSubview(self.titleLabel)
        self.contentView.addSubview(self.imageView)
        self.contentView.addSubview(self.playerView)
        self.contentView.addSubview(self.playImageView)
        
        self.playerView.addSubview(self.infoBackView)
        self.infoBackView.addSubview(self.countLabel)
        self.infoBackView.addSubview(self.sizeLabel)
        self.infoBackView.addSubview(self.moreImageView)
    }
    
    @objc private func didBecomeActive() -> Void {
        self.playerView.resume()
    }
    
    var firstID:String?
    
    var model:HomePhotosModel? {
        
        didSet {
            
//            guard let model else {return}
//            
//            // 设置标题
//            self.titleLabel.text = model.folderName
//            // 获取数量
//            var count = 0
//            for item in model.assets {
//                count = count + item.count
//            }
//            // 设置数量文字
//            if self.mediaType == 0 || self.mediaType == 2{
//                self.countLabel.text = "\(count) Photos"
//            }else{
//                self.countLabel.text = "\(count) Videos"
//            }
//            // 设置文件大小文字
//            let sizeKB : Double = model.allFileSize/1000
//            if sizeKB < 1000{
//                self.sizeLabel.text = String(format: "(%.2lf) KB" ,sizeKB)
//            }else if sizeKB < (1000 * 1000) && sizeKB > 1000{
//                self.sizeLabel.text = String(format: "(%.2lf) MB" ,sizeKB/1000)
//            }else{
//                self.sizeLabel.text = String(format: "(%.2lf) GB" ,sizeKB/(1000 * 1000))
//            }
            
        
            //let currentImageView = imageView
//            
//            guard let firstLocalIdentifier = model.firstLocalIdentifier else{
//                return
//            }
//            
           // let tempImage = imageView
            
//            PhotoManager.shared.getImage(localIdentifier:firstLocalIdentifier, completion: { image in
//               // guard let weakSelf = self else { return }
//                tempImage.image = image
//            })
            
           // if self.mediaType == 0 || self.mediaType == 2 {}
            
            
            
            
//            DispatchQueue.main.async {
//                // 设置标题
//                self.titleLabel.text = model.folderName
//                // 获取数量
//                var count = 0
//                for item in model.assets {
//                    count = count + item.count
//                }
//                // 设置数量文字
//                if self.mediaType == 0 || self.mediaType == 2{
//                    self.countLabel.text = "\(count) Photos"
//                }else{
//                    self.countLabel.text = "\(count) Videos"
//                }
//                // 设置文件大小文字
//                let sizeKB : Double = model.allFileSize/1000
//                if sizeKB < 1000{
//                    self.sizeLabel.text = String(format: "(%.2lf) KB" ,sizeKB)
//                }else if sizeKB < (1000 * 1000) && sizeKB > 1000{
//                    self.sizeLabel.text = String(format: "(%.2lf) MB" ,sizeKB/1000)
//                }else{
//                    self.sizeLabel.text = String(format: "(%.2lf) GB" ,sizeKB/(1000 * 1000))
//                }
//            }
            
            
//            guard let asset = model.assets.first?.first else {
//                DispatchQueue.main.async {
//                    if self.mediaType == 0 {
//                        self.imageView.image = UIImage(named: "othermoren")
//                    }else if self.mediaType == 2 {
//                        self.imageView.image = UIImage(named: "photosmoren")
//                    } else{
//                        self.imageView.image = UIImage(named: "videosmoren")
//                    }
//                }
//                return
//            }
//            if self.mediaType == 0 || self.mediaType == 2 {
//                let image = PhotoAndVideoMananger.mananger.getImageFromAssetID(id: asset.localIdentifier)
//                DispatchQueue.main.async {[weak self] in
//                    guard let self else {return}
//                    imageView.image = image
//                }
//            }else{
//                
//                // 定义请求选项来获取视频的第一帧
//                let options = PHImageRequestOptions()
//                // 获取当前版本的照片或视频
//                options.version = .current
//                // 尽可能快地提供结果
//                options.deliveryMode = .highQualityFormat
//                // 允许从iCloud请求
//                options.isNetworkAccessAllowed = true
//                // 异步请求
//                options.isSynchronous = false
//                // 从 PHAsset 获取 AVAsset
//                if let videoAsset = PhotoAndVideoMananger.mananger.getPHAsssetwithID(ids: [asset.localIdentifier]){
//                    // 使用requestImageForAsset方法请求视频的第一帧图片
//                    
//                    let options = PHVideoRequestOptions()
//                       options.version = .current
//                       options.deliveryMode = .automatic // 根据需求调整视频质量:ml-citation{ref="2,7" data="citationList"}
//                       
//                       PHImageManager.default().requestAVAsset(
//                        forVideo: videoAsset,
//                           options: options
//                       ) { (avAsset, audioMix, info) in
//                           guard let avAsset = avAsset as? AVURLAsset else { return }
//                           let videoURL = avAsset.url
//                           print("视频地址: \(videoURL)")
//                           DispatchQueue.main.async {
//                               self.playerView.playVideo(from: videoURL)
//                           }
//                       }
////                    PHImageManager.default().requestImage(for: videoAsset, targetSize: CGSize(width: 400, height: 400), contentMode: PHImageContentMode.aspectFit, options: options) { image, _ in
////                        // 处理获取到的图片
////                        if let thumbnailImage = image {
////                            // 使用获取到的图片，例如显示在UIImageView上
////                            DispatchQueue.main.async {
////                                // 确保在主线程更新UI
////                                self.imageView.image = thumbnailImage
////                            }
////                        } else {
////                            self.imageView.image = UIImage(named: "img_vedio_defpage")
////                            print("无法获取图片")
////                        }
////                    }
//                }
//            }
        }
        
    }
    
    func reloadUIWithModel(model:HomePhotosModel?){
        
        guard let model else {return}
        
        // 设置标题
        self.titleLabel.text = model.folderName
        // 获取数量
        var count = 0
        for item in model.assets {
            count = count + item.count
        }
        // 设置数量文字
        if self.mediaType == 0 || self.mediaType == 2{
            self.countLabel.text = "\(count) Photos"
        }else{
            self.countLabel.text = "\(count) Videos"
        }
        // 设置文件大小文字
        let sizeKB : Double = model.allFileSize/1000
        if sizeKB < 1000{
            self.sizeLabel.text = String(format: "(%.2lf) KB" ,sizeKB)
        }else if sizeKB < (1000 * 1000) && sizeKB > 1000{
            self.sizeLabel.text = String(format: "(%.2lf) MB" ,sizeKB/1000)
        }else{
            self.sizeLabel.text = String(format: "(%.2lf) GB" ,sizeKB/(1000 * 1000))
        }
        
        let placeImage = self.mediaType == 0 ? "othermoren" : self.mediaType == 2 ? "photosmoren" : "videosmoren"
        if let id = model.assets.first?.first?.localIdentifier{
            imageView.asset.load(withLocalIdentifier:id,placeholder: UIImage(named: placeImage))
        }else{

            self.imageView.image = UIImage.init(named: placeImage)
        }
    }
    
    
    func setCoverImageOrVideo(image:UIImage?){
        
        if image == nil{
            if self.mediaType == 0 {
                self.imageView.image = UIImage(named: "othermoren")
            }else if self.mediaType == 2 {
                self.imageView.image = UIImage(named: "photosmoren")
            } else{
                self.imageView.image = UIImage(named: "videosmoren")
            }
        }else{
            imageView.image = image
        }
        
    }
    
    func dealMediaType(_ row:Int){
        if row == 0 ||  row == 3{
            mediaType = 1
            playImageView.isHidden = false
        }else if row == 1 || row == 2{
            mediaType = 2
            playImageView.isHidden = true
        }else{
            mediaType = 0
            playImageView.isHidden = true
        }
    }
    
    // MARK: - Configuration
    func configure(with image: UIImage?, count: Int, size: String) {
        imageView.image = image
        countLabel.text = "\(count) Photos"
        sizeLabel.text = "(\(size)) MB"
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
        countLabel.text = "0 Photos"
        sizeLabel.text = "(0.0) MB"
    }
    
    override func layoutSubviews() {
        
        self.layer.cornerRadius = 12
        self.layer.masksToBounds = true
        
        imageView.snp.makeConstraints { make in
            make.top.equalTo(self.titleLabel.snp.bottom).offset(8)
            make.left.equalToSuperview().offset(8)
            make.width.equalToSuperview().offset(-16)
            make.height.equalTo(self.width - 16)
        }
        
        self.infoBackView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(40)
        }
        self.playImageView.snp.makeConstraints { make in
            make.width.height.equalTo(43)
            make.center.equalTo(self.imageView.snp.center)
        }
        self.playerView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(imageView)
        }
        
        titleLabel.snp.makeConstraints { make in
            
            make.left.top.equalToSuperview().offset(8)
            make.width.equalToSuperview().offset(-16)
        }
        
        self.countLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.top.equalToSuperview().offset(3)
            make.height.equalTo(20)
        }
        self.sizeLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.top.equalTo(countLabel.snp.bottom).offset(-2)
            make.height.equalTo(14)
        }
        self.moreImageView.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.left.equalTo(countLabel.snp.right).offset(7)
            make.centerY.equalToSuperview()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name("applicationDidBecomeActive"), object: nil)
    }
    
}
