//
//  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

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]
        cell?.icon.isHidden = !(model.isSelected ?? false)
        cell?.indexLabel.text = String(indexPath.item + 1)+"."
        if isPaiban == true {
            cell?.dateLabel.text = (model.rosterStartTime ?? "") + "\n~\n" + (model.rosterEndTime ?? "")
        }else{
            var status = model.vehicleStatus?.label ?? ""
            if model.onlineStatus?.code == .lostConnection {
                status = status + ",掉"
            }
            cell?.dateLabel.text = (model.vehicleName ?? "")+"/"+status
        }
        cell?.nameLabel.text = model.driverName
        cell?.phoneLabel.text = model.driverPhone
        
        if self.isAlarm == true {
            if model.alarmType?.code == .busy {
                cell?.indexLabel.textColor = .hex("1C62D9")
                cell?.dateLabel.textColor = .hex("1C62D9")
                cell?.nameLabel.textColor = .hex("1C62D9")
                cell?.phoneLabel.textColor = .hex("1C62D9")
            }else{
                cell?.indexLabel.textColor = .hex("787878")
                cell?.dateLabel.textColor = .hex("787878")
                cell?.nameLabel.textColor = .hex("787878")
                cell?.phoneLabel.textColor = .hex("787878")
            }
        }else{
            if model.onlineStatus?.code == .onLine {
                cell?.indexLabel.textColor = .hex("1C62D9")
                cell?.dateLabel.textColor = .hex("1C62D9")
                cell?.nameLabel.textColor = .hex("1C62D9")
                cell?.phoneLabel.textColor = .hex("1C62D9")
            }else{
                cell?.indexLabel.textColor = .hex("787878")
                cell?.dateLabel.textColor = .hex("787878")
                cell?.nameLabel.textColor = .hex("787878")
                cell?.phoneLabel.textColor = .hex("787878")
            }
        }
        
        cell?.callButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { _ in
                TOOL.call(phone: model.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)
        }
    }
}

open class VehicleMonitoringListController : DDViewController {
    public let vehicleMonitoringListView = VehicleMonitoringListView()
    public var models : [VehicleMonitorListDataModel.ItemModel] = []
    public var selectCellBlock: ((VehicleMonitorListDataModel.ItemModel) -> Void)?
    private var isPaiban : Bool?
    private var isAlarm : Bool?
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        
        view.addSubview(vehicleMonitoringListView)
        vehicleMonitoringListView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        vehicleMonitoringListView.tableView.delegate = self
        vehicleMonitoringListView.tableView.dataSource = self
    }
    
    public func reloadCell(models:[VehicleMonitorListDataModel.ItemModel]?,isPaiban:Bool? = false,isAlarm:Bool? = false) {
        self.isPaiban = isPaiban
        self.isAlarm = isAlarm
        
        self.models.removeAll()
        if let models {
            self.models.append(contentsOf: models)
        }
        vehicleMonitoringListView.tableView.reloadData()
    }
}

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
        
        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 icon : DDImageView
    public let indexLabel : DDLabel
    public let dateLabel : DDLabel
    public let nameLabel : DDLabel
    public let phoneLabel : DDLabel
    public let callButton : DDButton
    public var callLayer : 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
    }()
    private let line : DDView
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        disposeBag = DisposeBag()
        radiusView = DDView()
        icon = DDImageView(image: UIImage(named: "vehicleMonitoring_cellSelected"))
        indexLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("1C62D9"))
        dateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("1C62D9"))
        nameLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("1C62D9"))
        phoneLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("1C62D9"))
        callButton = DDButton.dd_initCustom()
        line = DDView()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        
        contentView.addSubview(radiusView)
        icon.isHidden = true
        radiusView.addSubview(icon)
        radiusView.addSubview(indexLabel)
        dateLabel.numberOfLines = 0
        dateLabel.textAlignment = .center
        radiusView.addSubview(dateLabel)
        radiusView.addSubview(nameLabel)
        radiusView.addSubview(phoneLabel)
        callButton.layer.cornerRadius = auto(4)
        callButton.layer.insertSublayer(callLayer, at: 0)
        callButton.setTitle("呼叫", for: .normal)
        callButton.titleLabel?.font = .mediumFont(auto(13))
        radiusView.addSubview(callButton)
        line.backgroundColor = .hex("F2F3F6")
        radiusView.addSubview(line)
        
        radiusView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.greaterThanOrEqualTo(auto(44))
        }
        
        icon.snp.makeConstraints { make in
            make.left.equalTo(auto(15))
            make.centerY.equalToSuperview()
        }
        
        indexLabel.snp.makeConstraints { make in
            make.left.equalTo(icon.snp.right).offset(auto(5))
            make.centerY.equalToSuperview()
        }
        
        dateLabel.snp.makeConstraints { make in
            make.left.equalTo(indexLabel.snp.right).offset(auto(3))
            make.width.equalTo(auto(80))
            make.top.equalToSuperview().offset(auto(5))
            make.bottom.equalToSuperview().offset(-auto(5))
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(dateLabel.snp.right).offset(auto(5))
            make.width.equalTo(auto(60))
            make.centerY.equalToSuperview()
        }
        
        phoneLabel.snp.makeConstraints { make in
            make.left.equalTo(nameLabel.snp.right).offset(auto(5))
            make.width.equalTo(auto(100))
            make.centerY.equalToSuperview()
        }
        
        callButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-auto(10))
            make.centerY.equalToSuperview()
            make.width.equalTo(auto(50))
            make.height.equalTo(auto(20))
        }
        
        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()
        callLayer.frame = CGRectMake(0, 0, auto(50), auto(20))
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
}

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

