//
//  VehicleMonitorVideoController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/16.
//

import Foundation
import DDControlsKit_Private
import DDCategoryKit_Private
import DDAutoUIKit_Private
import JXCategoryView
import SnapKit
import RxSwift
import RxRelay
import RxCocoa
import DDProgressHUDKit_Private

extension VehicleMonitorVideoController : JXCategoryViewDelegate {
    public func categoryView(_ categoryView: JXCategoryBaseView!, didSelectedItemAt index: Int) {
        videoView.endShow()
        RQ.closeHistoryControl(prameters: GetVideoUrlParameters(simNumber: simNumber,channel: channel))
            .subscribe {[weak self] _ in
                if let wsUrl = self?.videos[index] {
                    self?.videoView.wsUrl = wsUrl
                    self?.channel = self?.channels[index]
                }
            }
            .disposed(by: disposeBag)
    }
}

open class VehicleMonitorVideoController : ZDViewController {
    private var vehicleId : Int?
    private var simNumber : String?
    private let vehicleMonitorVideoView : VehicleMonitorVideoView
    private let reloadRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    private let disposeBag = DisposeBag()
    private var videos : [String] = []
    var channels : [Int] = []
    var channel : Int?
    var closeSub = ReplaySubject<Any?>.create(bufferSize: 1)
    var videoView = VideoPlayView()
    public init(vehicleId:Int?,simNumber: String?) {
        self.vehicleId = vehicleId
        self.simNumber = simNumber
        self.vehicleMonitorVideoView = VehicleMonitorVideoView()
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationItemTitle = "实时监控"
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        dd_navigationBarBarButtonItemAttributes = [.foregroundColor : UIColor.white]
        
        vehicleMonitorVideoView.categoryView.delegate = self
        
        reloadRelay
            .filter({[weak self] _ in
                return self?.vehicleId != nil && self?.simNumber != nil
            })
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_showHUD()
            })
            .flatMapLatest {[weak self] _ in
                return RQ.getRealtimeUrl(prameters: GetVideoUrlParameters(vehicleId: (self?.vehicleId)!,simNumber: (self?.simNumber)!))
            }
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_hideHUD()
            })
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                    var channels : [String] = []
                    self?.channels.removeAll()
                    for index in 0..<(response?.data?.channelList?.count ?? 0) {
                        let channelN = response?.data?.channelList?[index] ?? ""
                        channels.append("通道"+"\(channelN)")
                        self?.channels.append(Int(channelN) ?? 1)
                    }
                    if let data = response?.data {
                        self?.videos.removeAll()
                        self?.videos.append(contentsOf: data.realtimeList ?? [])
                    }
                    self?.vehicleMonitorVideoView.categoryView.titles = channels
                    self?.vehicleMonitorVideoView.categoryView.reloadData()
                    self?.vehicleMonitorVideoView.categoryView.selectItem(at: 0)
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
                
            })
            .disposed(by: disposeBag)
        
        closeSub
            .flatMapLatest {[weak self] response in
                return RQ.closeHistoryControl(prameters: GetVideoUrlParameters(simNumber: self?.simNumber,channel:self?.channel))
            }
            .subscribe(onNext: { response in
            })
            .disposed(by: disposeBag)
        
        NotificationCenter.default.rx
            .notification(UIApplication.didEnterBackgroundNotification)
            .observe(on: ConcurrentMainScheduler.instance)
            .subscribe(onNext: { [weak self] _ in
                self?.videoView.endShow()
                self?.closeSub.onNext(nil)
            })
            .disposed(by: disposeBag)
    }

    open override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        if vehicleMonitorVideoView.superview == nil {
            view.addSubview(vehicleMonitorVideoView)
            vehicleMonitorVideoView.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(view.safeAreaInsets.top)
                make.left.right.bottom.equalToSuperview()
            }
            
            vehicleMonitorVideoView.addSubview(videoView)
            videoView.snp.makeConstraints { make in
                make.top.equalTo(vehicleMonitorVideoView.categoryView.snp.bottom).offset(auto(10))
                make.width.equalTo(auto(375))
                make.height.equalTo(auto(300))
                make.centerX.equalToSuperview()
            }
            reloadRelay.accept(nil)
        }
    }
    
    open override func dd_backActionPop(_ isAnimated: Bool) {
        super.dd_backActionPop(isAnimated)
        videoView.endShow()
        closeSub.onNext(nil)
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

open class VehicleMonitorVideoView : DDView {
    public let categoryView : JXCategoryTitleView
    
    public override init(frame: CGRect) {
        categoryView = JXCategoryTitleView.init()
        super.init(frame: frame)
        categoryView.titleColor = .hex("737373").alpha(0.55)
        categoryView.titleSelectedColor = .hex("3678FF")
        categoryView.titleFont = .mediumFont(auto(14))
        categoryView.backgroundColor = .hex("FFFFFF")
        let indicator = JXCategoryIndicatorLineView()
        indicator.indicatorColor = .hex("3678FF")
        indicator.indicatorWidth = JXCategoryViewAutomaticDimension
        indicator.verticalMargin = 7
        categoryView.indicators = [indicator]
        addSubview(categoryView)
        categoryView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(0)
            make.left.equalTo(auto(20))
            make.right.equalTo(-auto(20))
            make.height.equalTo(auto(40))
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

