package com.yidian.shenghuoquan.bgeneralbusiness.service

import com.google.gson.Gson
import com.yidian.bcommon.constant.AppConfig
import com.yidian.bcommon.constant.RunConfig
import com.yidian.bcommon.http.bean.GetCommonConfigBean
import com.yidian.bcommon.http.callback.IGetCommonConfigCallback
import com.yidian.bcommon.sdk.BCommonManager
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.shenghuoquan.bgeneralbusiness.config.LazyInitConfig
import com.yidian.shenghuoquan.bgeneralbusiness.http.GeneralBusinessRemoteDataService
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import org.json.JSONObject


/**
 * 通用能力服务，提供其他组件的共用操作能力
 */
class GeneralAbilityService : ZapService() {

  private val gson by lazy { Gson() }

  override fun onAction(path: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
    params as JSONObject
    when (action) {
      ZapServiceActionConstants.ActionRequestSmsCode -> requestSmsCode(params, resolver)
      ZapServiceActionConstants.ActionLazyInit -> lazyInit()
      ZapServiceActionConstants.ActionGetTowerProCommonConfig -> getTowerProCommonConfig(resolver)
    }
  }

  override fun onExit() {
  }

  override fun onInit() {
  }

  /**
   * 请求短信验证码
   */
  private fun requestSmsCode(params: JSONObject, resolver: ResultResolver) {
    val mobile = params.optString("mobile")
    val scene = params.optString("scene")
    val paramsMap = HashMap<String, String?>()
    paramsMap["mobile"] = mobile
    paramsMap["scene"] = scene
    GeneralBusinessRemoteDataService.sendMsgCode(paramsMap) {
      if (it) {
        resolver.success(true)
      }
    }
  }

  /**
   * 延迟初始化
   */
  private fun lazyInit() {
    // 初始化网络请求
    LazyInitConfig.initHttp()
    // 初始化慧眼
    LazyInitConfig.initXInsight()
  }

  /**
   * 获取TowerPro通用配置数据
   */
  private fun getTowerProCommonConfig(resolver: ResultResolver) {
    GeneralBusinessRemoteDataService.getCommonConfig(
      object : IGetCommonConfigCallback {
        override fun getCommonConfigSuccess(result: GetCommonConfigBean.GetCommonConfigResponse?) {
          resolver.success(JSONObject(gson.toJson(result)))
        }

        override fun getCommonConfigFailure(message: String?) {
          resolver.fail(-1, message, "获取配置失败，请稍后重试")
        }
      }, hashMapOf(
        "appid" to BCommonManager.getAppId(),
        "env" to RunConfig.TOWER_API_ENV.toString(),
        "version" to AppConfig.TowerApiVersion,
        "os" to AppConfig.TowerApiOS,
        "keytag" to BCommonManager.getTowerProKeyTag()
      )
    )
  }
}
