//
//  VideoPlayingView.swift
//  PhoneManager
//
//  Created by edy on 2025/4/7.
//

import Foundation
import UIKit
import AVKit

class ChargeVideoPlayingView: UIView {
    private var player: AVPlayer?
    private var playerLayer: AVPlayerLayer?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    private func setupView() {
        backgroundColor = .black
    }

    func playVideo(with url: URL) {
        
        // 对 URL 字符串进行编码处理
        guard let encodedURLString = url.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            print("URL 编码失败")
            return
        }
        // 将编码后的字符串转换为 URL 对象
        guard URL(string: encodedURLString) != nil else {
            print("无法创建编码后的 URL")
            return
        }
        
        self.player = AVPlayer(url: url)
        self.player?.volume = 0
        self.player?.isMuted = true
        self.playerLayer = AVPlayerLayer(player: self.player)
        self.playerLayer?.frame = self.bounds
        
        self.layer.addSublayer(playerLayer!)

        // 监听视频加载状态
        player?.addObserver(self, forKeyPath: "status", options: [.new, .old], context: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)

        player?.play()
    }

    @objc private func playerDidFinishPlaying() {
        player?.seek(to: CMTime.zero)
        player?.play()
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == "status" {
                if let status = player?.status {
                    switch status {
                    case .readyToPlay:
                        break
                    case .failed:
                        if let error = player?.error {
                            print("视频播放失败: \(error.localizedDescription)")
                        }
                    case .unknown:
                        print("视频状态未知")
                    @unknown default:
                        break
                    }
                }
            }
        }

    deinit {
        NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
    }
}
