//
//  VehicleMonitoringController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/14.
//

import Foundation
import DDControlsKit_Private
import DDMAMapKit_Private
import DDAutoUIKit_Private
import RxSwift
import RxCocoa
import RxRelay
import JXCategoryView
import SnapKit

fileprivate let vehicleMonitoringPannelViewHeight = auto(300)
fileprivate let vehicleMonitoringPannelViewTopInset = auto(90)

fileprivate let vehicleMonitoringPointAnnotationW = auto(120)
fileprivate let vehicleMonitoringPointAnnotationNameLeftInset = auto(35)
fileprivate let vehicleMonitoringPointAnnotationNameRightInset = auto(35)
fileprivate let vehicleMonitoringPointAnnotationNameAtLeastH = auto(30)

extension VehicleMonitoringController {
    func addAction() {
        MCOUNT.messageCountRelay
            .subscribe(onNext: {[weak self] count in
                if count > 0 {
                    self?.messageView.countLabel.isHidden = false
                    self?.messageView.countLabel.text = String(count)
                    self?.messageView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(20)
                    })
                }else{
                    self?.messageView.countLabel.isHidden = true
                    self?.messageView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(0)
                    })
                }
            })
            .disposed(by: disposeBag)
        
        MCOUNT.pendingCountRelay
            .subscribe(onNext: {[weak self] count in
                if count > 0 {
                    self?.pendingView.countLabel.isHidden = false
                    self?.pendingView.countLabel.text = String(count)
                    self?.pendingView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(20)
                    })
                }else{
                    self?.pendingView.countLabel.isHidden = true
                    self?.pendingView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(0)
                    })
                }
            })
            .disposed(by: disposeBag)
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_reloadRescusControolerToDoMessageCount), object: nil)
        
        reloadRelay
            .flatMapLatest { _ in
                return RQ.vehicleMonitorList()
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                    self?.dataModel = response?.data
                    let roster = String(response?.data?.vehicleMonitorCount.rosterCount ?? 0)+"\n"+"排班"
                    let onLineCount = String(response?.data?.vehicleMonitorCount.onLineCount ?? 0)+"\n"+"上线"
                    let lostConnectionCount = String(response?.data?.vehicleMonitorCount.lostConnectionCount ?? 0)+"\n"+"掉线"
                    let leisureCount = String(response?.data?.vehicleMonitorCount.leisureCount ?? 0)+"\n"+"空闲"
                    let busyCount = String(response?.data?.vehicleMonitorCount.busyCount ?? 0)+"\n"+"忙碌"
                    let alarmCount = String(response?.data?.vehicleMonitorCount.alarmCount ?? 0)+"\n"+"报警"
                    if USER.supplierType == 2 {
                        self?.vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.titles = [roster,onLineCount,lostConnectionCount,leisureCount,busyCount,alarmCount]
                    }else{
                        self?.vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.titles = [onLineCount,lostConnectionCount,leisureCount,busyCount,alarmCount]
                    }
                    self?.vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.reloadData()
                    self?.vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.selectItem(at: 0)
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        let bottomSafeArea = view.safeAreaInsets.bottom
        vehicleMonitoringView.vehicleMonitoringPannelView.tapButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                if let isSelected = self?.vehicleMonitoringView.vehicleMonitoringPannelView.tapButton.isSelected {
                    self?.vehicleMonitoringView.vehicleMonitoringPannelView.tapButton.isSelected = !isSelected
                    
                    if isSelected == false {
                        self?.vehicleMonitoringView.coverView.isHidden = true
                        self?.vehicleMonitoringView.vehicleMonitoringPannelView.snp.updateConstraints({ make in
                            make.bottom.equalToSuperview().offset((vehicleMonitoringPannelViewHeight - vehicleMonitoringPannelViewTopInset) - (self?.tabBarController?.tabBar.height ?? 0) - bottomSafeArea)
                        })
                    }else{
                        self?.vehicleMonitoringView.coverView.isHidden = false
                        self?.vehicleMonitoringView.vehicleMonitoringPannelView.snp.updateConstraints({ make in
                            make.bottom.equalToSuperview().offset(0)
                        })
                    }
                    
                    UIView.animate(withDuration: 0.25) {[weak self] in
                        self?.vehicleMonitoringView.layoutIfNeeded()
                    }
                }
            })
            .disposed(by: disposeBag)
        
        vehicleMonitoringView.tapGes.rx.event
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.vehicleMonitoringView.coverView.isHidden = true
                self?.vehicleMonitoringView.vehicleMonitoringPannelView.tapButton.isSelected = true
                self?.vehicleMonitoringView.vehicleMonitoringPannelView.snp.updateConstraints({ make in
                    make.bottom.equalToSuperview().offset((vehicleMonitoringPannelViewHeight - vehicleMonitoringPannelViewTopInset) - (self?.tabBarController?.tabBar.height ?? 0) - bottomSafeArea)
                })
                
                UIView.animate(withDuration: 0.25) {[weak self] in
                    self?.vehicleMonitoringView.layoutIfNeeded()
                }
            })
            .disposed(by: disposeBag)
        
        vehicleMonitoringView.panGes.rx.event
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.vehicleMonitoringView.coverView.isHidden = true
                self?.vehicleMonitoringView.vehicleMonitoringPannelView.tapButton.isSelected = true
                self?.vehicleMonitoringView.vehicleMonitoringPannelView.snp.updateConstraints({ make in
                    make.bottom.equalToSuperview().offset((vehicleMonitoringPannelViewHeight - vehicleMonitoringPannelViewTopInset) - (self?.tabBarController?.tabBar.height ?? 0) - bottomSafeArea)
                })
                
                UIView.animate(withDuration: 0.25) {[weak self] in
                    self?.vehicleMonitoringView.layoutIfNeeded()
                }
            })
            .disposed(by: disposeBag)
        
        reloadRelay.accept(nil)
    }
}

extension VehicleMonitoringController : DDMAMapViewDelegate {
    public func dd_mapView(_ mapView: MAMapView, viewFor annotation: MAAnnotation) -> MAAnnotationView {
        if annotation.isMember(of: MAPointAnnotation.self) {
            let pointAnnotation = annotation as! MAPointAnnotation
            if pointAnnotation.annotationClass == VehicleMonitoringPointAnnotation.self{
                let DriverPointReuseIndentifier = "DispatchMapStatePointAnnotation"
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: DriverPointReuseIndentifier) as? VehicleMonitoringPointAnnotation
                if annotationView == nil {
                    annotationView = VehicleMonitoringPointAnnotation.init(annotation: pointAnnotation, reuseIdentifier: DriverPointReuseIndentifier)
                }
                annotationView!.annotation = pointAnnotation
                let model = mapModel?[pointAnnotation.tag]
                
                if let alarmType = model?.alarmType {
                    switch alarmType.code {
                    case .busy:
                        annotationView?.pointView.backgroundColor = .hex("BA1717")
                        annotationView?.verticalView.backgroundColor = .hex("BA1717")
                        annotationView?.stateImageView.backgroundColor = .hex("BA1717")
                        annotationView?.nameLabel.textColor = .hex("BA1717")
                        annotationView?.topBackgroundImageView.backgroundColor = .hex("BA1717").alpha(0.1)
                        annotationView?.cameraBackgroundImageView.layer.borderColor = UIColor.hex("BA1717").cgColor
                        annotationView?.cameraIcon.tintColor = .hex("BA1717")
                        annotationView?.cameraArrow.tintColor = .hex("BA1717")
                        break
                    default:
                        annotationView?.pointView.backgroundColor = .hex("787878")
                        annotationView?.verticalView.backgroundColor = .hex("787878")
                        annotationView?.stateImageView.backgroundColor = .hex("787878")
                        annotationView?.nameLabel.textColor = .hex("787878")
                        annotationView?.topBackgroundImageView.backgroundColor = .hex("787878").alpha(0.1)
                        annotationView?.cameraBackgroundImageView.layer.borderColor = UIColor.hex("787878").cgColor
                        annotationView?.cameraIcon.tintColor = .hex("787878")
                        annotationView?.cameraArrow.tintColor = .hex("787878")
                        break
                    }
                }else{
                    switch model?.vehicleStatus?.code {
                    case .offLine,.lostConnection:
                        annotationView?.pointView.backgroundColor = .hex("787878")
                        annotationView?.verticalView.backgroundColor = .hex("787878")
                        annotationView?.stateImageView.backgroundColor = .hex("787878")
                        annotationView?.nameLabel.textColor = .hex("787878")
                        annotationView?.topBackgroundImageView.backgroundColor = .hex("787878").alpha(0.1)
                        annotationView?.cameraBackgroundImageView.layer.borderColor = UIColor.hex("787878").cgColor
                        annotationView?.cameraIcon.tintColor = .hex("787878")
                        annotationView?.cameraArrow.tintColor = .hex("787878")
                        break
                    case .onLine,.leisure:
                        annotationView?.pointView.backgroundColor = .hex("2956DB")
                        annotationView?.verticalView.backgroundColor = .hex("2956DB")
                        annotationView?.stateImageView.backgroundColor = .hex("2956DB")
                        annotationView?.nameLabel.textColor = .hex("2956DB")
                        annotationView?.topBackgroundImageView.backgroundColor = .hex("2956DB").alpha(0.1)
                        annotationView?.cameraBackgroundImageView.layer.borderColor = UIColor.hex("2956DB").cgColor
                        annotationView?.cameraIcon.tintColor = .hex("2956DB")
                        annotationView?.cameraArrow.tintColor = .hex("2956DB")
                        break
                    case .busy:
                        annotationView?.pointView.backgroundColor = .hex("BA1717")
                        annotationView?.verticalView.backgroundColor = .hex("BA1717")
                        annotationView?.stateImageView.backgroundColor = .hex("BA1717")
                        annotationView?.nameLabel.textColor = .hex("BA1717")
                        annotationView?.topBackgroundImageView.backgroundColor = .hex("BA1717").alpha(0.1)
                        annotationView?.cameraBackgroundImageView.layer.borderColor = UIColor.hex("BA1717").cgColor
                        annotationView?.cameraIcon.tintColor = .hex("BA1717")
                        annotationView?.cameraArrow.tintColor = .hex("BA1717")
                        break
                    case .BuyBusy:
                        annotationView?.pointView.backgroundColor = .hex("ffa400")
                        annotationView?.verticalView.backgroundColor = .hex("ffa400")
                        annotationView?.stateImageView.backgroundColor = .hex("ffa400")
                        annotationView?.nameLabel.textColor = .hex("ffa400")
                        annotationView?.topBackgroundImageView.backgroundColor = .hex("ffa400").alpha(0.1)
                        annotationView?.cameraBackgroundImageView.layer.borderColor = UIColor.hex("ffa400").cgColor
                        annotationView?.cameraIcon.tintColor = .hex("ffa400")
                        annotationView?.cameraArrow.tintColor = .hex("ffa400")
                        break
                    case .none:
                        break
                    }
                }
                
                annotationView?.stateLabel.text = model?.vehicleStatus?.label
                annotationView?.nameLabel.text = model?.vehicleName
                if model?.isSelected == true {
                    var content = ""
                    if model?.orderCode?.isEmpty == false {
                        content.append("· \((model?.orderCode)!)")
                    }else if model?.serviceName?.isEmpty == false {
                        content.append("· \((model?.serviceName)!)")
                    }else if model?.taskStatusString?.isEmpty == false {
                        content.append("· \((model?.taskStatusString)!)")
                    }else if model?.workingCount != nil {
                        content = content + "· " + String((model?.workingCount)!)
                    }
                    annotationView?.contentLabel.text = content
                    annotationView?.zIndex = zIndex + 1
                }else{
                    annotationView?.contentLabel.text = nil
                }
                
                var vehicleMonitoringPointAnnotationNameInset = vehicleMonitoringPointAnnotationNameLeftInset + vehicleMonitoringPointAnnotationNameRightInset
                if model?.terminalType == .GPS {
                    annotationView?.cameraBackgroundImageView.isHidden = false
                    annotationView?.nameLabel.snp.updateConstraints({ make in
                        make.right.equalToSuperview().offset(-auto(35))
                    })
                }else{
                    annotationView?.cameraBackgroundImageView.isHidden = true
                    annotationView?.nameLabel.snp.updateConstraints({ make in
                        make.right.equalToSuperview().offset(-auto(5))
                    })
                    vehicleMonitoringPointAnnotationNameInset = vehicleMonitoringPointAnnotationNameInset - auto(30)
                }
                let contentSizeH = annotationView?.contentLabel.sizeThatFits(CGSize(width: vehicleMonitoringPointAnnotationW, height: 1000)).height ?? 0
                var nameSizeH = annotationView?.nameLabel.sizeThatFits(CGSize(width: vehicleMonitoringPointAnnotationW - vehicleMonitoringPointAnnotationNameInset, height: 1000)).height ?? 0
                if nameSizeH < vehicleMonitoringPointAnnotationNameAtLeastH {
                    nameSizeH = vehicleMonitoringPointAnnotationNameAtLeastH
                }
                annotationView?.frame = CGRect(origin: (annotationView?.frame.origin)!, size: CGSize(width: vehicleMonitoringPointAnnotationW, height: contentSizeH + nameSizeH))
                
                annotationView?.tapGes.rx.event
                    .observe(on: MainScheduler.instance)
                    .subscribe(onNext: {[weak self] _ in
                        let vc = VehicleMonitorVideoController(vehicleId: model?.vehicleId, deviceCode: nil)
                        self?.navigationController?.pushViewController(vc, animated: true)
                    })
                    .disposed(by: annotationView!.disposeBag)
                return annotationView!
            }
            
            if pointAnnotation.annotationClass == DispatchMapSericeAddressPointAnnotation.self{
                let DriverPointReuseIndentifier = "DispatchMapSericeAddressPointAnnotation"
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: DriverPointReuseIndentifier) as? DispatchMapSericeAddressPointAnnotation
                if annotationView == nil {
                    annotationView = DispatchMapSericeAddressPointAnnotation.init(annotation: pointAnnotation, reuseIdentifier: DriverPointReuseIndentifier)
                }
                annotationView!.annotation = pointAnnotation
                return annotationView!
            }
        }

        return MAAnnotationView.init(annotation: annotation, reuseIdentifier: "cell")
    }
    
    public func dd_mapView(_ mapView: MAMapView, didAnnotationViewTapped view: MAAnnotationView) {
        zIndex += 1
        view.zIndex = zIndex
    }
}

// MARK: JXCategoryListContainerViewDelegate
extension VehicleMonitoringController : JXCategoryListContainerViewDelegate {
    public func number(ofListsInlistContainerView listContainerView: JXCategoryListContainerView!) -> Int {
        return vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.titles.count
    }
    
    public func listContainerView(_ listContainerView: JXCategoryListContainerView!, initListFor index: Int) -> JXCategoryListContentViewDelegate! {
        let vc = VehicleMonitoringListController()
        if USER.supplierType == 2 {
            if index == 0 {
                vc.reloadCell(models: dataModel?.rosterList,isPaiban: true)
            }else if index == 1 {
                vc.reloadCell(models: dataModel?.onLineList)
            }else if index == 2 {
                vc.reloadCell(models: dataModel?.lostConnectionList)
            }else if index == 3 {
                vc.reloadCell(models: dataModel?.leisureList)
            }else if index == 4 {
                vc.reloadCell(models: dataModel?.busyList)
            }else if index == 5 {
                vc.reloadCell(models: dataModel?.alarmList,isAlarm: true)
            }
        }else{
            if index == 0 {
                vc.reloadCell(models: dataModel?.onLineList)
            }else if index == 1 {
                vc.reloadCell(models: dataModel?.lostConnectionList)
            }else if index == 2 {
                vc.reloadCell(models: dataModel?.leisureList)
            }else if index == 3 {
                vc.reloadCell(models: dataModel?.busyList)
            }else if index == 4 {
                vc.reloadCell(models: dataModel?.alarmList,isAlarm: true)
            }
        }
        
        vc.selectCellBlock = {[weak self] model in
            // 去掉其他tableview的选中
            for index in 0..<(self?.dataModel?.rosterList.count ?? 0) {
                let _model = self?.dataModel?.rosterList[index]
                _model?.isSelected = false
            }
            for index in 0..<(self?.dataModel?.onLineList.count ?? 0) {
                let _model = self?.dataModel?.onLineList[index]
                _model?.isSelected = false
            }
            for index in 0..<(self?.dataModel?.lostConnectionList.count ?? 0) {
                let _model = self?.dataModel?.lostConnectionList[index]
                _model?.isSelected = false
            }
            for index in 0..<(self?.dataModel?.leisureList.count ?? 0) {
                let _model = self?.dataModel?.leisureList[index]
                _model?.isSelected = false
            }
            for index in 0..<(self?.dataModel?.busyList.count ?? 0) {
                let _model = self?.dataModel?.busyList[index]
                _model?.isSelected = false
            }
            for index in 0..<(self?.dataModel?.alarmList.count ?? 0) {
                let _model = self?.dataModel?.alarmList[index]
                _model?.isSelected = false
            }
            self?.preciousTableView?.reloadData()
            model.isSelected = true
            vc.vehicleMonitoringListView.tableView.reloadData()
            self?.preciousTableView = vc.vehicleMonitoringListView.tableView
            
            // 设置当前选中的annotation
            self?.vehicleMonitoringView.maMapView.maMapView.setCenter(CLLocationCoordinate2D(latitude: Double(model.lat ?? "0")!, longitude: Double(model.lon ?? "0")!), animated: true)
            
            // 当前annotation展开，其他闭合
            self?.vehicleMonitoringView.maMapView.maMapView.removeAnnotations(self?.mapAnnotaions)
            self?.mapAnnotaions.removeAll()
            for index in 0..<vc.models.count {
                let model = vc.models[index]
                let coordinate = CLLocationCoordinate2D(latitude: Double(model.lat ?? "") ?? 0, longitude: Double(model.lon ?? "") ?? 0)
                let pointAnnotation = MAPointAnnotation.init()
                pointAnnotation.annotationClass = VehicleMonitoringPointAnnotation.self
                pointAnnotation.coordinate = coordinate
                pointAnnotation.tag = index
                self?.vehicleMonitoringView.maMapView.maMapView.addAnnotation(pointAnnotation)
                self?.mapAnnotaions.append(pointAnnotation)
            }
        }
        return vc
    }
}

extension VehicleMonitoringController : JXCategoryViewDelegate {
    public func categoryView(_ categoryView: JXCategoryBaseView!, didSelectedItemAt index: Int) {
        reloadData(index: index)
    }
    
    public func categoryView(_ categoryView: JXCategoryBaseView!, didScrollSelectedItemAt index: Int) {
        reloadData(index: index)
    }
    
    func reloadData(index:Int) {
        if USER.supplierType == 2 {
            if index == 0 {
                mapModel = dataModel?.rosterList
            }else if index == 1 {
                mapModel = dataModel?.onLineList
            }else if index == 2 {
                mapModel = dataModel?.lostConnectionList
            }else if index == 3 {
                mapModel = dataModel?.leisureList
            }else if index == 4 {
                mapModel = dataModel?.busyList
            }else if index == 5 {
                mapModel = dataModel?.alarmList
            }
        }else{
            if index == 0 {
                mapModel = dataModel?.onLineList
            }else if index == 1 {
                mapModel = dataModel?.lostConnectionList
            }else if index == 2 {
                mapModel = dataModel?.leisureList
            }else if index == 3 {
                mapModel = dataModel?.busyList
            }else if index == 4 {
                mapModel = dataModel?.alarmList
            }
        }
        
        vehicleMonitoringView.maMapView.maMapView.removeAnnotations(mapAnnotaions)
        for index in 0..<(mapModel?.count ?? 0) {
            let model = mapModel?[index]
            let coordinate = CLLocationCoordinate2D(latitude: Double(model?.lat ?? "") ?? 0, longitude: Double(model?.lon ?? "") ?? 0)
            let pointAnnotation = MAPointAnnotation.init()
            pointAnnotation.annotationClass = VehicleMonitoringPointAnnotation.self
            pointAnnotation.coordinate = coordinate
            pointAnnotation.tag = index
            vehicleMonitoringView.maMapView.maMapView.addAnnotation(pointAnnotation)
            mapAnnotaions.append(pointAnnotation)
            
            if index == 0{
                vehicleMonitoringView.maMapView.maMapView.setCenter(coordinate, animated: true)
            }
        }
    }
}

open class VehicleMonitoringController : DDViewController {
    private let vehicleMonitoringView = VehicleMonitoringView(titles:[""])
    public var zIndex = 0
    private let disposeBag = DisposeBag()
    private let reloadRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    private var dataModel : VehicleMonitorListDataModel?
    private var mapModel : [VehicleMonitorListDataModel.ItemModel]?
    private var mapAnnotaions : [MAPointAnnotation] = []
    public lazy var categoryContainerView = JXCategoryListContainerView(type: .scrollView, delegate: self)
    private var preciousTableView : DDTableView?
    private var preciousModel : (VehicleMonitorListDataModel.ItemModel)?
    private let messageTapGes = UITapGestureRecognizer()
    private let messageView = MessageView()
    private let pendingTapGes = UITapGestureRecognizer()
    private let pendingView = MessageView()
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationItemTitle = "车辆监控"
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        navigationItem.leftBarButtonItems = nil

        addSubviews()
        addAction()
    }
    
    func addSubviews() {
        view.addSubview(vehicleMonitoringView)
        vehicleMonitoringView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(CGRectGetHeight(UIApplication.shared.dd_statusBarFrame)+CGRectGetHeight(navigationController?.navigationBar.frame ?? .zero))
        }
        
        vehicleMonitoringView.maMapView.delegate = self
        vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.delegate = self
        vehicleMonitoringView.vehicleMonitoringPannelView.radiusView.addSubview(categoryContainerView!)
        vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.listContainer = categoryContainerView
        categoryContainerView?.snp.makeConstraints({ make in
            make.top.equalTo(vehicleMonitoringView.vehicleMonitoringPannelView.categoryView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        })
        
        messageView.titleLabel.text = "消息"
        messageView.addGestureRecognizer(messageTapGes)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: messageView)
        messageView.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(40)
        }

        pendingView.titleLabel.text = "待办"
        pendingView.addGestureRecognizer(pendingTapGes)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: pendingView)
        pendingView.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(40)
        }
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
}

// MARK: UI
open class VehicleMonitoringView : DDView {
    public let vehicleMonitoringPannelView : VehicleMonitoringPannelView
    public let maMapView : DDMAMapView
    public let coverView : DDView
    public let tapGes : UITapGestureRecognizer
    public let panGes : UIPanGestureRecognizer
    public init(titles:[String]) {
        vehicleMonitoringPannelView = VehicleMonitoringPannelView(titles:titles)
        maMapView = DDMAMapView()
        coverView = DDView()
        tapGes = UITapGestureRecognizer()
        panGes = UIPanGestureRecognizer()
        super.init(frame: .zero)
        
        maMapView.maMapView.logoCenter = CGPoint(x: 100, y: 100)
        addSubview(maMapView)
        coverView.addGestureRecognizer(tapGes)
        coverView.addGestureRecognizer(panGes)
        coverView.isHidden = true
        addSubview(coverView)
        vehicleMonitoringPannelView.layer.cornerRadius = auto(16)
        addSubview(vehicleMonitoringPannelView)
        
        maMapView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(vehicleMonitoringPannelView.snp.top).offset(auto(30))
        }
        
        coverView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        vehicleMonitoringPannelView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(vehicleMonitoringPannelViewHeight)
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class VehicleMonitoringPannelView : DDView {
    public let radiusView : DDView
    public let tapButton : DDButton
    public let categoryView : JXCategoryTitleView

    public init(titles:[String]) {
        radiusView = DDView()
        tapButton = DDButton.dd_initCustom()
        categoryView = JXCategoryTitleView.init()
        categoryView.titles = titles
        super.init(frame: .zero)
        backgroundColor = .hex("FBFBFB")
        radiusView.backgroundColor = .clear
        addSubview(radiusView)
        tapButton.setImage(UIImage(named: "dispatchOrder_down"), for: .normal)
        tapButton.setImage(UIImage(named: "dispatchOrder_up"), for: .selected)
        radiusView.addSubview(tapButton)
        categoryView.titleNumberOfLines = 2
        categoryView.titleColor = .hex("737373").alpha(0.55)
        categoryView.titleSelectedColor = .hex("3678FF")
        categoryView.titleFont = .mediumFont(auto(14))
        categoryView.backgroundColor = .hex("FBFBFB")
        let indicator = JXCategoryIndicatorLineView()
        indicator.indicatorColor = .hex("3678FF")
        indicator.indicatorWidth = JXCategoryViewAutomaticDimension
        indicator.verticalMargin = 7
        categoryView.indicators = [indicator]
        radiusView.addSubview(categoryView)
        
        radiusView.layer.cornerRadius = auto(4)
        radiusView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-safeAreaInsets.bottom)
        }
        
        tapButton.snp.makeConstraints { make in
            make.top.equalTo(auto(7))
            make.height.width.equalTo(auto(23))
            make.centerX.equalToSuperview()
        }
        
        categoryView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(tapButton.snp.bottom)
            make.height.equalTo(auto(60))
        }
       
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class VehicleMonitoringPointAnnotation : MAAnnotationView {
    public let radiusView : DDView
    public let topBackgroundImageView : DDImageView
    public let stateImageView : DDImageView
    public let stateLabel : DDLabel
    public let nameLabel : DDLabel
    public let contentLabel : DDLabel
    public let cameraBackgroundImageView : DDImageView
    public let cameraIcon : DDImageView
    public let cameraArrow : DDImageView
    public let tapGes : UITapGestureRecognizer
    public let verticalView : UIView
    public let pointView : UIView
    public var disposeBag : DisposeBag
    
    override init!(annotation: MAAnnotation!, reuseIdentifier: String!) {
        radiusView = DDView.init()
        topBackgroundImageView = DDImageView.init()
        stateImageView = DDImageView.init()
        stateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(10)), textColor: .white(alpha: 1.0))
        nameLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("#2C395F"))
        contentLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("#2C395F"))
        cameraBackgroundImageView = DDImageView()
        cameraIcon = DDImageView(image: UIImage(named: "vehicleMonitoring_cameraIdle")?.withRenderingMode(.alwaysTemplate))
        cameraArrow = DDImageView(image: UIImage(named: "vehicleMonitoring_cameraIdleArrow")?.withRenderingMode(.alwaysTemplate))
        tapGes = UITapGestureRecognizer()
        verticalView = UIView.init()
        pointView = UIView.init()
        disposeBag = DisposeBag()
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        setUpSubviews()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
    
    func setUpSubviews(){
        backgroundColor = .white
        layer.cornerRadius = auto(4)
        isUserInteractionEnabled = true
        imageView.isUserInteractionEnabled = true
        
        radiusView.backgroundColor = .white(alpha: 1)
        radiusView.layer.cornerRadius = auto(4)
        radiusView.layer.masksToBounds = true
        radiusView.isUserInteractionEnabled = true
        addSubview(radiusView)
        radiusView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.width.equalTo(vehicleMonitoringPointAnnotationW)
            make.bottom.equalToSuperview()
        }
        
        topBackgroundImageView.isUserInteractionEnabled = true
        radiusView.addSubview(topBackgroundImageView)
        topBackgroundImageView.snp.makeConstraints { make in
            make.top.left.right.equalTo(0)
            make.height.greaterThanOrEqualTo(auto(30))
        }
        
        stateImageView.isUserInteractionEnabled = false
        topBackgroundImageView.addSubview(stateImageView)
        stateImageView.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(auto(30))
        }
        
        stateLabel.textAlignment = .center
        stateLabel.isUserInteractionEnabled = false
        stateImageView.addSubview(stateLabel)
        stateLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        nameLabel.textAlignment = .center
        nameLabel.numberOfLines = 0
        nameLabel.isUserInteractionEnabled = false
        topBackgroundImageView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(vehicleMonitoringPointAnnotationNameLeftInset)
            make.right.equalToSuperview().offset(-vehicleMonitoringPointAnnotationNameRightInset)
            make.top.bottom.equalToSuperview()
        }
        
        cameraBackgroundImageView.layer.cornerRadius = auto(4)
        cameraBackgroundImageView.layer.borderColor = UIColor.hex("4D64DA").cgColor
        cameraBackgroundImageView.layer.borderWidth = 1
        cameraBackgroundImageView.isUserInteractionEnabled = true
        cameraBackgroundImageView.addGestureRecognizer(tapGes)
        topBackgroundImageView.addSubview(cameraBackgroundImageView)
        cameraBackgroundImageView.snp.makeConstraints { make in
            make.right.equalTo(-auto(3))
            make.centerY.equalToSuperview()
            make.width.equalTo(auto(30))
            make.height.equalTo(auto(15))
        }
        
        cameraIcon.isUserInteractionEnabled = false
        cameraBackgroundImageView.addSubview(cameraIcon)
        cameraIcon.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(auto(3))
            make.width.equalTo(auto(15))
            make.height.equalTo(auto(10))
        }

        cameraArrow.isUserInteractionEnabled = false
        cameraBackgroundImageView.addSubview(cameraArrow)
        cameraArrow.snp.makeConstraints { make in
            make.right.equalTo(-auto(3))
            make.centerY.equalToSuperview()
        }
        
        contentLabel.numberOfLines = 0
        radiusView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.top.equalTo(topBackgroundImageView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        verticalView.isUserInteractionEnabled = false
        addSubview(verticalView)
        verticalView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(radiusView.snp.bottom)
            make.width.equalTo(auto(2.5))
            make.height.equalTo(auto(15))
        }
        
        pointView.isUserInteractionEnabled = false
        pointView.layer.cornerRadius = auto(5)
        pointView.layer.borderColor = UIColor.white.cgColor
        pointView.layer.borderWidth = auto(2)
        addSubview(pointView)
        pointView.snp.makeConstraints { make in
            make.centerX.equalTo(verticalView.snp.centerX)
            make.top.equalTo(verticalView.snp.bottom).offset(0)
            make.width.height.equalTo(auto(10))
        }
        
    }
}
