//
//  Initial.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/4.
//

import Foundation
import DDMAMapKit_Private
import IQKeyboardManagerSwift
import DDAutoUIKit_Private
import DDNetworkingOfAlamofireKit_Private
import Alamofire
import DDToastKit_Private
import DDCategoryKit_Private
import DDControlsKit_Private
import RxSwift
import Bugly

class Initial : NSObject {
    static let shareInstance = Initial.init()

    private let disposeBag = DisposeBag()
    
    private let locationManager = CLLocationManager()
    // MARK: <Third>
    func initThirdLib() {
        // bugly
        initBugly()
        
        // 键盘
        initIQKeyboard()

        // mamap
        initMaMapKey()

        // autoUI
        initAutoUI()
        
        // af
        initAF()
        
        // initCall
        initCall()

    }
    
    func initBugly() {
        Bugly.start(withAppId: BUGLYAPPID)
    }
    
    func initIQKeyboard(){
        IQKeyboardManager.shared.enable = true
    }
    
    func initMaMapKey(){
        DDMAMapView.start(withAppKey: MAAppKey)
        DDMAMapView.agreePrivacy()
        
        locationManager.requestWhenInUseAuthorization()
    }
    
    func initAutoUI() {
        let _ = AutoUI.default.getScale(size: 375)
    }
    
    func initAF() {
        DDAF.delegate = self
    }
    
    func initCall() {
        SC.callEvent { (isCallSuccess,callTime,duration) in
            SC.uploadRelay.accept(nil)
        }
        
        SC.uploadRelay
            .flatMapLatest { _ in
                return SC.getParameters()
            }
            .flatMapLatest { parameters in
                return RQ.uploadCallRecord(parameters: parameters)
            }
            .subscribe(onNext: { response in
            })
            .disposed(by: disposeBag)
    }
    
    func initRefreshToken() {
        // 刷新token,全屏都不许动
        Observable.just(1)
            .observe(on: MainScheduler.instance)
            .do(onNext: { _ in
                UIApplication.shared.dd_keyWindow.dd_showHUD()
            })
            .flatMapLatest { _ in
                return RQ.token(parameters: TokenParameters(refresh_token: USER.refreshToken!))
            }
            .observe(on: MainScheduler.instance)
            .do(onNext: { _ in
                UIApplication.shared.dd_keyWindow.dd_hideHUD()
            })
            .subscribe(onNext: { response in
                if response?.success == true {
                    USER.setToken(token: response?.data?.accessToken.tokenValue)
                    USER.setRefreshToken(token: response?.data?.refreshToken.tokenValue)
                }
                USER.refreshTokenSub.onNext(true)
            })
            .disposed(by: disposeBag)
    }
    
    func initPermission() {
        USERP.relay.accept(nil)
    }
    
    func initAppUpdate() {
        APPUPDATE.requestAppUpdateRelay.accept(.auto)
    }
    
    func initNewestMessage() {
        MCOUNT.newestMessage()
    }
    
    func initGongdanpici() {
        UserData.default.showGongdanpiciAlert()
    }
    
    // MARK: <RootViewController>
    func initRootViewController(){
        if USER.isLogin == true {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_loginSuccessToRescueController), object: nil)
        }else{
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_logoutSuccessToLoginController), object: nil)
        }
    }
    
    func changeRootViewController(window:UIWindow?) {
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Notification_logoutSuccessToLoginController), object: nil, queue: .main) { note in
            USER.clear()
            GROUP.clear()
            let nav = DDNavigationController(rootViewController: LoginController.init())
            window?.rootViewController = nav
        }
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Notification_loginSuccessToRescueController), object: nil, queue: .main) {[weak self] note in
            window?.rootViewController = MainTabBarController.init()
            self?.initPermission()
            self?.initAppUpdate()
            self?.initRefreshToken()
            self?.initNewestMessage()
            self?.initGongdanpici()
        }
        
    }
}

extension Initial : DDAlamofireDelegate {
    func networkErrorHandler<T>(response: AFDataResponse<T>) -> AFDataResponse<T> where T : Decodable {
        DispatchQueue.main.async {
            UIApplication.shared.dd_keyWindow.dd_makeToast(networkFailed)
        }
        return response
    }
    
    func errorCodeHandler<T>(response: AFDataResponse<T>) -> AFDataResponse<T> where T : Decodable {
        if response.response?.statusCode == 401 && (USER.isLogin == true) {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_logoutSuccessToLoginController), object: nil)
        }else if let data = response.data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers),let dic = json as? Dictionary<String, Any>,let msg = dic["msg"] as? String {
            DispatchQueue.main.async {
                UIApplication.shared.dd_keyWindow.dd_makeToast(msg)
            }
        }else if let data = response.data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers),let dic = json as? Dictionary<String, Any>,let msg = dic["error"] as? String {
            DispatchQueue.main.async {
                UIApplication.shared.dd_keyWindow.dd_makeToast(msg)
            }
        }else if let error = response.error {
            DispatchQueue.main.async {
                UIApplication.shared.dd_keyWindow.dd_makeToast(error.errorDescription)
            }
        }
        return response
    }
    
    func completionHandler<T>(response: AFDataResponse<T>) -> AFDataResponse<T> where T : Decodable {
        return response
    }
}
