//
//  HomeCollectionViewHeader.swift
//  PhoneManager
//
//  Created by edy on 2025/4/24.
//

import Foundation


class HomeCollectionViewHeader : UICollectionReusableView {
    
    
    var cleanNowButtonCallback : () -> Void = {}
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    lazy var progressBar : CustomProgressBar = {
        let bar = CustomProgressBar()
        return bar
    }()
    
    lazy var permissionView : PMPermissionView = {
        let view = Bundle.main.loadNibNamed("PMPermissionView", owner: nil, options: nil)?.last as! PMPermissionView
        view.isHidden = true
        return view
    }()
    
    private lazy var tipLabel:UILabel = {
        let label = UILabel()
        label.numberOfLines = 0 // 支持多行
        return label
    }()
    
    
    private func setupUI() {

        // 文本
        self.addSubview(self.tipLabel)
        self.tipLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.top.equalToSuperview().offset(44)
            make.height.equalTo(17)
        }
        self.addSubview(self.progressBar)
        self.progressBar.snp.makeConstraints { make in
            make.top.equalTo(self.snp.top).offset(12 + 44 + 17)
            make.width.equalToSuperview().offset(-16)
            make.height.equalTo(31)
            make.left.equalToSuperview().offset(8)
        }
        
        self.addSubview(self.permissionView)
        self.permissionView.snp.makeConstraints { make in
            make.top.equalTo(progressBar.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(-22)
            make.right.equalToSuperview().offset(22)
            make.height.equalTo(340)
        }
        
        
        // 设置是否显示权限页
        setNoPermissionHeaderPage()

    }
    
}

extension HomeCollectionViewHeader{
    /// 设置头部权限UI是否显示
    func setNoPermissionHeaderPage(){
        DispatchQueue.main.async {
            if PhotoManager.shared.permissionStatus == .authorized {
                self.permissionView.isHidden = true
            }else {
                self.setFileAndCount(count: 0, fileSize: 0)
                self.permissionView.isHidden = false
            }
        }
    }
    
    
    /// 设置头部视图文件数量和大小
    /// - Parameters:
    ///   - count: 文件数量
    ///   - fileSize: 文件总大小
    func setFileAndCount(count:Int,fileSize:Double) -> NSMutableAttributedString {
        
        let countString = "\(count)"
        let fileSizeString = formatFileSize(fileSize)
        
        let text = countString + " files · " + fileSizeString + " of storage to clean up"
        let attributedText = NSMutableAttributedString(string: text)
        
        // 设置整体文本样式
        let fullTextAttributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 14, weight: .regular),
            .foregroundColor: UIColor(red: 0.4, green: 0.4, blue: 0.4,alpha:1)
        ]
        attributedText.addAttributes(fullTextAttributes, range: NSRange(location: 0, length: text.count))
        
        // 设置 "202" 为蓝色
        if let range1 = text.range(of: countString) {
            let nsRange1 = NSRange(range1, in: text)
            attributedText.addAttributes([
                .foregroundColor: UIColor.colorWithHex(hexStr: mColor),
                .font:UIFont.systemFont(ofSize: 14, weight: .semibold)
            ], range: nsRange1)
        }
        
        // 设置 "1.15 GB" 为蓝色
        if let range2 = text.range(of: fileSizeString) {
            let nsRange2 = NSRange(range2, in: text)
            attributedText.addAttributes([
                .font:UIFont.systemFont(ofSize: 14, weight: .semibold),
                .foregroundColor: UIColor.colorWithHex(hexStr: mColor)
            ], range: nsRange2)
        }
        return attributedText
        // 将 attributedText 赋值给 UILabel
//        self.tipLabel.attributedText = attributedText
    }
}




// MARK: - 进度条
class CustomProgressBar: UIView {
    private let progressLayer = CALayer()
    private let usedColor = UIColor(hex: "#0082FF") ?? .blue
    private let chaoticColor = UIColor(hex: "#FFAE00") ?? .yellow
    private let idleColor = UIColor(hex: "#FFFFFF") ?? .white
    
    private let usedLabel = UILabel()
    private let chaoticLabel = UILabel()
    private let idleLabel = UILabel()
    
    private let dotSize: CGFloat = 8
    private let labelSpacing: CGFloat = 18
    
    // 添加防抖计时器
    private var updateTimer: Timer?
    // 缓存上一次的进度值，用于动画
    private var lastUsedProgress: CGFloat = 0
    private var lastChaoticProgress: CGFloat = 0
    
    var usedProgress: CGFloat = 0 {
        didSet {
            scheduleProgressUpdate()
        }
    }
    
    var totalProgress: CGFloat = 0
    
    var chaoticProgress: CGFloat = 0 {
        didSet {
            guard chaoticProgress != oldValue else{
                return
            }
            scheduleProgressUpdate()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        let disk = WidgetPublicModel.getDiskSpace()
        self.totalProgress = Double(disk.0)
        self.usedProgress = Double(disk.0) - Double(disk.1)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        
        layer.addSublayer(progressLayer)
        
        
        usedLabel.text = "Used"
        usedLabel.font = UIFont.systemFont(ofSize: 12)
        usedLabel.textColor = UIColor.colorWithHex(hexStr: black6Color)
        addSubview(usedLabel)
        
        chaoticLabel.text = "Chaotic content"
        chaoticLabel.font = UIFont.systemFont(ofSize: 12)
        chaoticLabel.textColor = UIColor.colorWithHex(hexStr: black6Color)
        addSubview(chaoticLabel)
        
        idleLabel.text = "Idle"
        idleLabel.font = UIFont.systemFont(ofSize: 12)
        idleLabel.textColor = UIColor.colorWithHex(hexStr: black6Color)
        addSubview(idleLabel)
        
        progressLayer.frame = CGRect(x: 0, y: 0, width: ScreenW-48, height: 10)
        progressLayer.cornerRadius = 5
        progressLayer.masksToBounds = true
        updateProgress()
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
       
      //  updateProgress()
        
        let dotY = progressLayer.frame.maxY + 9
        let usedDotX = bounds.minX
        let chaoticDotX = usedDotX + usedLabel.intrinsicContentSize.width + dotSize + labelSpacing
        let idleDotX = chaoticDotX + chaoticLabel.intrinsicContentSize.width + dotSize + labelSpacing
        
        drawDot(at: CGPoint(x: usedDotX, y: dotY), color: usedColor)
        usedLabel.frame = CGRect(x: usedDotX + dotSize + 5, y: 0, width: usedLabel.intrinsicContentSize.width, height: usedLabel.intrinsicContentSize.height)
        usedLabel.centerY = dotY + 4
        
        drawDot(at: CGPoint(x: chaoticDotX, y: dotY), color: chaoticColor)
        chaoticLabel.frame = CGRect(x: chaoticDotX + dotSize + 5, y: 0, width: chaoticLabel.intrinsicContentSize.width, height: chaoticLabel.intrinsicContentSize.height)
        chaoticLabel.centerY = dotY + 4
        
        drawDot(at: CGPoint(x: idleDotX, y: dotY), color: idleColor)
        idleLabel.frame = CGRect(x: idleDotX + dotSize + 5, y: 0, width: idleLabel.intrinsicContentSize.width, height: idleLabel.intrinsicContentSize.height)
        idleLabel.centerY = dotY + 4
    }
    
    private func scheduleProgressUpdate() {
        // 取消之前的计时器
//        updateTimer?.invalidate()
//        // 设置新的计时器，延迟0.2秒更新UI
//        updateTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { [weak self] _ in
//            self?.updateProgress()
//        }
        updateProgress()
    }
    
    private func updateProgress() {
        // 确保在主线程更新UI
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            
            // 计算总容量和各部分比例
            let total = max(self.totalProgress + self.chaoticProgress, 0.001) // 避免除以0
            let usedRatio = min(max(self.usedProgress / total, 0), 1)
            let chaoticRatio = min(max(self.chaoticProgress / total, 0), 1)
            
            // 计算实际宽度
            let usedWidth = (ScreenW-48) * usedRatio
            let chaoticWidth = (ScreenW-48) * chaoticRatio
            
            // 设置进度条背景为白色
            self.progressLayer.backgroundColor = self.idleColor.cgColor
            
            // 更新或创建used层
            let usedLayer = self.progressLayer.sublayers?.first as? CALayer ?? CALayer()
            usedLayer.frame = CGRect(x: 0, y: 0, width: usedWidth, height: 10)
            usedLayer.backgroundColor = self.usedColor.cgColor
            
            // 更新或创建chaotic层
            let chaoticLayer = self.progressLayer.sublayers?[safe: 1] as? CALayer ?? CALayer()
            chaoticLayer.frame = CGRect(x: usedWidth, y: 0, width: chaoticWidth, height: 10)
            chaoticLayer.backgroundColor = self.chaoticColor.cgColor
            
            // 一次性设置所有子层
            if self.progressLayer.sublayers == nil {
                self.progressLayer.sublayers = [usedLayer, chaoticLayer]
            }
        }
    }
    
    private func drawDot(at point: CGPoint, color: UIColor) {
        let dotLayer = CAShapeLayer()
        let dotPath = UIBezierPath(ovalIn: CGRect(x: point.x, y: point.y, width: dotSize, height: dotSize))
        dotLayer.path = dotPath.cgPath
        dotLayer.fillColor = color.cgColor
        layer.addSublayer(dotLayer)
    }
}

// 添加安全数组访问扩展
private extension Array {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
