package com.shenghuoquan.business

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import com.orhanobut.hawk.Hawk
import com.yidian.common.AppConfig
import com.yidian.common.YdBaseApplication
import com.yidian.common.http.ApiSaveCookiesInterceptor
import com.yidian.common.http.ApiSetCookiesInterceptor
import com.yidian.common.services.XEventService
import com.yidian.common.services.XPageService
import com.yidian.common.utils.JVerificationUtils
import com.yidian.common.utils.UMConfigUtils
import com.yidian.commonutil.CommonUtilLifecycleModule
import com.yidian.framework.mobile.xdiamond.SecretUtil
import com.yidian.http.ServiceFactory
import com.yidian.news.util.ProcessUtil
import com.yidian.xarc.xbrid.*
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.core.YacAppSpec
import com.yidian.yac.core.zap.Zap
import com.yidian.yac.core.zap.ZapTicket
import com.yidian.yac.ftdevicefinger.core.FtDeviceFingerManager
import org.json.JSONObject


@YacAppSpec
class YdSubwayApplication : YdBaseApplication() {
  private val module: CommonUtilLifecycleModule by lazy {
    CommonUtilLifecycleModule(
      BuildConfig.DEBUG,
      this,
      ".CommonInfrastructure"
    )
  }

  private val activityLifecycle = object : ActivityLifecycleCallbacks {
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
      activityList.add(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
      activityList.remove(activity)
    }


  }

  override fun onCreate() {
    super.onCreate()
    UMConfigUtils.init(this)
    if (ProcessUtil.isMainProcess(this)) {
      context = this
      FtDeviceFingerManager.init(this)
      initCommonUtils()
      Zap.init(this) {}
      XPageManager.init(this)
      initXBridManager()
      loadService()
      JVerificationUtils.init(this)
      registerActivityLifecycleCallbacks(activityLifecycle)
      // 初始化磐石SDK
      SecretUtil.init(BuildConfig.IS_ENCRYPT_DEBUG_KEY)
    }
  }

  override fun attachBaseContext(base: Context?) {
    super.attachBaseContext(base)
    if (ProcessUtil.isMainProcess(this)) {
      module.onBaseContextAttached(base)
    }
  }

  override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    if (ProcessUtil.isMainProcess(this)) {
      module.onConfigurationChanged(newConfig)
    }
  }

  private fun initCommonUtils() {
    module.onCreate()
    Hawk.init(this).build()
    initHttp()
  }

  private fun initHttp() {
//        val header = HashMap<String, String>()
//        header["Content-Type"] = "application/json"
//        header["charset"] = "UTF-8"
//        ServiceFactory.getInstance().addInterceptor(HttpInterceptor(header))
//        ServiceFactory.getInstance().init(true, URLs.BASE_URL, 10, 10)
    ServiceFactory.getInstance().init(true, BuildConfig.API_URL, 10, 10)
    ServiceFactory.getInstance().addInterceptor(ApiSaveCookiesInterceptor())
    ServiceFactory.getInstance().addInterceptor(ApiSetCookiesInterceptor())

  }

  private fun initXBridManager() {
    XBridManager.init(
      XBridApp(applicationContext) {
        assetRoot = "www"//对应assets目录下存放xbrid资源对应的目录名
        appId = "com.yidian.subway"//当前应用包名
        platformId = 16 //需要去平台申请
        appVersion = AppConfig.cv//当前应用版本号
        deviceFinger = FtDeviceFingerManager.getDeviceFinger()//设备指纹
        androidChannel = AppConfig.distribution//对应渠道名
      }, 20//webview缓存池数量，默认不缓存
    )

    XBridManager.registerServiceInvoker(object : OnServiceInvoke {
      override fun onCall(
        identifier: String, // the identifier assigned when webview created
        xWebView: XWebView, // webivew 加载的 js 发起的服务调用请求
        request: Request, // 具体的服务请求参数，分为 name 和 params 两个部分
        response: Response // 业务方需要借助 response 来回应服务调用结果
      ) {
        val data = request.params as JSONObject
        Log.e("zhb-yd", "服务名:" + request.name)
        Log.e("zhb-yd", "JS传递参数：$data")

        val action = data.optString("action")
        val params = data.optJSONObject("params")
        val options = data.optJSONObject("options")

        ZapTicket(request.name).withAction(action).withServiceParams(params).withServiceOptions(options).withIdentifier(identifier)
          .onResult { result ->
            response.result(result.code, result.result!!, "")
          }.onLost { result ->
            response.result(result.code, "", result.mesg)
          }.ship()
      }
    })

    XBridManager.registerXPageInvoker(object : OnXPageInvoke {
      override fun onCall(identifier: String, xWebView: XWebView, request: XPageRequest) {
        val params = mutableMapOf<String, Any>()
        (request.params as JSONObject).let { reParams ->
          reParams.keys().forEach {
            params[it] = reParams[it]
          }
        }
        when (request.action) {
          "push" -> XPageManager.push(request.name, params)
          "pop" -> XPageManager.pop(params)
          "popTo" -> XPageManager.popTo(request.name, params)
          "popToRoot" -> XPageManager.popToRoot(params)
        }
      }
    })
  }

  private fun loadService() {
    Zap.addService(XPageService.name, XPageService())
    Zap.addService(XEventService.name, XEventService())
  }
}
