//
//  DispatchOrderController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/10.
//

import Foundation
import DDControlsKit_Private
import SnapKit
import RxSwift
import RxRelay
import DDAutoUIKit_Private
import DDMAMapKit_Private
import DDUIGestureRecognizer
import DDUtilsSwiftKit_Private

fileprivate let dispatchPannelViewHeight = auto(300)
fileprivate let dispatchPannelViewTopInset = auto(45)
fileprivate let mapInsetTopSafeArea = auto(80)
fileprivate let mapInsetBottomSafeArea = auto(80)

extension DispatchOrderController {
    func addActions() {
        
        dispatchOrderView.dispatchPannelView.onlineButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                if let isSelected = self?.dispatchOrderView.dispatchPannelView.onlineButton.isSelected,isSelected == false {
                    self?.dispatchOrderView.dispatchPannelView.onlineButton.isSelected = !isSelected
                    self?.dispatchOrderView.dispatchPannelView.offlineButton.isSelected = false
                    self?.dispatchOrderView.dispatchPannelView.tapBackgroundView.image = UIImage(named: "dispatchOrder_online_tap_background")
                    self?.dispatchOrderView.dispatchPannelView.tableView.isHidden = false
                    self?.dispatchOrderView.dispatchPannelView.offlineView.isHidden = true
                }
            })
            .disposed(by: disposeBag)
        
        dispatchOrderView.dispatchPannelView.offlineButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                if let isSelected = self?.dispatchOrderView.dispatchPannelView.offlineButton.isSelected,isSelected == false {
                    self?.dispatchOrderView.dispatchPannelView.offlineButton.isSelected = !isSelected
                    self?.dispatchOrderView.dispatchPannelView.onlineButton.isSelected = false
                    self?.dispatchOrderView.dispatchPannelView.tapBackgroundView.image = UIImage(named: "dispatchOrder_offline_tap_background")
                    self?.dispatchOrderView.dispatchPannelView.tableView.isHidden = true
                    self?.dispatchOrderView.dispatchPannelView.offlineView.isHidden = false
                }
            })
            .disposed(by: disposeBag)
        
        dispatchOrderView.dispatchPannelView.offlineView.rewriteButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.dispatchOrderView.dispatchPannelView.offlineView.name.textFiled.text = nil
                self?.dispatchOrderView.dispatchPannelView.offlineView.phone.textFiled.text = nil
                self?.dispatchOrderView.dispatchPannelView.offlineView.license.textFiled.text = nil
            })
            .disposed(by: disposeBag)
        
        dispatchOrderView.dispatchPannelView.offlineView.submitButton.rx.tap
            .observe(on: MainScheduler.instance)
            .filter({[weak self] _ in
                if self?.dispatchOrderView.dispatchPannelView.offlineView.name.textFiled.text?.isEmpty != false {
                    self?.view.dd_makeToast(dispatchOrderInputName)
                    return false
                }
                if self?.dispatchOrderView.dispatchPannelView.offlineView.phone.textFiled.text?.isEmpty != false {
                    self?.view.dd_makeToast(dispatchOrderInputPhone)
                    return false
                }
                if self?.dispatchOrderView.dispatchPannelView.offlineView.license.textFiled.text?.isEmpty != false {
                    self?.view.dd_makeToast(dispatchOrderInputLicense)
                    return false
                }
                return self?.dispatchOrderView.dispatchPannelView.offlineView.name.textFiled.text?.isEmpty == false && self?.dispatchOrderView.dispatchPannelView.offlineView.phone.textFiled.text?.isEmpty == false && self?.dispatchOrderView.dispatchPannelView.offlineView.license.textFiled.text?.isEmpty == false
            })
            .observe(on: MainScheduler.instance)
            .flatMapLatest {[weak self] _ in
                return RQ.dispatchVehicle(parameters: DispatchVehicleParameters(type: .offline, userOrderId: (self?.userOrderId)!, taskOrderId: (self?.taskOrderId)!,driverName: (self?.dispatchOrderView.dispatchPannelView.offlineView.name.textFiled.text)!,driverPhone: (self?.dispatchOrderView.dispatchPannelView.offlineView.phone.textFiled.text)!,plateNumber: (self?.dispatchOrderView.dispatchPannelView.offlineView.license.textFiled.text)!))
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                self?.dispatchOrderResponse(response: response)
            })
            .disposed(by: disposeBag)
        
        dispatchOrderRelay
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_showHUD()
            })
            .flatMapLatest {[weak self] model in
                return RQ.dispatchVehicle(parameters: DispatchVehicleParameters(type: .online, userOrderId: (self?.userOrderId)!, taskOrderId: (self?.taskOrderId)!,driverId: model.driverId,vehicleId: model.vehicleId))
            }
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_hideHUD()
            })
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                self?.dispatchOrderResponse(response: response)
            })
            .disposed(by: disposeBag)
        
        RQ.dispatchVehicleList(parameters: DispatchVehicleListParameters(type:.online, userOrderId: userOrderId, taskOrderId: taskOrderId))
            .observe(on: MainScheduler.instance)
            .subscribe(onSuccess: {[weak self] response in
                if response?.success == true {
                    if let array = response?.data {
                        // 重新计算数组
                        self?.resultArr.removeAll()
                        self?.resultArr.append(contentsOf: array)
                        self?.dispatchOrderView.maMapView.maMapView.removeAnnotations(self?.dispatchOrderView.maMapView.maMapView.annotations)
                        
                        self?.isShowSmallAnnotation = false
                        self?.shouldShowSmallAnnotation = true
                        
                        for index in 0..<array.count {
                            let model = array[index]
                            let coordinate = CLLocationCoordinate2D(latitude: Double(model.lat ?? "") ?? 0, longitude: Double(model.lon ?? "") ?? 0)
                            let pointAnnotation = MAPointAnnotation.init()
                            pointAnnotation.annotationClass = DispatchMapStatePointAnnotation.self
                            pointAnnotation.coordinate = coordinate
                            pointAnnotation.tag = index
                            self?.dispatchOrderView.maMapView.maMapView.addAnnotation(pointAnnotation)
                        }
                        
                        if let serviceAddressLat = self?.serviceAddressLat, let serviceAddressLon = self?.serviceAddressLon {
                            let serviceAddressCoordinate = CLLocationCoordinate2D(latitude: serviceAddressLat, longitude: serviceAddressLon)
                            let serviceAddressPointAnnotation = MAPointAnnotation.init()
                            serviceAddressPointAnnotation.annotationClass = DispatchMapSericeAddressPointAnnotation.self
                            serviceAddressPointAnnotation.coordinate = serviceAddressCoordinate
                            serviceAddressPointAnnotation.tag = 1000000
                            self?.dispatchOrderView.maMapView.maMapView.addAnnotation(serviceAddressPointAnnotation)
                            self?.dispatchOrderView.maMapView.maMapView.setCenter(serviceAddressCoordinate, animated: true)
                        }
                        
                        if (self?.dispatchOrderView.maMapView.maMapView.annotations.count ?? 0) > 0 , let annotations = self?.dispatchOrderView.maMapView.maMapView.annotations {
                            DispatchQueue.main.async {[weak self] in
                                self?.modifyMapAnchor()
                                self?.dispatchOrderView.maMapView.maMapView.showAnnotations(annotations, edgePadding:UIEdgeInsets(top: mapInsetTopSafeArea, left: 0, bottom: dispatchPannelViewHeight + mapInsetBottomSafeArea, right: 0), animated: true)
                            }
                        }
                        self?.dispatchOrderView.dispatchPannelView.tableView.reloadData()
                    }
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        dispatchOrderView.dispatchPannelView.onlineButton.sendActions(for: .touchUpInside)
    }
    
    func dispatchOrderResponse(response:ResponseModel<String>?) {
        view.dd_makeToast(response?.msg ?? dispatchOrderSuccess,completion: {[weak self] _ in
            if self?.dispatchCompletionHandler != nil {
                self?.dispatchCompletionHandler?((self?.userOrderId)!)
            }
            
            DispatchQueue.main.async {
                self?.navigationController?.popViewController(animated: true)
            }
        })
    }
    
    func annotationViewStateConfig(annotationView: DispatchMapStatePointAnnotation,vehicleModel: DispatchVehicleListDataModel, shouldShowSmallAnnotation: Bool) {
        var backgroundColor : UIColor?
        var bigImage : UIImage?
        var middleImage : UIImage?
        
        switch vehicleModel.vehicleStatus?.code {
        case VehicleStatusCodeEnum.offLine.rawValue,VehicleStatusCodeEnum.lostConnection.rawValue:
            backgroundColor = .hex("858585")
            bigImage = UIImage(named: "vehicleMonitoring_offline_big")
            middleImage = UIImage(named: "vehicleMonitor_offline_cell_flag_bg")
            break
        case VehicleStatusCodeEnum.onLine.rawValue,VehicleStatusCodeEnum.leisure.rawValue:
            backgroundColor = .hex("067BB9")
            bigImage = UIImage(named: "vehicleMonitoring_empty_big")
            middleImage = UIImage(named: "vehicleMonitor_empty_cell_flag_bg")
            break
        case VehicleStatusCodeEnum.busy.rawValue:
            backgroundColor = .hex("F05412")
            bigImage = UIImage(named: "vehicleMonitoring_busy_big")
            middleImage = UIImage(named: "vehicleMonitor_busy_cell_onlne_bg")
            break
        case VehicleStatusCodeEnum.BuyBusy.rawValue:
            backgroundColor = .hex("F05412")
            bigImage = UIImage(named: "vehicleMonitoring_busy_big")
            middleImage = UIImage(named: "vehicleMonitor_busy_cell_onlne_bg")
            break
        default:
            backgroundColor = .hex("858585")
            bigImage = UIImage(named: "vehicleMonitoring_offline_big")
            middleImage = UIImage(named: "vehicleMonitor_offline_cell_flag_bg")
            break
        }
        
        switch vehicleModel.onlineStatus?.code {
        case OnlineStatusModel.OnlineStatusCodeEnum.onLine.rawValue:
            annotationView.bigStateLabel.textColor = .white
            annotationView.middleStateLabel.textColor = .white
            break
        default:
            annotationView.bigStateLabel.textColor = .hex("CCCCCC")
            annotationView.middleStateLabel.textColor = .hex("CCCCCC")
            break
        }
        
        if vehicleModel.isSelected == true {
            annotationView.bigImageView.isHidden = false
            annotationView.bigStateLabel.isHidden = false
            annotationView.smallImageView.isHidden = true
            annotationView.middleImageView.isHidden = true
            annotationView.bigImageView.image = bigImage
            annotationView.bigStateLabel.text = vehicleModel.vehicleTypeStr
            annotationView.titleLabel.backgroundColor = .hex("FFFFFF")
        }else{
            annotationView.bigImageView.isHidden = true
            annotationView.bigStateLabel.isHidden = true
            if shouldShowSmallAnnotation == true {
                annotationView.smallImageView.isHidden = false
                annotationView.middleImageView.isHidden = true
                annotationView.middleStateLabel.isHidden = true
                annotationView.titleLabel.isHidden = true
                annotationView.smallImageView.backgroundColor = backgroundColor
            }else{
                annotationView.smallImageView.isHidden = true
                annotationView.middleImageView.isHidden = false
                annotationView.middleStateLabel.isHidden = false
                annotationView.titleLabel.isHidden = false
                annotationView.middleImageView.image = middleImage
                annotationView.middleStateLabel.text = vehicleModel.vehicleTypeStr
            }
            annotationView.titleLabel.backgroundColor = .clear
        }
        
        annotationView.titleLabel.text = vehicleModel.vehicleName
    }
    
    func selectVehicle(selectState: Bool,vehicleModel: DispatchVehicleListDataModel, currentTableViewVehicleModels: [DispatchVehicleListDataModel],selectIndex: Int, mapView: MAMapView) {
        
        resetSelectedOfDataModel()
        
        /// 在当前mapModel中查找vehicleId，如果找到的话就先删除再添加
        if let selectedModel = currentTableViewVehicleModels.first(where: {[weak self] model in
            return model.vehicleId == self?.selectedVehicleId
        }) {
            if let tag = currentTableViewVehicleModels.firstIndex(where: { model in
                return selectedModel.vehicleId == model.vehicleId
            }) {
                if let annotation = mapView.annotations.first(where: { annotation in
                    let pointAnnotation = annotation as? MAPointAnnotation
                    return pointAnnotation?.vehicleId == selectedModel.vehicleId
                }) {
                    mapView.removeAnnotation(annotation as? MAAnnotation)
                    
                    selectedModel.isSelected = false
                    let coordinate = CLLocationCoordinate2D(latitude: Double(selectedModel.lat ?? "0") ?? 0, longitude: Double(selectedModel.lon ?? "0") ?? 0)
                    let pointAnnotation = MAPointAnnotation.init()
                    pointAnnotation.annotationClass = DispatchMapStatePointAnnotation.self
                    pointAnnotation.coordinate = coordinate
                    pointAnnotation.tag = tag
                    mapView.addAnnotation(pointAnnotation)
                }
            }
        }
        
        /// 找到当前的车辆
        /// 移除之前的annotation
        if let oldAnnotation = mapView.annotations.first(where: { annotation in
            let pointAnnotation = annotation as? MAPointAnnotation
            return pointAnnotation?.tag == selectIndex
        }) {
            mapView.removeAnnotation(oldAnnotation as? MAAnnotation)
        }
        
        /// 将当前选中设为true
        vehicleModel.isSelected = selectState
        zIndex+=1
        vehicleModel.zIndex = zIndex

        /// 重新添加新的annotation
        let coordinate = CLLocationCoordinate2D(latitude: Double(vehicleModel.lat ?? "0") ?? 0, longitude: Double(vehicleModel.lon ?? "0") ?? 0)
        let pointAnnotation = MAPointAnnotation.init()
        pointAnnotation.annotationClass = DispatchMapStatePointAnnotation.self
        pointAnnotation.coordinate = coordinate
        pointAnnotation.tag = selectIndex
        mapView.addAnnotation(pointAnnotation)
        
        /// 记录当前的选中车辆id
        selectedVehicleId = vehicleModel.vehicleId

        /// 刷新tableview
        dispatchOrderView.dispatchPannelView.tableView.reloadData()
    }
    
    func showIncidentLocation(incidentCoordi: CLLocationCoordinate2D,destCoordi: CLLocationCoordinate2D?) {
        let incidentCoordiAnnotation = MAPointAnnotation()
        incidentCoordiAnnotation.dd_image = UIImage(named: "vehichleMonitoring_start_32")
        incidentCoordiAnnotation.coordinate = incidentCoordi
        incidentCoordiAnnotation.annotationClass = VehicleMonitoringIncidentLocationAnnotationView.self
        incidentCoordiAnnotation.tag = -1
        dispatchOrderView.maMapView.maMapView.addAnnotation(incidentCoordiAnnotation)
        if let destCoordi {
            let destCoordiAnnotation = MAPointAnnotation()
            destCoordiAnnotation.dd_image = UIImage(named: "vehichleMonitoring_terminal_32")
            destCoordiAnnotation.coordinate = destCoordi
            destCoordiAnnotation.annotationClass = VehicleMonitoringIncidentLocationAnnotationView.self
            destCoordiAnnotation.tag = -2
            dispatchOrderView.maMapView.maMapView.addAnnotation(destCoordiAnnotation)
        }
    }
    
    func hideIncidentLocation() {
        let annotations = dispatchOrderView.maMapView.maMapView.annotations.filter { item in
            let annotation = item as? MAPointAnnotation
            return annotation?.annotationClass == VehicleMonitoringIncidentLocationAnnotationView.self
        }
        dispatchOrderView.maMapView.maMapView.removeAnnotations(annotations)
    }
    
    func resetSelectedOfDataModel() {
        // 去掉其他tableview的选中
        for index in 0..<resultArr.count {
            let model = resultArr[index]
            model.isSelected = false
        }
    }
    
    func modifyMapAnchor() {
        let mapHeight = dispatchOrderView.maMapView.height
        var deltaH = 0.0
        if pannelPanGes.panGesValue.expandLevel == .max {
            deltaH = mapHeight - pannelPanGes.panGesValue.maxDisplayHeight
        }else if pannelPanGes.panGesValue.expandLevel == .default {
            deltaH = mapHeight - pannelPanGes.panGesValue.defaultDisplayHeight
        }else{
            deltaH = mapHeight - pannelPanGes.panGesValue.minDisplayHeight
        }
        let scale = (deltaH/2) / (mapHeight/2)
        dispatchOrderView.maMapView.maMapView.screenAnchor = CGPoint(x: 0.5, y: 0.5 * scale)
    }
    
    func showMapCenter(with vehicleModel: DispatchVehicleListDataModel) {
        /// 将镜头设置为选中的item,需要修改锚点
        if let lat = vehicleModel.lat,let lon = vehicleModel.lon {
            modifyMapAnchor()

            dispatchOrderView.maMapView.maMapView.setCenter(CLLocationCoordinate2D(latitude: Double(lat) ?? 0, longitude: Double(lon) ?? 0), animated: true)
        }
    }
}

extension DispatchOrderController : UITableViewDelegate,UITableViewDataSource {
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return resultArr.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? DispatchOrderPannelCell
        if cell == nil {
            cell = DispatchOrderPannelCell.init(style: .default, reuseIdentifier: "cell")
        }
        let model = resultArr[indexPath.item]
        
        switch model.vehicleStatus?.code {
        case VehicleStatusCodeEnum.offLine.rawValue,VehicleStatusCodeEnum.lostConnection.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_offline_cell_flag_bg")
            cell?.stateLabel.textColor = .hex("787878")
            cell?.name.textColor = .hex("787878")
            cell?.distance.textColor = .hex("787878")
            break
        case VehicleStatusCodeEnum.onLine.rawValue,VehicleStatusCodeEnum.leisure.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_empty_cell_flag_bg")
            cell?.stateLabel.textColor = .hex("3364B7")
            cell?.name.textColor = .hex("3364B7")
            cell?.distance.textColor = .hex("3364B7")
            break
        case VehicleStatusCodeEnum.busy.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_busy_cell_onlne_bg")
            cell?.stateLabel.textColor = .hex("FA5714")
            cell?.name.textColor = .hex("FA5714")
            cell?.distance.textColor = .hex("FA5714")
            break
        case VehicleStatusCodeEnum.BuyBusy.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_busy_cell_onlne_bg")
            cell?.stateLabel.textColor = .hex("FA5714")
            cell?.name.textColor = .hex("FA5714")
            cell?.distance.textColor = .hex("FA5714")
            break
        default:
            cell?.icon.image = UIImage(named: "vehicleMonitor_offline_cell_flag_bg")
            cell?.stateLabel.textColor = .hex("787878")
            cell?.name.textColor = .hex("787878")
            cell?.distance.textColor = .hex("787878")
            break
        }
        
        switch model.onlineStatus?.code {
        case OnlineStatusModel.OnlineStatusCodeEnum.onLine.rawValue:
            cell?.iconStateLabel.textColor = .white
            break
        default:
            cell?.iconStateLabel.textColor = .hex("CCCCCC")
            break
        }
        
        cell?.iconStateLabel.text = model.vehicleTypeStr
        
        var status = model.vehicleStatus?.label ?? ""
        if model.onlineStatus?.code == OnlineStatusModel.OnlineStatusCodeEnum.lostConnection.rawValue {
            status = status + "," + (model.onlineStatus?.label ?? "")
        }
        cell?.stateLabel.text = (model.vehicleName ?? "")+"/"+status
        cell?.name.text = model.driverName
        
        if let distance = model.distance {
            cell?.distance.text = String(distance)+"km"
        }
        
        if model.driverPhone?.isEmpty == false {
            cell?.phoneButton.snp.updateConstraints({ make in
                make.width.equalTo(auto(24))
            })
        }else{
            cell?.phoneButton.snp.updateConstraints({ make in
                make.width.equalTo(0)
            })
        }
        
        cell?.phoneButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { _ in
                if let phone = model.driverPhone {
                    URLLINKS.openUrl(type: .phone, appending: phone)
                }
            })
            .disposed(by: cell!.disposeBag)
        
        cell?.dispatchButton.rx.tap
            .subscribe(onNext: {[weak self] _ in
                self?.dispatchOrderRelay.accept(model)
            })
            .disposed(by: cell!.disposeBag)
        
        if USERP.canDealWith == true {
            cell?.dispatchButton.isHidden = false
        }else{
            cell?.dispatchButton.isHidden = true
        }
        return cell!
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = resultArr[indexPath.item]
        selectVehicle(selectState: true,vehicleModel: model, currentTableViewVehicleModels: resultArr, selectIndex: indexPath.item, mapView: dispatchOrderView.maMapView.maMapView)
        showMapCenter(with: model)
    }
}

extension DispatchOrderController : 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 == DispatchMapStatePointAnnotation.self{
                let DriverPointReuseIndentifier = "DispatchMapStatePointAnnotation"
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: DriverPointReuseIndentifier) as? DispatchMapStatePointAnnotation
                if annotationView == nil {
                    annotationView = DispatchMapStatePointAnnotation.init(annotation: pointAnnotation, reuseIdentifier: DriverPointReuseIndentifier)
                }
                annotationView!.annotation = pointAnnotation
                let model = resultArr[pointAnnotation.tag]

                /// 绑定车辆id到annotation
                pointAnnotation.vehicleId = model.vehicleId
                annotationView!.annotation = pointAnnotation
                annotationView?.zIndex = model.zIndex ?? 0
                
                if let annotationView, let shouldShowSmallAnnotation {
                    annotationViewStateConfig(annotationView: annotationView, vehicleModel: model, shouldShowSmallAnnotation: shouldShowSmallAnnotation)
                }
                
                let labelSize = annotationView?.titleLabel.sizeThatFits(CGSize(width: auto(100), height: .infinity)) ?? .zero
                let annotationViewW = labelSize.width
                let annotationViewH = auto(50) + labelSize.height
                annotationView?.frame = CGRect(origin: (annotationView?.frame.origin)!, size: CGSize(width: annotationViewW, height: annotationViewH))
                
                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!
            }
            
            if pointAnnotation.annotationClass == VehicleMonitoringIncidentLocationAnnotationView.self {
                let incidentPointReuseIndentifier = "VehicleMonitoringIncidentLocationAnnotationView"
                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: incidentPointReuseIndentifier) as? VehicleMonitoringIncidentLocationAnnotationView
                if annotationView == nil {
                    annotationView = VehicleMonitoringIncidentLocationAnnotationView.init(annotation: pointAnnotation, reuseIdentifier: incidentPointReuseIndentifier)
                }
                annotationView!.annotation = pointAnnotation
                annotationView!.image = pointAnnotation.dd_image
                annotationView!.zIndex = Int.max
                return annotationView!
            }
        }

        return MAAnnotationView.init(annotation: annotation, reuseIdentifier: "cell")
    }
    
    public func dd_mapView(_ mapView: MAMapView, didAnnotationViewTapped view: MAAnnotationView) {
        zIndex += 1
        
        if let tapPointAnnotation = view.annotation as? MAPointAnnotation {
            let model = resultArr[tapPointAnnotation.tag]
            selectVehicle(selectState: true,vehicleModel: model, currentTableViewVehicleModels: resultArr, selectIndex: tapPointAnnotation.tag, mapView: mapView)
        }
    }
    
    public func dd_mapView(_ mapView: MAMapView, mapDidZoomByUser wasUserAction: Bool) {
        /// 缩小过一次后就不需要频繁调用移除添加
        if mapView.zoomLevel <= 14 {
            shouldShowSmallAnnotation = true
            
            if isShowSmallAnnotation == false {
                let annotations = mapView.annotations
                mapView.removeAnnotations(annotations)
                mapView.addAnnotations(annotations)
                
                isShowSmallAnnotation = true
            }
        }else{
            shouldShowSmallAnnotation = false

            if isShowSmallAnnotation == true {
                let annotations = mapView.annotations
                mapView.removeAnnotations(annotations)
                mapView.addAnnotations(annotations)
                isShowSmallAnnotation = false
            }
        }
        
    }
}

open class DispatchOrderController : ZDViewController {
    private let disposeBag = DisposeBag()
    
    private let dispatchOrderView = DispatchOrderView()
    private let bottomView = DDView()
    
    private let userOrderId : Int
    private let taskOrderId : Int
    private let serviceAddressLat : Double?
    private let serviceAddressLon : Double?
    
    private var resultArr : [DispatchVehicleListDataModel] = []

    private let dispatchOrderRelay = ReplayRelay<DispatchVehicleListDataModel>.create(bufferSize: 1)
    public var dispatchCompletionHandler: ((Int) -> Void)?
    
    private var shouldShowSmallAnnotation : Bool? = true /// 用于标记是否需要显示最小的annotation
    private var isShowSmallAnnotation : Bool? = false /// 用于标记是否已经显示最小的annotation
    
    public var zIndex = 0 /// 用于annotation的位置靠前靠后

    private var selectedModel : DispatchVehicleListDataModel? /// 用于选中
    private var selectedVehicleId : Int? /// 用于选中

    private let pannelPanGes = DDUIPanGestureRecognizer.init() /// 用于pannel的拖动效果

    public init(userOrderId:Int,taskOrderId:Int,serviceAddressLat:Double?,serviceAddressLon:Double?) {
        self.userOrderId = userOrderId
        self.taskOrderId = taskOrderId
        self.serviceAddressLat = serviceAddressLat
        self.serviceAddressLon = serviceAddressLon
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        let image = UIImage(named: "dispatchOrder_back")?.withRenderingMode(.alwaysOriginal)
        dd_backBarButtonItem?.image = image
        dd_navigationBarBackgroundColor = .clear
        addSubviews()
        addActions()
    }

    func addSubviews() {
        view.addSubview(dispatchOrderView)
        
        bottomView.backgroundColor = .white
        view.addSubview(bottomView)
        
        dispatchOrderView.maMapView.maMapView.isRotateCameraEnabled = false
        dispatchOrderView.maMapView.delegate = self
        dispatchOrderView.dispatchPannelView.tableView.delegate = self
        dispatchOrderView.dispatchPannelView.tableView.dataSource = self
        
        pannelPanGes.panGesValue.from = .bottom
        pannelPanGes.panGesValue.expandLevel = .max
        pannelPanGes.expandLevelChangedHandler = {[weak self] old, new in
            self?.modifyMapAnchor()
        }
        dispatchOrderView.dispatchPannelView.addGestureRecognizer(pannelPanGes)
    }
    
    open override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        dispatchOrderView.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        bottomView.snp.remakeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(view.safeAreaInsets.bottom)
        }
    }
    
    open override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        var bottom : CGFloat = 0
        if view.safeAreaInsets.bottom != 0 {
            bottom = view.safeAreaInsets.bottom
        }
        
        pannelPanGes.panGesValue.minDisplayHeight = dispatchPannelViewTopInset + bottom
        pannelPanGes.panGesValue.maxDisplayHeight = dispatchPannelViewHeight
        pannelPanGes.panGesValue.defaultDisplayHeight = dispatchPannelViewHeight
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .darkContent
    }
}

open class DispatchOrderPannelCell : DDTableViewCell {
    private let radiusView : DDView
    public let icon : DDImageView
    public let iconStateLabel : DDLabel
    public let stateLabel : DDLabel
    public let nameView : DDView
    public let name : DDLabel
    public let phoneButton : DDButton
    public let distance : DDLabel
    public let dispatchButton : DDButton
    public var dispatchLayer : CAGradientLayer = {
        var layer = CAGradientLayer.init()
        layer.startPoint = CGPoint(x: 0, y: 0)
        layer.endPoint = CGPoint(x: 1, y: 1)
        layer.locations = [0.0,1.0]
        layer.colors = [UIColor.hex("FF5A2C").cgColor,UIColor.hex("FE9D4D").cgColor]
        layer.cornerRadius = auto(4)
        layer.masksToBounds = true
        return layer
    }()
    public var disposeBag = DisposeBag()
    
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        radiusView = DDView()
        icon = DDImageView()
        iconStateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(10)), textColor: .white)
        stateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("3364B7"))
        nameView = DDView()
        name = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("3364B7"))
        phoneButton = DDButton.dd_initCustom()
        distance = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("3364B7"))
        dispatchButton = DDButton.dd_initCustom()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        
//        stateLabel.lineBreakMode = .byTruncatingMiddle
        radiusView.backgroundColor = .white
        contentView.addSubview(radiusView)
        radiusView.addSubview(icon)
        iconStateLabel.textAlignment = .center
        icon.addSubview(iconStateLabel)
        stateLabel.numberOfLines = 0
        radiusView.addSubview(stateLabel)
        radiusView.addSubview(nameView)
        name.numberOfLines = 0
        nameView.isUserInteractionEnabled = true
        nameView.addSubview(name)
        phoneButton.setImage(UIImage(named: "vehicleMonitor_call_cell"), for: .normal)
        phoneButton.isUserInteractionEnabled = true
        nameView.addSubview(phoneButton)
        distance.numberOfLines = 0
        radiusView.addSubview(distance)
        dispatchButton.layer.cornerRadius = auto(4)
        dispatchButton.layer.masksToBounds = true
        dispatchButton.setTitle("派单", for: .normal)
        dispatchButton.titleLabel?.font = .mediumFont(auto(12))
        dispatchButton.layer.insertSublayer(dispatchLayer, at: 0)
        radiusView.addSubview(dispatchButton)

        radiusView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.greaterThanOrEqualTo(auto(44)).priority(.high)
        }
        
        icon.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(auto(10))
            make.centerY.equalToSuperview()
        }
    
        iconStateLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        stateLabel.snp.makeConstraints { make in
            make.left.equalTo(icon.snp.right).offset(auto(5))
            make.centerY.equalToSuperview()
            make.width.equalTo(auto(95))
        }
        
        nameView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.greaterThanOrEqualTo(phoneButton)
        }
        
        name.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        phoneButton.snp.makeConstraints { make in
            make.left.equalTo(name.snp.right).priority(.high)
            make.width.height.equalTo(auto(24))
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }

        distance.snp.makeConstraints { make in
            make.right.equalTo(dispatchButton.snp.left).offset(-auto(5))
            make.centerY.equalToSuperview()
            make.width.equalTo(auto(60))
        }
        
        dispatchButton.snp.makeConstraints { make in
            make.right.equalTo(-auto(10))
            make.width.equalTo(auto(50))
            make.height.equalTo(auto(20))
            make.centerY.equalToSuperview()
        }
    }
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        dispatchLayer.frame = CGRectMake(0, 0, auto(50), auto(20))
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
}

open class DispatchOrderView : DDView {
    public let dispatchPannelView : DispatchOrderPannelView
    public let maMapView : DDMAMapView
    public override init(frame: CGRect) {
        dispatchPannelView = DispatchOrderPannelView()
        maMapView = DDMAMapView()
        super.init(frame: frame)
        
        CustomMapStyle.customMap(maMapView.maMapView)
        addSubview(maMapView)
        addSubview(dispatchPannelView)
        
        maMapView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
  
        dispatchPannelView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(dispatchPannelViewHeight)
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class DispatchOrderPannelView : DDView {
    private let radiusView : DDView
    public let tableView : DDTableView
    public let offlineView : DispatchOrderOfflineSchedulingView
    public let onlineButton : DDButton
    public let offlineButton : DDButton
    public let tapBackgroundView : DDImageView
    public override init(frame: CGRect) {
        radiusView = DDView()
        tableView = DDTableView.init(frame: CGRectZero, style: .plain)
        offlineView = DispatchOrderOfflineSchedulingView()
        onlineButton = DDButton.dd_initCustom()
        offlineButton = DDButton.dd_initCustom()
        tapBackgroundView = DDImageView.init()
        super.init(frame: frame)
        backgroundColor = .clear
        radiusView.backgroundColor = .clear
        addSubview(radiusView)
        tapBackgroundView.contentMode = .scaleAspectFill
        radiusView.addSubview(tapBackgroundView)
        onlineButton.setImage(UIImage(named: "dispatchOrder_online_unselected"), for: .normal)
        onlineButton.setImage(UIImage(named: "dispatchOrder_online_selected"), for: .selected)
        onlineButton.setTitle("调度给app", for: .normal)
        onlineButton.setTitle("调度给app", for: .selected)
        onlineButton.setTitleColor(.hex("585E6F").alpha(0.7), for: .normal)
        onlineButton.setTitleColor(.hex("000000"), for: .selected)
        onlineButton.titleLabel?.font = .mediumFont(auto(16))
        onlineButton.dd_customize(with: .ImageLeftPaddingTitleRightWithWholeCenter, padding: auto(10))
        radiusView.addSubview(onlineButton)
        offlineButton.setImage(UIImage(named: "dispatchOrder_offline_unselected"), for: .normal)
        offlineButton.setImage(UIImage(named: "dispatchOrder_offline_selected"), for: .selected)
        offlineButton.setTitle("调度给小程序", for: .normal)
        offlineButton.setTitle("调度给小程序", for: .selected)
        offlineButton.setTitleColor(.hex("585E6F").alpha(0.7), for: .normal)
        offlineButton.setTitleColor(.hex("000000"), for: .selected)
        offlineButton.titleLabel?.font = .mediumFont(auto(16))
        offlineButton.dd_customize(with: .ImageLeftPaddingTitleRightWithWholeCenter, padding: auto(10))
        radiusView.addSubview(offlineButton)
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        radiusView.addSubview(tableView)
        radiusView.addSubview(offlineView)
        
        radiusView.layer.cornerRadius = auto(4)
        radiusView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-safeAreaInsets.bottom)
        }
        
        tapBackgroundView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(-auto(20))
            make.height.equalTo(dispatchPannelViewTopInset + auto(20))
        }
        
        onlineButton.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.height.equalTo(dispatchPannelViewTopInset)
            make.width.equalToSuperview().multipliedBy(0.5)
            make.left.equalToSuperview()
        }
        
        offlineButton.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(dispatchPannelViewTopInset)
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(tapBackgroundView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        offlineView.snp.makeConstraints { make in
            make.top.equalTo(tapBackgroundView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class DispatchOrderOfflineSchedulingView : DDView {
    public let name : DispatchOrderOfflineSchedulingItemView
    public let phone : DispatchOrderOfflineSchedulingItemView
    public let license : DispatchOrderOfflineSchedulingItemView
    public let rewriteButton : DDButton
    public let submitButton : DDButton
    override init(frame: CGRect) {
        name = DispatchOrderOfflineSchedulingItemView()
        phone = DispatchOrderOfflineSchedulingItemView()
        license = DispatchOrderOfflineSchedulingItemView()
        rewriteButton = DDButton.dd_initCustom()
        submitButton = DDButton.dd_initCustom()
        super.init(frame: frame)
        backgroundColor = .white
        name.titleLabel.text = "司机姓名"
        name.textFiled.attributedPlaceholder = NSAttributedString(string: dispatchOrderInputName,attributes: [.font:UIFont.mediumFont(auto(14)),.foregroundColor:UIColor.hex("A1A1A1")])
        addSubview(name)
        phone.titleLabel.text = "司机电话"
        phone.textFiled.attributedPlaceholder = NSAttributedString(string: dispatchOrderInputPhone,attributes: [.font:UIFont.mediumFont(auto(14)),.foregroundColor:UIColor.hex("A1A1A1")])
        addSubview(phone)
        license.titleLabel.text = "车牌号码"
        license.textFiled.attributedPlaceholder = NSAttributedString(string: dispatchOrderInputLicense,attributes: [.font:UIFont.mediumFont(auto(14)),.foregroundColor:UIColor.hex("A1A1A1")])
        addSubview(license)
        rewriteButton.layer.cornerRadius = auto(4)
        rewriteButton.layer.borderColor = UIColor.hex("DDDDDD").cgColor
        rewriteButton.layer.borderWidth = 1
        rewriteButton.setTitle("重新填写", for: .normal)
        rewriteButton.setTitleColor(.hex("323643").alpha(0.9), for: .normal)
        rewriteButton.titleLabel?.font = .mediumFont(auto(14))
        addSubview(rewriteButton)
        submitButton.layer.cornerRadius = auto(4)
        submitButton.backgroundColor = .hex("2A5094")
        submitButton.setTitle("确定提交", for: .normal)
        submitButton.setTitleColor(.white, for: .normal)
        submitButton.titleLabel?.font = .mediumFont(auto(14))
        addSubview(submitButton)
        
        name.snp.makeConstraints { make in
            make.top.equalTo(auto(30))
            make.left.right.equalToSuperview()
            make.height.equalTo(auto(40))
        }
        
        phone.snp.makeConstraints { make in
            make.top.equalTo(name.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(auto(40))
        }
        
        license.snp.makeConstraints { make in
            make.top.equalTo(phone.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(auto(40))
        }
        
        rewriteButton.snp.makeConstraints { make in
            make.right.equalTo(snp.centerX).offset(-auto(5))
            make.top.equalTo(license.snp.bottom).offset(auto(30))
            make.width.equalTo(auto(150))
            make.height.equalTo(auto(40))
        }
        
        submitButton.snp.makeConstraints { make in
            make.left.equalTo(snp.centerX).offset(auto(5))
            make.top.equalTo(rewriteButton)
            make.width.equalTo(auto(150))
            make.height.equalTo(auto(40))
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class DispatchOrderOfflineSchedulingItemView : DDView {
    public let titleLabel : DDLabel
    public let textFiled : DDTextField
    public let line : DDView
    override init(frame: CGRect) {
        titleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(14)), textColor: .hex("323643").alpha(0.9))
        textFiled = DDTextField.init()
        line = DDView.init()
        super.init(frame: frame)
        
        addSubview(titleLabel)
        textFiled.textAlignment = .right
        textFiled.font = .mediumFont(auto(14))
        textFiled.textColor = .hex("323643").alpha(0.9)
        addSubview(textFiled)
        line.backgroundColor = .hex("F5F5F5")
        addSubview(line)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(auto(30))
            make.centerY.equalToSuperview()
        }
        
        textFiled.snp.makeConstraints { make in
            make.right.equalTo(-auto(30))
            make.centerY.equalToSuperview()
        }
        
        line.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalTo(auto(30)).priority(.high)
            make.right.equalTo(-auto(30))
            make.height.equalTo(1)
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class DispatchMapSericeAddressPointAnnotation : MAAnnotationView {
    private let topImageView : DDImageView
    private let bottonImageView : DDImageView
    
    override init!(annotation: MAAnnotation!, reuseIdentifier: String!) {
        topImageView = DDImageView(image: UIImage(named: "dispatchOrder_serviceAddress_top"))
        bottonImageView = DDImageView(image: UIImage(named: "dispatchOrder_serviceAddress_bottom"))
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        
        addSubview(bottonImageView)
        addSubview(topImageView)
        
        topImageView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(30)
            make.width.equalTo(20)
        }
        
        bottonImageView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.height.equalTo(15)
        }
        frame = CGRect(x: 0, y: 0, width: 20, height: 40)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class DispatchMapStatePointAnnotation : MAAnnotationView {
    public let clearView : DDView
    public var disposeBag : DisposeBag
    public var smallImageView : DDImageView
    public var middleImageView : DDImageView
    public var bigImageView : DDImageView
    public var titleLabel : DDLabel
    public var middleStateLabel : DDLabel
    public var bigStateLabel : DDLabel
    public var middleWorkingCountlabel : DDLabel
    public var bigWorkingCountlabel : DDLabel
    override init!(annotation: MAAnnotation!, reuseIdentifier: String!) {
        clearView = DDView.init()
        disposeBag = DisposeBag()
        smallImageView = DDImageView()
        middleImageView = DDImageView()
        bigImageView = DDImageView()
        titleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(11), textColor: .hex("03030F"))
        middleStateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(10), textColor: .white)
        bigStateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(18), textColor: .white)
        middleWorkingCountlabel = DDLabel.dd_init(withText: "", font: .mediumFont(7), textColor: .white)
        bigWorkingCountlabel = DDLabel.dd_init(withText: "", font: .mediumFont(9), textColor: .white)
        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(){
        clearView.isUserInteractionEnabled = false
        addSubview(clearView)
        
        smallImageView.layer.cornerRadius = auto(5)
        smallImageView.layer.borderColor = UIColor.white.cgColor
        smallImageView.layer.borderWidth = 1
        smallImageView.backgroundColor = .hex("858585")
        clearView.addSubview(smallImageView)
        
        titleLabel.textAlignment = .center
        clearView.addSubview(titleLabel)
        
        middleImageView.layer.cornerRadius = auto(11)
        middleImageView.layer.borderColor = UIColor.white.cgColor
        middleImageView.layer.borderWidth = 1
        middleImageView.backgroundColor = .hex("858585")
        clearView.addSubview(middleImageView)
        middleImageView.addSubview(middleStateLabel)
        middleWorkingCountlabel.backgroundColor = .hex("F93D3D")
        middleWorkingCountlabel.textAlignment = .center
        middleWorkingCountlabel.layer.borderColor = UIColor.white.cgColor
        middleWorkingCountlabel.layer.borderWidth = 1
        middleImageView.addSubview(middleWorkingCountlabel)
        
        clearView.addSubview(bigImageView)
        bigImageView.addSubview(bigStateLabel)
        bigWorkingCountlabel.backgroundColor = .hex("F93D3D")
        bigWorkingCountlabel.textAlignment = .center
        bigWorkingCountlabel.layer.borderColor = UIColor.white.cgColor
        bigWorkingCountlabel.layer.borderWidth = 1
        bigImageView.addSubview(bigWorkingCountlabel)
        
        clearView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        smallImageView.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.height.equalTo(auto(10))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
        }
        
        middleImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().priority(.high)
            make.width.height.equalTo(auto(22))
            make.bottom.equalTo(titleLabel.snp.top)
        }

        middleStateLabel.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(middleImageView)
        }
        
        middleWorkingCountlabel.layer.cornerRadius = auto(5)
        middleWorkingCountlabel.layer.masksToBounds = true
        middleWorkingCountlabel.isHidden = true
        middleWorkingCountlabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(-auto(5))
            make.right.equalToSuperview().offset(auto(5))
            make.width.height.equalTo(10)
        }
        
        bigImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().priority(.high)
            make.width.equalTo(auto(42))
            make.height.equalTo(auto(50))
            make.bottom.equalTo(titleLabel.snp.top)
        }
        
        bigStateLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-auto(4))
        }
        
        bigWorkingCountlabel.layer.cornerRadius = auto(7.5)
        bigWorkingCountlabel.layer.masksToBounds = true
        bigWorkingCountlabel.isHidden = true
        bigWorkingCountlabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(-auto(2.5))
            make.right.equalToSuperview().offset(auto(2.5))
            make.width.height.equalTo(15)
        }
    }
}
