//
//  Lunch_ProgressView.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/3/27.
//

import UIKit

class MP_Lunch_ProgressView: UIView {
    // 渐变层
    private var gradientLayer: CAGradientLayer!
    // 进度条层（作为渐变层的遮罩）
    private var progressLayer: CALayer!
    
    // 当前进度 (0.0 - 1.0)
    var progress: CGFloat = 0.0 {
        didSet {
            updateProgressLayer()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupGradientLayer()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupGradientLayer()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 保证子图层的尺寸和视图尺寸一致
        gradientLayer.frame = self.bounds
        updateProgressLayer()
    }
    
    private func setupGradientLayer() {
        backgroundColor = .init(hex: "#FFFFFF",alpha: 0.1)
        // 初始化并设置渐变层
        gradientLayer = CAGradientLayer()
        gradientLayer.colors = [
            UIColor(red: 0.109, green: 0.784, blue: 0.932, alpha: 1).cgColor,
            UIColor(red: 0.412, green: 0.996, blue: 0.451, alpha: 1).cgColor,
            UIColor(red: 0.796, green: 0.839, blue: 0.294, alpha: 1).cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        layer.addSublayer(gradientLayer)
        
        // 初始化进度条层并设置为渐变层的遮罩
        progressLayer = CALayer()
        progressLayer.backgroundColor = UIColor.white.cgColor // 颜色可以是任意的，因为这个图层只是用来作为形状遮罩
        gradientLayer.mask = progressLayer
    }
    
    private func updateProgressLayer() {
        // 根据当前进度和视图的宽度调整进度条层的大小
        let progressWidth = self.bounds.width * progress
        progressLayer.frame = CGRect(x: 0, y: 0, width: progressWidth, height: self.bounds.height)
    }
    
    // 当需要设置进度时，调用此方法
    func setProgress(_ progress: CGFloat, animated: Bool = false) {
        self.progress = min(max(progress, 0.0), 1.0) // 确保进度值在有效范围内
        if animated {
            let animation = CABasicAnimation(keyPath: "bounds.size.width")
            animation.toValue = self.bounds.width * self.progress
            animation.duration = 0 // 动画持续时间
            animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            animation.fillMode = .forwards
            animation.isRemovedOnCompletion = false
            progressLayer.add(animation, forKey: "progressWidth")
        }
    }
}

