//
//  YHDashLineView.swift
//  galaxy
//
//  Created by alexzzw on 2024/10/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHDashLineView: UIView {
    private var strokeColor: CGColor = UIColor(hex: 0x121A26, alpha: 0.12).cgColor
    private var lineWidth: CGFloat = 1
    private var lineDashPattern: [NSNumber] = [2, 2]
    private var isHorizontal: Bool = true
    
    init(strokeColor: CGColor = UIColor(hex: 0x121A26, alpha: 0.12).cgColor, lineWidth: CGFloat = 1, lineDashPattern: [NSNumber] = [2, 2], isHorizontal: Bool = true) {
        self.strokeColor = strokeColor
        self.lineWidth = lineWidth
        self.lineDashPattern = lineDashPattern
        self.isHorizontal = isHorizontal
        super.init(frame: CGRect.zero)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 移除之前的层，避免重复添加
        layer.sublayers?.filter { $0 is CAShapeLayer }.forEach { $0.removeFromSuperlayer() }
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = strokeColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineDashPattern = lineDashPattern // 实线长度，间隔长度
        
        let path = CGMutablePath()
        if isHorizontal {
            path.move(to: CGPoint(x: 0, y: bounds.midY))
            path.addLine(to: CGPoint(x: bounds.width, y: bounds.midY))
        } else {
            path.move(to: CGPoint(x: bounds.midX, y: 0)) // 从顶部中间开始
            path.addLine(to: CGPoint(x: bounds.midX, y: bounds.height)) // 到底部中间结束
        }
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)
    }
}
