//
//  CustomProgressBar.swift
//  PhoneManager
//
//  Created by edy on 2025/5/21.
//

import UIKit

class CustomCompressProgressBar: UIView {
    
    var animationCompletion: (() -> Void) = {}
    
    // 背景色（已完成进度颜色）
    private let backgroundLayer = CALayer()
    // 前景色（已完成进度颜色）
    private let foregroundLayer = CALayer()
    // 进度指示图标
    private let thumbLayer = CALayer()
    // 当前进度值（0-1）
    private var progress: CGFloat = 0.0
    // 动画持续时间
    private let animationDuration: CFTimeInterval = 4.0
    // 动画定时器
    private var displayLink: CADisplayLink?
    private var animationStartTime: CFTimeInterval = 0
    private var startProgress: CGFloat = 0
    private var targetProgress: CGFloat = 0
    
    var thumbImage: UIImage? {
        didSet {
            thumbLayer.contents = thumbImage?.cgImage
            // 调整缩略图锚点
            thumbLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            // 设置正确尺寸并居中
            thumbLayer.frame = CGRect(
                x: 0,
                y: bounds.height/2 - 12,  // 24/2=12
                width: 24,
                height: 24
            )
        }
    }
    
    // 添加视图配置防止裁剪
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        self.clipsToBounds = false
        layer.masksToBounds = false
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    private func setup() {
        // 设置背景层
        backgroundLayer.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor
        backgroundLayer.frame = CGRect(x: 0, y: self.bounds.height/2 - 3.5, width: self.bounds.width, height: 7)
        backgroundLayer.cornerRadius = 3.5
        layer.addSublayer(backgroundLayer)
        
        // 设置前景层
        foregroundLayer.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1).cgColor
        foregroundLayer.cornerRadius = 3.5
        layer.addSublayer(foregroundLayer)
        
        // 设置缩略图层
        layer.addSublayer(thumbLayer)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        updateLayers(for: progress)
        CATransaction.commit()
    }
    
    func updateProgress(to newProgress: CGFloat) {
        let clampedProgress = max(0, min(newProgress, 1.0))
        startProgress = currentPresentationProgress()
        targetProgress = clampedProgress
        startAnimation()
    }
    
    private func currentPresentationProgress() -> CGFloat {
        if let presentation = foregroundLayer.presentation() {
            return presentation.bounds.width / bounds.width
        }
        return progress
    }
    
    private func startAnimation() {
        animationStartTime = CACurrentMediaTime()
        displayLink?.invalidate()
        displayLink = CADisplayLink(target: self, selector: #selector(updateAnimation))
        displayLink?.add(to: .main, forMode: .common)
    }
    
    @objc private func updateAnimation() {
        let elapsed = CACurrentMediaTime() - animationStartTime
        let percent = min(elapsed / animationDuration, 1.0)
        
        let currentProgress = startProgress + (targetProgress - startProgress) * CGFloat(percent)
        progress = currentProgress
        
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        updateLayers(for: currentProgress)
        CATransaction.commit()
        
        if percent >= 1.0 {
            displayLink?.invalidate()
            displayLink = nil
            // 触发完成回调
            animationCompletion()
        }
    }
    
    private func updateLayers(for progress: CGFloat) {
        let foregroundWidth = bounds.width * progress
        foregroundLayer.frame = CGRect(
            x: 0,
            y: bounds.height/2 - 3.5,
            width: foregroundWidth,
            height: 7
        )
        
        // 修改缩略图位置计算
        let thumbSize = thumbLayer.bounds.size
        // 计算中心点位置（确保始终显示完整缩略图）
        let thumbCenterX = foregroundWidth - thumbSize.width/2
        
        // 限制缩略图显示范围（不超出进度条边界）
        let minX = -thumbSize.width/2  // 允许左侧部分超出
        let maxX = bounds.width - thumbSize.width/2
        thumbLayer.frame.origin.x = max(minX, min(thumbCenterX, maxX))
        
        // 设置垂直居中
        thumbLayer.frame.origin.y = bounds.height/2 - thumbSize.height/2
    }
}
