//
//  HomeVideoCoverCell.swift
//  PhoneManager
//
//  Created by edy on 2025/5/20.
//

import UIKit
import AVKit

class HomeVideoCoverCell: UICollectionViewCell {
    
    var videoUrl:URL?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .white
        self.contentView.addSubview(self.titleLabel)
        self.contentView.addSubview(self.imageView)

        contentView.layer.addSublayer(playerLayer)
        self.contentView.addSubview(self.infoBackView)
        self.infoBackView.addSubview(self.countLabel)
        self.infoBackView.addSubview(self.sizeLabel)
        self.infoBackView.addSubview(self.moreImageView)
    }
    
    func reloadUIWithModel(model:HomePhotosModel?){
        // 1. 先重置状态
        guard let model else {
            playerLayer.isHidden = true
            videoPlayer.pause()
            return
        }
        
        // 设置标题
        self.titleLabel.text = model.folderName
        // 获取数量
        var count = 0
        for item in model.assets {
            count = count + item.count
        }
        // 设置数量文字
        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))
        }
        
        if videoPlayer.rate == 0,videoPlayer.currentItem != nil{
            videoPlayer.seek(to: .zero)
            videoPlayer.play()
        }
        
        
        // 2. 设置新数据
        if let id = model.assets.first?.first?.localIdentifier{
            // 保存当前的 identifier 用于验证
            let currentID = id
            imageView.asset.load(withLocalIdentifier:id,placeholder: UIImage(named: "videosmoren"))
            PhotoManager.shared.getVideoURL(localIdentifier:id, completion: {[weak self] url in
                guard let weakSelf = self else { return }
                // 验证 ID 是否匹配，避免 cell 重用导致的错误
                if currentID == id {
                    weakSelf.configure(with: url)
                }
            })
            
        }else{
            self.imageView.image = UIImage.init(named: "videosmoren")
            playerLayer.isHidden = true
            videoPlayer.pause()
        }
    }
    
    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
    }()
    
    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.equalTo(imageView)
            make.height.equalTo(40)
        }

        
        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()
        }
        
        playerLayer.frame = imageView.frame
        playerLayer.cornerRadius = 8
        playerLayer.masksToBounds = true
    }

    
    lazy var videoPlayer:AVPlayer = {
        let palyer = AVPlayer.init()
        palyer.volume = 0
        palyer.isMuted = true
        // 设置音频会话，允许混音
        try? AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
        try? AVAudioSession.sharedInstance().setActive(true)
        return palyer
    }()
    
    lazy var playerLayer:AVPlayerLayer = {
        let playerLayer = AVPlayerLayer.init(player: videoPlayer)
        playerLayer.backgroundColor = UIColor.black.cgColor
        playerLayer.isHidden = true
        return playerLayer
    }()
    
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
   
}


extension HomeVideoCoverCell{
    
    
    func configure(with videoURL: URL?) {
        
        guard let videoURL = videoURL else{
            playerLayer.isHidden = true
            videoPlayer.pause()
            return
        }
        playerLayer.isHidden = false
    
        if videoURL == videoUrl{
          //  Print("地址相同，无需刷新")
            return
        }
        videoUrl = videoURL
        
        let item = AVPlayerItem.init(url: videoURL)
        
        
        videoPlayer.replaceCurrentItem(with: item)
        
        videoPlayer.play()

        NotificationCenter.default.addObserver(self,
                                             selector: #selector(playerDidFinishPlaying),
                                             name: .AVPlayerItemDidPlayToEndTime,
                                             object: item)
    }

    @objc private func playerDidFinishPlaying() {

        videoPlayer.seek(to: .zero)
        videoPlayer.play()
    }

    


}
