package com.yidian.shenghuoquan.bgeneralbusiness.service.net

import com.google.gson.Gson
import com.yidian.bcommon.constant.RunConfig
import com.yidian.bcommon.http.HttpResult
import com.yidian.shenghuoquan.bgeneralbusiness.service.net.callback.IBNARequestCallBack
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import org.json.JSONObject


/**
 * 网络请求服务类
 */
class BNAHttpReqService : ZapService() {

  /**
   * @param resolver 此参数建议作为具体能力的方法入参 避免使用全局变量（异步回传H5结果时seq顺序错乱）
   */
  override fun onAction(path: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
    try {
      //params
      val realParams = params as JSONObject
      val apiPath = realParams.optString("path")
      val requestParams = realParams.optJSONObject("params")

      //options
      val requestOptions = options as JSONObject
      val method = requestOptions.optString("method", "POST")
      val host = requestOptions.optString("host", RunConfig.API_URL)
      val isEncrypt = requestOptions.optBoolean("is_encrypt", true)
      val url = host + apiPath
      val paramsMap: HashMap<String, String?> = parseParams(requestParams)

      //发起请求
      when (method) {
        "GET", "get" -> {
          BNARemoteDataSource.launchGetRequest(iMBRequestCallBackImpl, paramsMap, url, isEncrypt, resolver)
        }
        "POST", "post" -> {
          BNARemoteDataSource.launchPostRequest(iMBRequestCallBackImpl, paramsMap, url, isEncrypt, resolver)
        }
        else -> {
          resolver.fail(-1000, "request error", "不支持的请求方式")
        }
      }
    } catch (e: Exception) {
      e.printStackTrace()
      resolver.fail(-1001, "other error", "其他错误")
    }
  }

  override fun onExit() {
  }

  override fun onInit() {
  }

  private fun parseParams(requestParams: JSONObject?): HashMap<String, String?> {
    var hashMap: HashMap<String, String?> = HashMap()
    if (requestParams != null) {
      hashMap = HashMap()
      var key: String?
      val iterator = requestParams.keys()
      while (iterator.hasNext()) {
        key = iterator.next()
        hashMap[key] = requestParams.optString(key)
      }
    }
    return hashMap
  }

  private val iMBRequestCallBackImpl = object : IBNARequestCallBack {

    override fun getRequestSuccess(response: Any?, resolver: ResultResolver) {
      val params = Gson().toJson(response)
      resolver.success(JSONObject(params))
    }

    override fun getRequestFailure(response: HttpResult<Any?>?, resolver: ResultResolver) {
      response?.let {
        resolver.fail(response.code, null, response.reason)
      }
    }
  }


}
