//
//  ZZHCustomSlider..swift
//  SwiftProject
//
//  Created by aaa on 2024/4/17.
//

import Foundation
import UIKit
typealias CustomSliderProcessChangeValueCallback =  (_ currentValue:Float,_ isMoving:Bool)->Void
class ZZHCustomSlider: UIView {
    
    var sHeight:CGFloat?
    var sLabel:UILabel?
    var eLabel:UILabel?
    var timeSlider:CustomSlider?
    
    var processChangeValueCallback:CustomSliderProcessChangeValueCallback?
    var preValue:Float = 0.0 //更新进度前的value
    var totalSec:Int = -1//代表视频总时长
    let bgView:UIView = UIView()
    
    deinit {
        print("zzhcustomslider....deinit...")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        self.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalTo(38)
        }
        
        timeSlider = CustomSlider()
        timeSlider?.isUserInteractionEnabled = false
        bgView.addSubview(timeSlider!)
        timeSlider!.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
        }
        
        sLabel = UILabel()
        bgView.addSubview(sLabel!)
        eLabel = UILabel()
        bgView.addSubview(eLabel!)
        sLabel?.snp.makeConstraints({ make in
            make.left.equalTo(timeSlider!.snp.left)
            make.top.equalTo(timeSlider!.snp.bottom).offset(20)
            make.bottom.equalToSuperview()
        })
        
        eLabel?.snp.makeConstraints({ make in
            make.right.equalTo(timeSlider!.snp.right)
            make.top.equalTo(sLabel!.snp.top)
            make.bottom.equalTo(sLabel!.snp.bottom)
            
        })
        
        sLabel?.font = UIFont.systemFont(ofSize: 14)
        eLabel?.font = UIFont.systemFont(ofSize: 14)
        
        sLabel?.textColor = .white
        eLabel?.textColor = .white
        
        sLabel?.text = "--:--:--"
        eLabel?.text = "--:--:--"
        timeSlider?.setThumbImage(UIImage(named: "slider_thumb"), for: .normal)
        timeSlider?.minimumTrackTintColor = .white
        timeSlider?.maximumTrackTintColor = UIColor(r: 20, g: 20, b: 20, a: 0.8)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //内部拖动更新当前滑块value:0~1
    func updateProcessValue(value:Float,isMoving:Bool) {
        self.timeSlider!.value = value
        guard let processChangeValueCallback else {
            return
        }
        
        if isMoving {
            var currentValue = max(0, min(value, 1))
            //格式化为0.x
            let formattedValue = String(format: "%.2f", currentValue)
            currentValue = Float(formattedValue)!
            //保证相邻2次的值不同才有必要去触发进度的改变
            if currentValue > preValue || currentValue < preValue {
                preValue = currentValue
                processChangeValueCallback(preValue,isMoving)
                if self.totalSec > 0 {//已经获取到总时长的情况下再去更新起始位置的时间文本值
                    self.sLabel?.text = ZZHHelper.formatVideoTime(second: Int(preValue*Float(self.totalSec)))
                }
            }
        }
        else {
            processChangeValueCallback(preValue,isMoving)
        }
        
    }
    
    //外部播放时的更新当前滑块
    func exUpdateProcessValue(value:Float,currSec:Int,totalSec:Int) {
        self.totalSec = totalSec
        self.sLabel?.text = ZZHHelper.formatVideoTime(second: currSec)
        self.eLabel?.text = ZZHHelper.formatVideoTime(second: totalSec)
        let formattedValue = String(format: "%.1f", value)
        let rv = Float(formattedValue)!
        self.timeSlider!.setValue(value, animated: false)
        preValue = rv
    }
    

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if timeSlider!.isNormal == true {
            timeSlider!.isNormal = false
            sHeight = self.bgView.height
            self.updateSliderHeight(height: (self.sHeight)! + 5)
        }
        let touch = touches.first
        if let th = touch {
            let touchPoint = th.location(in: self.timeSlider!)
            
            updateProcessValue(value: Float(touchPoint.x / self.timeSlider!.frame.size.width),isMoving: true)
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        if timeSlider!.isNormal == false {
            timeSlider!.isNormal = true
            self.updateSliderHeight(height: (self.sHeight)!)
        }
        
        updateProcessValue(value: preValue,isMoving: false)
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        if timeSlider!.isNormal == false {
            timeSlider!.isNormal = true
            self.updateSliderHeight(height: (self.sHeight)!)
        }
        updateProcessValue(value: preValue,isMoving: false)
    }
    
    
    func updateSliderHeight(height:CGFloat) {
        UIView.animate(withDuration: 0.25) {[weak self] in
            self?.bgView.snp.updateConstraints {make in
                make.height.equalTo(height)
            }
            self?.layoutIfNeeded()
        } completion: { finish in
            
        }
    }
    
}



class CustomSlider: UISlider {
    var isNormal:Bool = true {
        didSet {
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    
    override func trackRect(forBounds bounds: CGRect) -> CGRect {
        var rect = super.trackRect(forBounds: bounds)
        if isNormal == true {
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 8)
        }
        else {
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 10)
        }
        return rect
    }
    
    
//    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
//        var nb = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
//        nb = CGRectMake(nb.origin.x, nb.origin.y, 1, 1)
//        return nb
//    }
    
    
}














//底部自定义的参数调节视图
typealias CCSliderCallback = (_ value:Float,_ isMoving:Bool)->Void
class CCSlider: UIView{
    var preValue:Float = 0.0 //更新进度前的value
    var callback:CCSliderCallback?
    var slider:CustomSlider?
    var sHeight:CGFloat = 0.0
    override init(frame: CGRect) {
        super.init(frame: frame)
        slider = CustomSlider()
        slider?.isUserInteractionEnabled = false
        self.addSubview(slider!)
        slider!.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
        slider?.setThumbImage(UIImage(named: "slider_thumb"), for: .normal)
        slider?.minimumTrackTintColor = .white
        slider?.maximumTrackTintColor = UIColor(r: 20, g: 20, b: 20, a: 0.8)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if slider!.isNormal == true {
            slider!.isNormal = false
            sHeight = self.height
            self.updateSliderHeight(height: self.sHeight + 5)
        }
        let touch = touches.first
        if let th = touch {
            let touchPoint = th.location(in: self.slider!)
            
            updateProcessValue(value: Float(touchPoint.x / self.slider!.frame.size.width),isMoving: true)
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        if slider!.isNormal == false {
            slider!.isNormal = true
            self.updateSliderHeight(height: self.sHeight)
        }
        
        updateProcessValue(value: preValue,isMoving: false)
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        if slider!.isNormal == false {
            slider!.isNormal = true
            self.updateSliderHeight(height: self.sHeight)
        }
        updateProcessValue(value: preValue,isMoving: false)
    }
    
    
    func updateSliderHeight(height:CGFloat) {
        UIView.animate(withDuration: 0.25) {[weak self] in
            self?.snp.updateConstraints {make in
                make.height.equalTo(height)
            }
            self?.superview?.layoutIfNeeded()
        } completion: { finish in
            
        }
    }
    
    func updateProcessValue(value:Float,isMoving:Bool) {
        self.slider!.value = value
        guard let callback else {
            return
        }
        var currentValue = max(0, min(value, 1))

        preValue = currentValue
        callback(preValue,isMoving)
    
    }
    
    
}

















typealias CustomParamBoardViewScaleCallback = (_ scale:CGFloat)->Void
typealias CustomParamBoardViewEDCallback = (_ ed:Int)->Void
typealias CustomParamBoardViewResetCallback = ()->Void
typealias CustomParamBoardViewDismissCallback = ()->Void
class CustomParamBoardView: UIView {
    
    var scaleCallback:CustomParamBoardViewScaleCallback?
    var edCallback:CustomParamBoardViewEDCallback?
    var resetCallback:CustomParamBoardViewResetCallback?
    var dismissCallback:CustomParamBoardViewDismissCallback?
    var scaleSlider:CCSlider?
    var scaleTitleLabel:UILabel?
    
    var edSlider:CCSlider?
    var edTitleLabel:UILabel?
    
    let bgViewHeight = 400
    lazy var bgView:UIView = {
       let bg = UIView()
        bg.backgroundColor = UIColor(r: 28, g: 28, b: 28, a: 1)
        bg.layer.cornerRadius = 12
        bg.layer.masksToBounds = true
        
        let titleLabel = UILabel()
        titleLabel.text = NSLocalizedString("v1.6_参数设置", comment: "")
        titleLabel.textColor = .white
        titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
        bg.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(12)
        }
        
        let resetBtn = UIButton()
        bg.addSubview(resetBtn)
        resetBtn.addTarget(self, action: #selector(resetParams(sender: )), for: .touchUpInside)
        resetBtn.snp.makeConstraints { make in
            make.width.height.equalTo(26)
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.right.equalToSuperview().offset(-20)
        }
        resetBtn.setImage(UIImage(named: "custom_refresh"), for: .normal)
        return bg
    }()
    
    let superBgView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        let tgrBgView = UIView()
        self.addSubview(tgrBgView)
        tgrBgView.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
        self.addSubview(superBgView)
        self.superBgView.snp.makeConstraints { make in
            make.height.equalTo(170)
            make.width.equalTo(330)
            make.bottom.equalToSuperview().offset(bgViewHeight)
            make.centerX.equalToSuperview()
        }
        self.superBgView.backgroundColor = .clear
//        let blackBgView = UIView()
//        self.addSubview(blackBgView)
        
        
        self.superBgView.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
        
        scaleTitleLabel = UILabel()
        superBgView.addSubview(scaleTitleLabel!)
        scaleTitleLabel?.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(50)
        }
        scaleTitleLabel?.textColor = .white
        scaleTitleLabel?.font = UIFont.systemFont(ofSize: 14)
        scaleTitleLabel?.text = "缩放:100%"
        scaleSlider = CCSlider(frame: .zero)
        scaleSlider?.callback = {[weak self] (value,isMoving) in //scale不能小于0.5
            if isMoving {
                if(self?.scaleSlider?.tag == 0) {
                    self?.scaleSlider?.tag = 1
                    self?.hiddenOther(slider: self?.edSlider, titleLabel: self?.edTitleLabel)
                }
            }
            else {
                self?.scaleSlider?.tag = 0
                self?.showAll()
            }
            self?.updateScaleTitleWithValue(value:value)
            
            
        }
        superBgView.addSubview(scaleSlider!)
        scaleSlider!.snp.makeConstraints { make in
            make.left.equalTo(scaleTitleLabel!.snp.left)
            make.top.equalTo(scaleTitleLabel!.snp.bottom).offset(-1)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(30)
        }
        
        
        
        edTitleLabel = UILabel()
        superBgView.addSubview(edTitleLabel!)
        edTitleLabel?.snp.makeConstraints { make in
            make.left.equalTo(scaleTitleLabel!.snp.left)
            make.top.equalTo(scaleSlider!.snp.bottom).offset(10)
        }
        edTitleLabel?.textColor = .white
        edTitleLabel?.font = UIFont.systemFont(ofSize: 14)
        edTitleLabel?.text = "瞳距:10mm"
        
        edSlider = CCSlider(frame: .zero)
        edSlider?.callback = {[weak self] (value,isMoving) in
            if isMoving {
                if(self?.edSlider?.tag == 0) {
                    self?.edSlider?.tag = 1
                    self?.hiddenOther(slider: self?.scaleSlider, titleLabel: self?.scaleTitleLabel)
                }
            }
            else {
                self?.edSlider?.tag = 0
                self?.showAll()
            }
            
            self?.updateEDTitleLabelWith(value:value)
        }
        superBgView.addSubview(edSlider!)
        edSlider!.snp.makeConstraints { make in
            make.left.equalTo(edTitleLabel!.snp.left)
            make.top.equalTo(edTitleLabel!.snp.bottom).offset(-1)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(30)
        }
        
        
        
        
        
        
        let tgr = UITapGestureRecognizer(target: self, action: #selector(hidenView(sender: )))
        tgrBgView.addGestureRecognizer(tgr)
    }
    
    //更新缩放的标题文本
    func updateScaleTitleWithValue(value:Float) {
        let minValue = 0.3
        let maxValue = 1.8
        let resultValue = minValue + (maxValue - minValue) * Double(value)
        let formattedValue = String(format: "\(NSLocalizedString("v1.6_缩放", comment: ""))%.f%%", (resultValue) * 100)
        self.scaleTitleLabel?.text = formattedValue
        if let scaleCallback = self.scaleCallback {
            scaleCallback(CGFloat(resultValue))
        }
    }
    
    //提供给它的类方法调用
    func exUpdateScaleTitleWithValue(resultValue:CGFloat) {
        let formattedValue = String(format: "\(NSLocalizedString("v1.6_缩放", comment: ""))%.f%%", (resultValue) * 100)
        self.scaleTitleLabel?.text = formattedValue
        let minValue = 0.3
        let maxValue = 1.8
//        let resultValue = minValue + (maxValue - minValue) * Double(value)
        let v = (resultValue - minValue) / (maxValue - minValue)
        self.scaleSlider?.slider?.value = Float(v)
    }
    
    //更新瞳距的标题文本
    func updateEDTitleLabelWith(value:Float)  {
        let currED = Int(60 * (value - 0.5))
        if let edCallback = self.edCallback {
            edCallback(Int(currED))
        }
        let formattedValue = String(format: "\(NSLocalizedString("v1.6_瞳距", comment: ""))%dmm", currED)
        self.edTitleLabel?.text = formattedValue
    }
    
    func exUpdateEDTitleLabelWith(currED:Int)  {
        let formattedValue = String(format: "\(NSLocalizedString("v1.6_瞳距", comment: ""))%dmm", currED)
        self.edTitleLabel?.text = formattedValue
        let v =  Float(currED) * 1.0 / 30.0 + 0.5
        self.edSlider?.slider?.value = v
    }
    
    
    
    
    func hiddenOther(slider:CCSlider?,titleLabel:UILabel?) {
        UIView.animate(withDuration: 0.25) {[weak self] in
            slider?.alpha = 0
            titleLabel?.alpha = 0
            self?.bgView.alpha = 0
        } completion: { finish in
            
        }
    }
    
    func showAll() {
        UIView.animate(withDuration: 0.25) {[weak self] in
            self?.scaleSlider?.alpha = 1
            self?.scaleTitleLabel?.alpha = 1
            self?.edSlider?.alpha = 1
            self?.edTitleLabel?.alpha = 1
            self?.bgView.alpha = 1
        } completion: { finish in
            
        }
    }
    
    //dismiss
    @objc func hidenView(sender:UITapGestureRecognizer) {
        if let dismissCallback = self.dismissCallback {
            dismissCallback()
        }
        
        UIView.animate(withDuration: 0.25) {[weak self] in
            self?.superBgView.snp.updateConstraints({ make in
                make.bottom.equalToSuperview().offset(self?.bgViewHeight ?? 400)
            })
            self?.layoutIfNeeded()
            
        } completion: { finish in
            self.removeFromSuperview()
        }

    }
    
    class func showBoard(scaleCallback:@escaping CustomParamBoardViewScaleCallback,edCallback:@escaping CustomParamBoardViewEDCallback,resetCallback:@escaping CustomParamBoardViewResetCallback,dismissCallback:@escaping CustomParamBoardViewDismissCallback,scale:CGFloat,ed:Int) {
        let view = CustomParamBoardView(frame: .zero)
        view.scaleCallback = scaleCallback
        view.edCallback = edCallback
        view.resetCallback = resetCallback
        view.dismissCallback = dismissCallback
        view.exUpdateEDTitleLabelWith(currED: ed)
        view.exUpdateScaleTitleWithValue(resultValue: scale)
        KWindow?.addSubview(view)
        view.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
        KWindow?.layoutIfNeeded()
        UIView.animate(withDuration: 0.25) {
            view.superBgView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(-30)
            }
            view.layoutIfNeeded()
        } completion: { finish in
            
        }

    }
    
    //重置
    @objc func resetParams(sender:UIButton)  {
        if let rc = self.resetCallback {
            rc()
            exUpdateScaleTitleWithValue(resultValue: 1.0)
            exUpdateEDTitleLabelWith(currED: 0)
        }
    }
    
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
