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

import UIKit

class MP_Lunch_ProgressView: UIView {
    struct Constant {
        //进度条宽度
        static let lineWidth: CGFloat = 6*width
        //进度槽颜色
        static let trackColor:UIColor = .init(hex: "#FFFFFF")
        //进度条颜色
        static let progressColors:[CGColor] = [
                                               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
        ]
    }
    //渐变层
    private var gradientLayer:CAGradientLayer!
    //进度槽
    private var trackLayer:CAShapeLayer!
    //进度条路径（水平线）
    private var path:UIBezierPath!
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpLayers()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setUpLayers()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    override func draw(_ rect: CGRect) {
        //初始化圆角矩形路径
        path = UIBezierPath()
        //获取起点
        let startPoint = CGPoint(x: bounds.minX, y: bounds.maxY)
        //获取终点
        let endPoint = CGPoint(x: bounds.maxX, y: bounds.maxY)
        //路径起始点
        path.move(to: startPoint)
        //增加路线
        path.addLine(to: endPoint)
        //初始化进度槽
        trackLayer = .init()
        //路径宽
        trackLayer.lineWidth = bounds.height
        trackLayer.fillColor = UIColor.clear.cgColor
        //路径颜色
        trackLayer.strokeColor = Constant.trackColor.cgColor
        //设置起始点
        trackLayer.strokeStart = 0
        //设置当前点
        trackLayer.strokeEnd = 0
        //路径端口为圆形
        trackLayer.lineCap = .round
        trackLayer.path = path.cgPath
        layer.addSublayer(trackLayer)
        //初始化渐变色进度条
        gradientLayer = .init()
        //渐变层大小
        gradientLayer.frame = .init(x: 0, y: -2, width: bounds.size.width, height: bounds.size.height+1)
//        gradientLayer.shadowPath = trackLayer.path
        //渐变层颜色
        gradientLayer.colors = Constant.progressColors
        //渐变层起始点
        gradientLayer.startPoint = .init(x: 0, y: 1)
        //渐变层终点
        gradientLayer.endPoint = .init(x: 1, y: 1)
        layer.addSublayer(gradientLayer)
        //渐变层遮罩
        gradientLayer.mask = trackLayer
    }
    //layer添加
    private func setUpLayers() {
        backgroundColor = .init(hex: "#FFFFFF", alpha: 0.15)
    }
    /// 渐变色执行方法
    /// - Parameter progress: 进度值
    func setProgress(_ progress: CGFloat) {
        if progress <= 1 {
            //进度条动画
            trackLayer.strokeEnd = progress
        }
    }
}
