//
//  PQSpeedSettingView.swift
//  BFFramework
//
//  Created by ak on 2021/8/2.
//  功能：设置快慢速 跳越卡点 的倍速 VIEW

import Foundation
class PQSpeedSettingView: UIView {
    // 速度列表
    lazy var titleCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .horizontal

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)

        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(PQSpeedTitleCell.self, forCellWithReuseIdentifier: String(describing: PQSpeedTitleCell.self))
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        // 延迟scrollView上子视图的响应，所以当直接拖动UISlider时，如果此时touch时间在150ms以内，UIScrollView会认为是拖动自己，从而拦截了event，导致UISlider接收不到滑动的event
        collectionView.delaysContentTouches = false
        return collectionView
    }()

    // 保存数据
    var datas: Array<PQSpeedTitleModel> = Array()
    var lastSelectModel: PQSpeedTitleModel?
    // view 初化的类型 1, 快慢速度卡点  2，跳跃卡点 ,3,循环设置
    var viewType: Int = 0 {
        didSet {
            
            if(viewType == oldValue){
                return
            }
            
            titleCollectionView.snp.remakeConstraints { make in
                make.right.equalToSuperview()
                make.width.equalToSuperview()
                make.height.equalTo(viewType == 1 ? 44 : 30)
                make.top.equalToSuperview()
            }
            datas.removeAll()
            if viewType == 1 {
                let tempTitle =
                    ["1.0x\n0.2x",
                     "1.8x\n0.3x",
                     "2.4x\n0.4x",
                     "3.0x\n0.5x",
                     "5.0x\n1.0x",
                     "6.0x\n1.2x",
                     "自定义\n快慢速"]
                
                let tempMaxSpeed = [1.0,   1.8,   2.4,   3, 5, 6, 0.0]
                let tempMinSpeed = [0.2,   0.3,  0.4,0.5,1.0,1.2, 0.0]
                for (index, str) in tempTitle.enumerated() {
                    let model = PQSpeedTitleModel()
                    model.title = str
                    model.maxSpeed = Float(tempMaxSpeed[index])
                    model.minSpeed = Float(tempMinSpeed[index])
                    datas.append(model)
                }

            } else {
                let str:String = (viewType == 2) ? "跳跃" : "循环"
                let tempTitle =
                    ["\(str)1x",
                     "2x",
                     "3x",
                     "4x",
                     "5x",
                     "自定义"]
                let tempMaxSpeed = [1, 2, 3, 4, 5, 0]
                for (index, str) in tempTitle.enumerated() {
                    let model = PQSpeedTitleModel()
                    model.title = str
                    model.maxSpeed = Float(tempMaxSpeed[index])
                    datas.append(model)
                }
            }
            //如果有老数据先插入 补位
            if viewType == 3 && insertModle != nil{
                datas.insert(insertModle!, at: 5)
            }
            if(lastSelectModel != nil){
                selectCustom()
            }else{
                titleCollectionView.reloadData()
            }

        }
    }
    
    //上一次插入的倍速数据
    var insertModle:PQSpeedTitleModel?

    // 点击回调 maxSpeed,minSpeed 同时为0 说明点击的是自定义速度
    public var selectSpeedCallBack: ((_ maxSpeed: Float, _ minSpeed: Float,_ selectIndex:Int,_ isSettingPlayer:Bool) -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(titleCollectionView)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    deinit {
        BFLog(1, message: "speed setting view release")
    }
    //设置默认选择的
    /// - Parameters:
    ///   - index: index: 第几位 从0 开始
    ///   - isSettingPlayer: 是否重启播放器
    ///   - setEnable: 设置不可用状态
    ///   - enableInsert: 是否插入一组新数据，只有第一次 < 10s 设置为 true ,自定义及其它情况都不设置 true

    func setSelectItem(index:Int,isSettingPlayer:Bool = true,setDisable:Bool = false,isCancle:Bool = false,enableInsert:Bool = false) {
       BFLog(message: "setSelectItem is \(index)")
        if(index < 0 ){
            BFLog(message: "选择位置数据出错\(index)")
            return
        }
        //设置不可用状态
        if(setDisable){
            for (i,model) in datas.enumerated() {
                model.isDisable = i == index ? false: true
            }
        }
        lastSelectModel?.isSelected = false
       
        if viewType == 3{
            if(index > 4 && datas.count < 7 && enableInsert){
                if(index >= datas.count - 1){
                    let model = PQSpeedTitleModel()
                    model.title = "\(index + 1)x"
                    model.maxSpeed = Float(index + 1)
                    insertModle = model
                    datas.insert(insertModle!, at: 5)
                    lastSelectModel = datas[5]
                }else{
                    lastSelectModel = datas[index]
                }
         
            }else{
                if(index > datas.count){
                    lastSelectModel?.isSelected = true
                    titleCollectionView.reloadData()

                    return
                }
                lastSelectModel = datas[index]
            }
        }else{
            lastSelectModel = datas[index]
        }
        lastSelectModel?.isSelected = true
        titleCollectionView.reloadData()
 
        
        //发出回调，调用方走统一处理逻辑
        if selectSpeedCallBack != nil {
            BFLog(message: "选择的速度为 max: \(lastSelectModel?.maxSpeed ?? 0.0) min: \(lastSelectModel?.minSpeed ?? 0.0) title  \(lastSelectModel?.title ?? "")")
      
                
            let lastSelectIndex = datas.firstIndex(where: { (model) -> Bool in
                (model.maxSpeed == lastSelectModel?.maxSpeed)
            }) ?? 0

            selectSpeedCallBack!(lastSelectModel?.maxSpeed ?? 0.0, lastSelectModel?.minSpeed ?? 0.0,lastSelectIndex,isSettingPlayer)
       
 
        }
    }
    
    //选中自定义
    func selectCustom() {
        
        lastSelectModel?.isSelected = false
        lastSelectModel = datas.last
        lastSelectModel?.isSelected = true
        titleCollectionView.reloadData()
         
    }
}

extension PQSpeedSettingView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return datas.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PQSpeedTitleCell.self), for: indexPath) as! PQSpeedTitleCell

        cell.titleModel = datas[indexPath.row]
        return cell
    }

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        BFLog(message: "选择了 \(String(describing: datas[indexPath.row]))")
        if(datas[indexPath.row].isDisable){
            BFLog(message: "不可用速度")
            cShowHUB(superView: nil, msg: "素材时长需要大于6秒\n   才可选择其他档位")
            return
        }
        
        if(datas[indexPath.row].title == "自定义" || datas[indexPath.row].title == "自定义\n快慢速"){
            selectSpeedCallBack!(-1,-1,indexPath.row, false)
        }else{
        
            setSelectItem(index: indexPath.row)
        }
        //下面只是统计  //1, 快慢速度卡点  2，跳跃卡点 ,3,循环设置
        if(viewType == 1){
            
            if(datas[indexPath.row].title == "自定义" || datas[indexPath.row].title == "自定义\n快慢速"){
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_customizeSpeed, pageSource: .sp_stuck_previewSyncedUp, extParams:nil, remindmsg: "")
            }else{
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectSpeed, pageSource: .sp_stuck_previewSyncedUp, extParams:nil, remindmsg: "")
            }
        }else if(viewType == 2){
           
            if(datas[indexPath.row].title == "自定义" || datas[indexPath.row].title == "自定义\n快慢速"){
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_customizeRatio, pageSource: .sp_stuck_previewSyncedUp, extParams:nil, remindmsg: "")
            }else{
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectRatio, pageSource: .sp_stuck_previewSyncedUp, extParams:nil, remindmsg: "")
            }
     
        }else if(viewType == 3){
            if(datas[indexPath.row].title == "自定义" || datas[indexPath.row].title == "自定义\n快慢速"){
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_customizeRepeatTimes, pageSource: .sp_stuck_previewSyncedUp, extParams:nil, remindmsg: "")
            }else{
                PQEventTrackViewModel.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shanyinApp_musicVideoPreview_selectRepeatTimes, pageSource: .sp_stuck_previewSyncedUp, extParams:nil, remindmsg: "")
            }
        }
 
    }

    func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 20  是 cell label 上下边距总和
        if viewType == 1 {
            if indexPath.row == datas.count - 1 {
                return CGSize(width: 65, height: 44)
            }
            return CGSize(width: 44 + 10, height: 24 + 20)
        } else {
            if indexPath.row == 0 || indexPath.row == datas.count - 1 {
                return CGSize(width: 60 + 10, height: 30)
            }
            return CGSize(width: 30 + 10, height: 30)
        }
    }
}

class PQSpeedTitleModel: NSObject {
    // UI 上显示的文字
    var title: String = ""
    // 是否已经选择
    var isSelected: Bool = false

    // 最大、最小速度
    var maxSpeed: Float = 0.0
    var minSpeed: Float = 0.0
    //是否可用
    var isDisable:Bool = false
    public override init() {
        super.init()
    }
}

class PQSpeedTitleCell: UICollectionViewCell {
    lazy var titleLab: UILabel = {
        let titleLab = UILabel()
        titleLab.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        titleLab.textColor = UIColor.hexColor(hexadecimal: "#959595")
        titleLab.numberOfLines = 0
        titleLab.lineBreakMode = .byCharWrapping
        titleLab.isUserInteractionEnabled = true
        titleLab.textAlignment = .center
        titleLab.addCorner(corner: 5)

        return titleLab
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(titleLab)
        titleLab.snp.remakeConstraints { make in
            make.height.equalToSuperview()
            make.width.equalToSuperview().offset(-10)
            make.left.equalToSuperview()
            make.top.equalToSuperview()
        }
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var titleModel: PQSpeedTitleModel? {
        didSet {
            titleLab.text = titleModel?.title

            titleLab.snp.remakeConstraints { make in
                make.height.equalToSuperview()
                make.width.equalToSuperview().offset(-10)
                make.left.equalToSuperview()
                make.top.equalToSuperview()
            }

            if titleModel?.isSelected ?? false {
            
                let styleColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
                titleLab.backgroundColor = UIColor(red: styleColor.rgbaf[0], green: styleColor.rgbaf[1], blue: styleColor.rgbaf[2], alpha: 0.15)
                titleLab.textColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
                
                titleLab.font = UIFont.boldSystemFont(ofSize: 13)

            } else {
                if(titleModel?.isDisable ?? false){
                    
                    let backColor = PQBFConfig.shared.pointEditNamalBackgroundColor
                    let textColor = UIColor.hexColor(hexadecimal: "#959595")
                    titleLab.backgroundColor = UIColor.init(red: backColor.rgbaf[0], green: backColor.rgbaf[1], blue: backColor.rgbaf[2], alpha: 0.3)
                    titleLab.textColor =  UIColor.init(red: textColor.rgbaf[0], green: textColor.rgbaf[1], blue: textColor.rgbaf[2], alpha: 0.3)
                    
                }else{
                    titleLab.backgroundColor = PQBFConfig.shared.pointEditNamalBackgroundColor
                    titleLab.textColor = UIColor.hexColor(hexadecimal: "#959595")
                }
                titleLab.font = UIFont.systemFont(ofSize: 13, weight: .regular)
              
            }
        }
    }
}
