package com.yidian.shenghuoquan.broot

import android.content.Context
import com.yidian.bcommon.BuildConfig
import com.yidian.bcommon.constant.AppConfig
import com.yidian.bcommon.constant.GlobalConstants
import com.yidian.bcommon.constant.RunConfig
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.bcommon.services.ZapServiceNameConstants
import com.yidian.bcommon.utils.UMConfigUtils
import com.yidian.news.util.ProcessUtil
import com.yidian.xarc.xbase.utils.XLogger
import com.yidian.xarc.xbrid.*
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapTicket
import com.yidian.yac.ftdevicefinger.core.FtDeviceFingerManager
import com.yidian.yac.pm.appupdate.PmUpdateApp
import com.yidian.yac.pm.appupdate.YDAppUpdateManager
import org.json.JSONObject
import timber.log.Timber


/**
 * 项目基础配置类初始化,用于同意隐私政策后的初始化
 *
 * 三方库的初始化应该放这里执行，防止因为隐私政策被应用市场拒绝
 */
object BaseInitConfig {

  fun performInitialization(context: Context) {
    // 使用编译器运行时，根据Flavor进行环境的配置切换
    when (GlobalConstants.ENVIRONMENT) {
      "dev" -> RunConfig.switchEnvironment(RunConfig.RunEnvironment.DEV)
      "beta" -> RunConfig.switchEnvironment(RunConfig.RunEnvironment.TEST)
      "prod" -> RunConfig.switchEnvironment(RunConfig.RunEnvironment.PROD)
    }
    // 初始化友盟
    UMConfigUtils.init(context)
    if (ProcessUtil.isMainProcess(context)) {
      FtDeviceFingerManager.init(context)
      initXBridManager(context)
      // 初始化App升级
      initAppUpgrade(context)
      // 调用延迟初始化
      ZapTicket(ZapServiceNameConstants.GeneralAbilityService).withAction(ZapServiceActionConstants.ActionLazyInit).ship()
    }
  }

  /**
   * 初始化XBrid
   *
   * 注意：
   * 1.如果有多个xbrid资源时，请分别进行注册，区分assetRoot名称，否则打包后出现文件丢失加载失败
   * 2.更新assert文件后不生效，可以卸载重新安装
   */
  private fun initXBridManager(context: Context) {
    XBridManager.init(
      XBridApp(context) {
        online = RunConfig.IS_UPGRADE_ONLINE // 线上、线下
        assetRoot = "www/src"//对应assets目录下存放xbrid资源对应的目录名
        appId = context.packageName //当前应用包名
        platformId = AppConfig.TowerProXBridUpgradePlatformId //需要去平台申请
        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
        // JS调用Native传递的数据
        Timber.tag("xbrid").e("服务名:%s", request.name)
        Timber.tag("xbrid").e("JS传递参数:%s", data)

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

        // 发送JS传递的数据到Service,并监听服务返回的结果回传JS
        ZapTicket(request.name).withAction(action).withServiceParams(params).withServiceOptions(options).withIdentifier(identifier)
          .onResult { result ->
            Timber.tag("xbrid").e("回传JS的结果码： ${result.code}   +  结果信息： ${result.result}")
            response.result(result.code, result.result ?: "", "")
          }.onLost { result ->
            Timber.tag("xbrid").e("回传JS的错误码： ${result.code}   +  错误信息： ${result.mesg}")
            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)
        }
      }
    })
  }

  /**
   * App升级
   */
  private fun initAppUpgrade(context: Context) {
    val logger = XLogger("appUpgrade")
    logger.debugOn(BuildConfig.DEBUG)
    YDAppUpdateManager.init(PmUpdateApp(context) {
      online = RunConfig.IS_UPGRADE_ONLINE // 线上true、线下false
      platformId = AppConfig.TowerProAppUpgradePlatformId // 平台Id
      platform = AppConfig.TowerProPlatform // ios/Android
      appId = context.packageName // 应用包名
      appVersion = AppConfig.cv // 客户端版本号
      deviceFinger = FtDeviceFingerManager.getDeviceFinger() // 设备指纹
      androidChannel = AppConfig.distribution // 渠道
      this.logger = logger.subLogger("appUpgrade")
    })
  }

}
