//
//  AcceptOrderTool.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/25.
//

import Foundation
import RxSwift
import RxCocoa

public let ACCEPTORDERTOOL = AcceptOrderTool.default

open class AcceptOrderTool : NSObject {
    public static let `default` = AcceptOrderTool()
    private let disposeBag = DisposeBag()
    
    func open(userInfo:[AnyHashable:Any]?) {
        let acceptOrderView = AcceptOrderView()
        acceptOrderView.titleLabel.text = "新订单"
        acceptOrderView.contentLabel.text = TOOL.getOrderString(userInfo: userInfo)
        acceptOrderView.readButton.setTitle("查看", for: .normal)
        acceptOrderView.cancelButton.setTitle("稍后查看", for: .normal)
        acceptOrderView.readButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {
                ENTRY.dismiss(name: acceptOrderViewEntry) {
                    DispatchQueue.main.async {
                        // 停止声音播放
                        TOOL.stopVoice()
                        // 来到首页的救援中-待接单
                        let tabBarVc = UIApplication.shared.dd_keyWindow.rootViewController as? MainTabBarController
                        let currentNav = tabBarVc?.selectedViewController as? UINavigationController
                        currentNav?.popToRootViewController(animated: true)
                        DispatchQueue.main.asyncAfter(deadline: .now()+0.25, execute: {
                            tabBarVc?.selectedIndex = 0
                            let nav = tabBarVc?.children.first as? UINavigationController
                            let vc = nav?.children.first as? RescueController
                            vc?.categoryView.selectItem(at: 0)
                        })
                    }
                }
            })
            .disposed(by: disposeBag)
        acceptOrderView.cancelButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { _ in
                ENTRY.dismiss(name: acceptOrderViewEntry) {
                    // 停止声音播放
                    TOOL.stopVoice()
                }
            })
            .disposed(by: disposeBag)
        
        ENTRY.showAcceptOrderEntry(view: acceptOrderView,name: acceptOrderViewEntry)
    }
}
