package com.yidian.shenghuoquan.bgeneralbusiness.service

import com.yidian.bcommon.sdk.BCommonManager
import com.yidian.bcommon.sdk.IEncryptService
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.framework.mobile.xdiamond.SecretUtil
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import org.json.JSONObject

/**
 * author: yinjiacheng
 * date: 7/28/21 9:34 AM
 * description: 加密服务
 * 目前基于XDiamond（磐石）实现
 */
class EncryptService : ZapService(), IEncryptService {

  init {
    BCommonManager.setEncryptIml(this)
  }

  override fun sign(src: String): String {
    return SecretUtil.sign(src) ?: ""
  }

  override fun verifySign(src: String, sign: String): Boolean {
    return SecretUtil.verifySign(src, sign)
  }

  override fun rsaEncrypt(src: String): String {
    return SecretUtil.rsaEncrypt(src) ?: ""
  }

  override fun rsaDecrypt(src: String): String {
    return SecretUtil.rsaDecrypt(src) ?: ""
  }

  override fun aesEncrypt(src: String): String {
    return SecretUtil.aesEncrypt(src) ?: ""
  }

  override fun aesDecrypt(src: String): String {
    return SecretUtil.aesDecrypt(src) ?: ""
  }

  override fun onAction(path: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
    when (action) {
      ZapServiceActionConstants.ActionRSASign -> {
        // RSA私钥签名
        val result = SecretUtil.sign((params as JSONObject).optString("src"))
        resolver.success(JSONObject().put("result", result))
      }
      ZapServiceActionConstants.ActionRSAVerifySign -> {
        // RSA公钥验签
        val result = SecretUtil.verifySign((params as JSONObject).optString("src"), params.optString("sign"))
        resolver.success(JSONObject().put("result", result))
      }
      ZapServiceActionConstants.ActionRSAEncrypt -> {
        // RSA公钥加密
        val result = SecretUtil.rsaEncrypt((params as JSONObject).optString("src"))
        resolver.success(JSONObject().put("result", result))
      }
      ZapServiceActionConstants.ActionRSADecrypt -> {
        // RSA私钥解密
        val result = SecretUtil.rsaDecrypt((params as JSONObject).optString("src"))
        resolver.success(JSONObject().put("result", result))
      }
      ZapServiceActionConstants.ActionAESEncrypt -> {
        // AES加密
        val result = SecretUtil.aesEncrypt((params as JSONObject).optString("src"))
        resolver.success(JSONObject().put("result", result))
      }
      ZapServiceActionConstants.ActionAESDecrypt -> {
        // AES解密
        val result = SecretUtil.aesDecrypt((params as JSONObject).optString("src"))
        resolver.success(JSONObject().put("result", result))
      }
    }
  }

  override fun onExit() {

  }

  override fun onInit() {

  }
}
