//
//  WebViewTool.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/21.
//

import Foundation
import RxSwift
import RxRelay

public let WEBTOOL = WebViewTool.default

open class WebViewTool : NSObject {
    public static let `default` = WebViewTool()
    
    private var requestModelRelay = ReplayRelay<WebViewNameEnum>.create(bufferSize: 1)
    private var appendingRelay = ReplayRelay<String?>.create(bufferSize: 1)

    private var disposeBag = DisposeBag()
    public var h5Models : DispatchAppH5UrlDataModel?

    enum WebViewNameEnum : String {
        case todoList = "待办事项"
        case workOrderReconciliation = "工单记账"
        case vehicleManage = "车辆管理"
        case driverManage = "司机管理"
        case invoicingNotify = "开票通知"
        case reporting = "报备"
        case supplySettlement = "补结算单"
        case workOrderDetail = "工单详情页"
    }
    
    public override init() {
        super.init()
        Observable.zip(requestModelRelay, appendingRelay)
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] (name,appending) in
                if let _ = self?.h5Models {
                    self?.openWebView(name: name,appending: appending)
                }else{
                    let tabBarVc = UIApplication.shared.dd_keyWindow.rootViewController as? UITabBarController
                    let nav = tabBarVc?.selectedViewController as? UINavigationController
                    nav?.topViewController?.view.dd_showHUD()
                }
            })
            .filter({[weak self] (name,appending) in
                return self?.h5Models == nil
            })
            .throttle(RxTimeInterval.seconds(20), scheduler: ConcurrentMainScheduler.instance)
            .flatMapLatest { (name,appending) in
                return Observable.zip(RQ.dispatchAppH5Urls().asObservable(), Observable.just(name),Observable.just(appending))
            }
            .retry(5)
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] (response,name,appending) in
                let tabBarVc = UIApplication.shared.dd_keyWindow.rootViewController as? UITabBarController
                let nav = tabBarVc?.selectedViewController as? UINavigationController
                nav?.topViewController?.view.dd_hideHUD()

                self?.h5Models = response?.data
                self?.openWebView(name: name,appending: appending)
            })
            .disposed(by: disposeBag)

    }
    
    private func openWebView(name:WebViewNameEnum,appending:String?) {
        var vc : WebViewController?
        switch name {
        case .todoList:
            vc = WebViewController(title: WebViewNameEnum.todoList.rawValue, url: "\((h5Models?.todoList)!)?token=\((USER.token)!)")
            break
        case .workOrderReconciliation:
            vc = WebViewController(showNavBar:false, title: WebViewNameEnum.workOrderReconciliation.rawValue, url: "\((h5Models?.workOrderReconciliation)!)?token=\((USER.token)!)")
            break
        case .vehicleManage:
            vc = WebViewController(showNavBar:false, title: WebViewNameEnum.vehicleManage.rawValue, url: "\((h5Models?.vehicleManage)!)?token=\((USER.token)!)")
            break
        case .driverManage:
            vc = WebViewController(showNavBar:false, title: WebViewNameEnum.driverManage.rawValue, url: "\((h5Models?.driverManage)!)?token=\((USER.token)!)")
            break
        case .invoicingNotify:
            vc = WebViewController(showNavBar:false, title: WebViewNameEnum.invoicingNotify.rawValue, url: "\((h5Models?.invoicingNotify)!)?token=\((USER.token)!)")
            break
        case .reporting:
            vc = WebViewController(title: WebViewNameEnum.reporting.rawValue, url: "\((h5Models?.reporting)!)?token=\((USER.token)!)"+(appending ?? ""))
            break
        case .supplySettlement:
            vc = WebViewController(title: WebViewNameEnum.supplySettlement.rawValue, url: "\((h5Models?.supplySettlement)!)?token=\((USER.token)!)"+(appending ?? ""))
            break
        case .workOrderDetail:
            vc = WebViewController(title: WebViewNameEnum.workOrderDetail.rawValue, url: "\((h5Models?.workOrderDetail)!)?token=\((USER.token)!)"+(appending ?? ""))
            break
        }
        
        if let vc {
            let tabVc = UIApplication.shared.dd_keyWindow.rootViewController as? MainTabBarController
            let nav = tabVc?.selectedViewController as? UINavigationController
              nav?.pushViewController(vc, animated: true)
        }
    }

    func open(name:WebViewNameEnum,appending:String?) {
        requestModelRelay.accept(name)
        appendingRelay.accept(appending)
    }
}
