//
//  VehicleMonitoringListController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/15.
//

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

extension VehicleMonitoringListController : UITableViewDelegate,UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? VehicleMonitoringListCell
        if cell == nil {
            cell = VehicleMonitoringListCell(style: .default, reuseIdentifier: "cell")
        }
        let model = models[indexPath.item]

        /// 排班
        if isPaiban == true {
            cell?.dateLabel.isHidden = false
            cell?.dateLabel.text = (model.rosterStartTime?.components(separatedBy: " ").last ?? "") + "~" + (model.rosterEndTime?.components(separatedBy: " ").last ?? "")
        }else if isAlarm == true {
            cell?.dateLabel.isHidden = true
        }else{
            cell?.dateLabel.isHidden = false
            cell?.dateLabel.text = nil
        }
        
        if model.isSelected == true {
            cell?.flagIcon.isHidden = false
        }else{
            cell?.flagIcon.isHidden = true
        }
        cell?.nameLabel.text = model.driverName
        cell?.vehicleLabel.text = model.vehicleName
        cell?.stateLabel.text = model.vehicleTypeStr
        cell?.workingCountLabel.isHidden = !model.shouldShowWorkingCount
        if let workingCount = model.workingCount {
            cell?.workingCountLabel.text = String(workingCount)
        }
        
        switch model.vehicleStatus?.code {
        case VehicleStatusCodeEnum.offLine.rawValue,VehicleStatusCodeEnum.lostConnection.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_offline_cell_flag_bg")
            break
        case VehicleStatusCodeEnum.onLine.rawValue,VehicleStatusCodeEnum.leisure.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_empty_cell_flag_bg")
            break
        case VehicleStatusCodeEnum.busy.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_busy_cell_onlne_bg")
            break
        case VehicleStatusCodeEnum.BuyBusy.rawValue:
            cell?.icon.image = UIImage(named: "vehicleMonitor_busy_cell_onlne_bg")
            break
        default:
            cell?.icon.image = UIImage(named: "vehicleMonitor_offline_cell_flag_bg")
            break
        }
        
        switch model.onlineStatus?.code {
        case OnlineStatusModel.OnlineStatusCodeEnum.onLine.rawValue:
            cell?.stateLabel.textColor = .white
            break
        default:
            cell?.stateLabel.textColor = .hex("CCCCCC")
            break
        }
        
        cell?.iconTapGes.rx.event
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                if self?.showDetailBlock != nil {
                    self?.showDetailBlock!(model,indexPath.item)
                }
            })
            .disposed(by: cell!.disposeBag)
        
        cell?.vehicleTapGes.rx.event
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                if self?.showDetailBlock != nil {
                    self?.showDetailBlock!(model,indexPath.item)
                }
            })
            .disposed(by: cell!.disposeBag)
        
        cell?.callButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                guard let driverPhone = model.driverPhone else {
                    self?.view.dd_makeToast("空号")
                    return
                }
                URLLINKS.openUrl(type: .phone, appending: driverPhone)
            })
            .disposed(by: cell!.disposeBag)
        return cell!
    }

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectCellBlock != nil {
            let model = models[indexPath.item]
            selectCellBlock!(model,indexPath.item)
        }
    }
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let maxContentH = vehicleMonitoringListView.tableView.rect(forSection: 0).height
        let tableViewH = vehicleMonitoringListView.tableView.height

        let maxOffSet = 100.0
        if tableViewH >= maxContentH {
            if scrollView.contentOffset.y > maxOffSet {
                if let showMaxBlock = showMaxBlock {
                    showMaxBlock()
                }
            }
        }else{
            let deltaH = maxContentH - tableViewH + maxOffSet
            if scrollView.contentOffset.y > deltaH {
                if let showMaxBlock = showMaxBlock {
                    showMaxBlock()
                }
            }
        }
        
    }
}

open class VehicleMonitoringListController : ZDViewController {
    public let vehicleMonitoringListView = VehicleMonitoringListView()
    public var models : [VehicleMonitorListDataModel.ItemModel] = []
    public var selectCellBlock: ((VehicleMonitorListDataModel.ItemModel, Int) -> Void)?
    public var showDetailBlock: ((VehicleMonitorListDataModel.ItemModel, Int) -> Void)?
    private var isPaiban : Bool?
    private var isAlarm : Bool?
    private var emptyView = EmptyView()
    public var showMaxBlock: (() -> Void)?

    public init(models:[VehicleMonitorListDataModel.ItemModel]?,isPaiban:Bool? = false,isAlarm:Bool? = false) {
        self.isPaiban = isPaiban
        self.isAlarm = isAlarm
        if let models {
            self.models.append(contentsOf: models)
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        dd_navigationBarBarButtonItemAttributes = [.foregroundColor : UIColor.white]

        view.addSubview(vehicleMonitoringListView)
        vehicleMonitoringListView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        vehicleMonitoringListView.tableView.backgroundColor = .hex("FAFAFA")
        if self.models.isEmpty == false {
            emptyView.isHidden = true
        }else{
            emptyView.isHidden = false
        }
        vehicleMonitoringListView.tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.equalTo(auto(303))
            make.height.equalTo(auto(94))
        }
        
        vehicleMonitoringListView.tableView.delegate = self
        vehicleMonitoringListView.tableView.dataSource = self
    }
}

open class VehicleMonitoringListView : DDView {
    public let tableView : DDTableView
    public override init(frame: CGRect) {
        tableView = DDTableView.init(frame: frame, style: .plain)
        super.init(frame: frame)
        
        tableView.separatorStyle = .none
        tableView.contentInsetAdjustmentBehavior = .never
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open  class VehicleMonitoringListCell : DDTableViewCell {
    public var disposeBag : DisposeBag
    private let radiusView : DDView
    public let flagIcon : DDImageView
    public let icon : DDImageView
    public let workingCountLabel : DDLabel
    public let stateLabel : DDLabel
    public let vehicleLabel : DDLabel
    public let dateLabel : DDLabel
    public let nameLabel : DDLabel
    public let callButton : DDButton
    private let line : DDView
    public let iconTapGes : UITapGestureRecognizer
    public let vehicleTapGes : UITapGestureRecognizer
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        disposeBag = DisposeBag()
        radiusView = DDView()
        flagIcon = DDImageView(image: UIImage(named: "vehicleMonitoring_cellSelected"))
        icon = DDImageView()
        workingCountLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(7)), textColor: .white)
        stateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(10)), textColor: .white)
        vehicleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13.5)), textColor: .hex("0B0B0B"))
        dateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("0B0B0B"))
        nameLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13.5)), textColor: .hex("0B0B0B"))
        callButton = DDButton.dd_initCustom()
        callButton.setImage(UIImage(named:"vehicleMonitor_call_cell"), for: .normal)
        line = DDView()
        iconTapGes = UITapGestureRecognizer()
        vehicleTapGes = UITapGestureRecognizer()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        contentView.addSubview(radiusView)
        radiusView.addSubview(icon)
        radiusView.addSubview(flagIcon)
        stateLabel.textAlignment = .center
        icon.addSubview(stateLabel)
        workingCountLabel.textAlignment = .center
        workingCountLabel.backgroundColor = .hex("F93D3D")
        icon.addSubview(workingCountLabel)
        vehicleLabel.numberOfLines = 0
        radiusView.addSubview(vehicleLabel)
        dateLabel.numberOfLines = 0
        dateLabel.textAlignment = .center
        radiusView.addSubview(dateLabel)
        nameLabel.numberOfLines = 0
        radiusView.addSubview(nameLabel)
        radiusView.addSubview(callButton)
        line.backgroundColor = .hex("F2F3F6")
        radiusView.addSubview(line)
        icon.isUserInteractionEnabled = true
        icon.addGestureRecognizer(iconTapGes)
        vehicleLabel.isUserInteractionEnabled = true
        vehicleLabel.addGestureRecognizer(vehicleTapGes)
        
        radiusView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.greaterThanOrEqualTo(auto(44)).priority(.high)
        }
        
        flagIcon.snp.makeConstraints { make in
            make.left.equalTo(auto(10))
            make.centerY.equalToSuperview()
        }
        
        icon.snp.makeConstraints { make in
            make.left.equalTo(flagIcon.snp.right).offset(auto(5))
            make.centerY.equalToSuperview()
        }
        
        stateLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.height.equalTo(auto(20))
        }
        
        workingCountLabel.layer.cornerRadius = auto(5)
        workingCountLabel.layer.masksToBounds = true
        workingCountLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(-auto(5))
            make.right.equalToSuperview().offset(auto(5))
            make.width.height.equalTo(auto(10))
        }
        
        vehicleLabel.snp.makeConstraints { make in
            make.left.equalTo(icon.snp.right).offset(auto(7))
            make.centerY.equalToSuperview()
            make.right.lessThanOrEqualTo(radiusView.snp.centerX)
        }
        
        dateLabel.snp.makeConstraints { make in
            make.left.equalTo(vehicleLabel.snp.right).offset(auto(7))
            make.centerY.equalToSuperview()
            make.top.bottom.greaterThanOrEqualToSuperview().inset(auto(7))
        }
        
        callButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-auto(10))
            make.centerY.equalToSuperview()
            make.width.equalTo(auto(24))
            make.height.equalTo(auto(24))
        }
        
        nameLabel.snp.makeConstraints { make in
            make.right.equalTo(callButton.snp.left).offset(-auto(7))
            make.centerY.equalToSuperview()
            make.left.greaterThanOrEqualTo(radiusView.snp.centerX)
        }

        line.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(1)
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
}

extension VehicleMonitoringListController : JXCategoryListContentViewDelegate {
    public func listView() -> UIView! {
        return view
    }
}

