//
//  ChargeInfoBackView.swift
//  PhoneManager
//
//  Created by edy on 2025/3/27.
//

import UIKit
import SnapKit
import AVKit
import Lottie

class ChargeInfoBackView:UIView {
    
    var model : ChargeDataModel?
    
    private var timer: Timer?
    
    lazy var videoPlayView:ChargeVideoPlayingView = {
        let sview:ChargeVideoPlayingView = ChargeVideoPlayingView(frame: self.bounds)
        return sview
    }()
    
    lazy var animationView:LottieAnimationView = {
        let animationView = LottieAnimationView(name: "DefaultChargeLight")
        animationView.frame = self.bounds
        animationView.loopMode = .loop
        return animationView
    }()
    
    let timeLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 72, weight: .bold)
        label.textColor = .white
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    let weekLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 20, weight: .regular)
        label.textColor = .white
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    
    let batteryLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 40, weight: .regular)
        label.textColor = .white
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    init(frame: CGRect,model:ChargeDataModel) {
        
        super.init(frame: frame)
        
        self.model = model
        
        setupUI()
        
        self.videoPlayView.playVideo(with: model.url)
        // 表示这个是一张图片
        if model.url == URL(""){
            self.videoPlayView.isHidden = true
            self.animationView.isHidden = false
            self.backgroundColor = .black
            self.animationView.play()
        }else {
            // 这是视频
            self.videoPlayView.isHidden = false
            self.animationView.isHidden = true
            self.videoPlayView.playVideo(with: model.url)
            self.backgroundColor = .clear
        }
        
        setupTimeUpdates()
        
        BatteryMonitorManager.shared.delegate = self
        
        BatteryMonitorManager.shared.startMonitoring()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
    
        
        self.addSubview(videoPlayView)
        
        self.addSubview(animationView)
        
        self.addSubview(timeLabel)
        
        self.addSubview(weekLabel)
        
        self.addSubview(batteryLabel)
    }
    
    func setupTimeUpdates() {
        // 初始更新
        updateTime()
        startTimer()
        
        // 监听系统时间变化通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(updateTime),
            name: UIApplication.significantTimeChangeNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(updateTime),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
        
    }
    
    func startTimer() {
        
        stopTimer()
        
        timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { [weak self] _ in
            self?.updateTime()
        }
    }
    
    func stopTimer() {
        
        timer?.invalidate()
        timer = nil
    }
    
    @objc func updateTime() {
        
        let text = timeFormatter()
        let attributedString = NSMutableAttributedString(string: text)
        
        // 设置前部文本样式（除最后2个字符外）
        let mainTextRange = NSRange(location: 0, length: max(text.count - 2, 0))
        if mainTextRange.length > 0 {
            attributedString.addAttribute(
                .font,
                value: UIFont.systemFont(ofSize: 72, weight: .regular),
                range: mainTextRange
            )
        }
        
        // 设置最后2个字符的样式
        let lastTwoRange = NSRange(location: max(text.count - 2, 0), length: min(2, text.count))
        if lastTwoRange.length > 0 {
            attributedString.addAttribute(
                .font,
                value: UIFont.systemFont(ofSize: 28, weight: .regular),
                range: lastTwoRange
            )
        }
        
        // 应用到UILabel
        DispatchQueue.main.async {
            self.timeLabel.attributedText = attributedString
            self.weekLabel.text = weekFormatter()
        }
    }
    
    func changeBattery(level:Float) {
        
        let text = String(format: "%.0f", (level * 100)) + "%"
        
        let attributedString = NSMutableAttributedString(string: text)
        
        // 设置前部文本样式（除最后2个字符外）
        let mainTextRange = NSRange(location: 0, length: max(text.count - 1, 0))
        if mainTextRange.length > 0 {
            attributedString.addAttribute(
                .font,
                value: UIFont.systemFont(ofSize: 40, weight: .regular),
                range: mainTextRange
            )
        }
        
        // 设置最后2个字符的样式
        let lastTwoRange = NSRange(location: max(text.count - 1, 0), length: min(1, text.count))
        if lastTwoRange.length > 0 {
            attributedString.addAttribute(
                .font,
                value: UIFont.systemFont(ofSize: 24, weight: .regular),
                range: lastTwoRange
            )
        }
        
        // 应用到UILabel
        DispatchQueue.main.async {
            self.batteryLabel.attributedText = attributedString
        }
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        videoPlayView.snp.makeConstraints { make in
            
            make.centerX.width.height.equalToSuperview()
        }
        
        timeLabel.snp.makeConstraints { make in
            
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 76)
        }
        
        weekLabel.sizeToFit()
        
        weekLabel.snp.makeConstraints { make in
            
            make.centerX.equalToSuperview()
            make.top.equalTo(timeLabel.snp.bottom)
        }
        
        batteryLabel.snp.makeConstraints { make in
            
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-(safeHeight + 76))
        }
    }
    
    deinit {
        stopTimer()
        BatteryMonitorManager.shared.stopMonitoring()
        NotificationCenter.default.removeObserver(self)
        Print("deinit")
    }
}

extension ChargeInfoBackView:BatteryStatusDelegate {
    
    
    func batteryStatusDidUpdate(level: Float, state: UIDevice.BatteryState) {
        
        changeBattery(level: level)
    }
    
    
    
}
