package com.zxhl.cms.pay.alipay


import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Handler
import android.os.Message

import android.text.TextUtils
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alipay.sdk.app.PayTask
import com.zxhl.cms.common.Constant
import com.zxhl.cms.utils.RxBus
import com.zxhl.cms.net.model.uc.PayResultEntity


/**
 * 支付宝支付
 * @author lbm
 *
 */
object AlipayServer {
    private val SDK_PAY_FLAG = 1
    private val SDK_AUTH_FLAG = 2
//    var activity: Activity? = null
    /**
     * 获取权限使用的 RequestCode
     */
    private val PERMISSIONS_REQUEST_CODE = 1002

    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String, String>)
                    println("payResult:$payResult")
                    /**
                     * payResult:resultStatus={9000};memo={};result={{"alipay_trade_app_pay_response":
                     * {"code":"10000","msg":"Success","app_id":"2019070565716816","auth_app_id":"2019070565716816",
                     * "charset":"utf-8","timestamp":"2019-07-09 20:46:00","out_trade_no":"1148573956964810752","
                     * total_amount":"0.01","trade_no":"2019070922001462921044512553","seller_id":"2088821704449704"},
                     * "sign":"JtMmew6Ew0ZRHd+FmGuHhLGDEgYaklFCAMp8RZX2/e8qhps/p51sBL4qtr1fMYWeUV5pHK/KyTVFs8C4g/ElUNCFr
                     * NZ8di2q6kCyNDLIMpaykQrdJIIjQTPHv2xbeCkGP3CWXkhZL6yVw4A7m8taxmiJ1jGL+vOlGUsWxvtCPXGCxFWn69g76T/mj2
                     * GhQc5F8E11iL2fqFYQ3rXsliUd4lOoylp4rH4BwldFLvmFouuW95awtoZGBmmtARzm3VMVPZY8b4Llkz8v/8BolLtN0oR47OjO4pI
                     * s92Egp78VoeNCT0Tb8OyLUmYTu9AP5mmxci808eMQ/KmSII5EXNtMHQ==","sign_type":"RSA2"}}
                     */
                    val resultInfo = payResult.result// 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        try {
//                            var obj = JSONObject(resultInfo)
//                            var tradeOrder  = obj.getString("out_trade_no")
//                            var  order = obj.getString("trade_no")
//                            var  authAppId = obj.getString("auth_app_id")
                            result(true,resultInfo,resultStatus)
                        }catch (e:Exception){
                            result(false,resultInfo,resultStatus)
                        }

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        result(false,resultInfo,resultStatus)
                    }
                }
                SDK_AUTH_FLAG -> {
                    val authResult = AuthResult(msg.obj as Map<String, String>, true)
                    val resultStatus = authResult.resultStatus

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.resultCode, "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        						showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
                        println("resultStatus")
                    } else {
                        // 其他状态值则为授权失败
                        //						showAlert(PayDemoActivity.this, getString(R.string.auth_failed) + authResult);
                    }
                }
                else -> {
                    result(false,msg?.toString(),"-1")
                }
            }
        }
    }

    fun result(isPaysuc:Boolean,txt:String,status:String){

        var entity = PayResultEntity()
        entity.isPaySuc = isPaysuc
        entity.payStatus = status
        entity.txt = txt
        entity.payType = 1//支付宝支付类型
        RxBus.get().post(Constant.PAY_RESULT,entity)
//        verifyPay(txt,1)
    }


    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    fun requestPermission(activity: Activity) {
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(activity,
                    arrayOf(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSIONS_REQUEST_CODE)

        } else {
            //			showToast(this, getString(R.string.permission_already_granted));
        }
    }

    /**
     * 权限获取回调
     */
    fun onRequestPermissionsResult(activity: Activity, requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSIONS_REQUEST_CODE -> {

                // 用户取消了权限弹窗
                if (grantResults.size == 0) {
                    //					showToast(this, getString(R.string.permission_rejected));
                    return
                }

                // 用户拒绝了某些权限
                for (x in grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        //						showToast(this, getString(R.string.permission_rejected));
                        return
                    }
                }

                // 所需的权限均正常获取
                //				showToast(this, getString(R.string.permission_granted));
            }
        }
    }


    /**
     * 支付宝支付
     */
    fun payV2(activity: Activity?, url: String) {
//        this.activity = activity
        val payRunnable = Runnable {
            val alipay = PayTask(activity)
            val result = alipay.payV2(url, true)
            Log.i("msp", result.toString())

            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }


}
