package cn.yyxx.eyuancomm.impl.channel.huawei

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import cn.yyxx.eyuancomm.comm.entity.SdkChargeInfo
import cn.yyxx.eyuancomm.comm.ext.setThrottleListener
import cn.yyxx.eyuancomm.comm.internal.feature.IApplication
import cn.yyxx.eyuancomm.comm.internal.feature.IFeature
import cn.yyxx.eyuancomm.comm.internal.feature.IFloatBall
import cn.yyxx.eyuancomm.comm.internal.feature.ILifeCycle
import cn.yyxx.eyuancomm.comm.utils.Logger
import cn.yyxx.eyuancomm.comm.widget.ScaleLoadingDialog
import cn.yyxx.eyuancomm.impl.channel.huawei.floatview.FloatBall
import cn.yyxx.eyuancomm.impl.channel.huawei.floatview.FloatBallMenu
import cn.yyxx.eyuancomm.impl.channel.huawei.floatview.FloatCenterServiceManager
import cn.yyxx.eyuancomm.impl.channel.huawei.floatview.FloatFeature
import cn.yyxx.support.ResUtils
import cn.yyxx.support.hawkeye.ToastUtils
import com.huawei.agconnect.AGCRoutePolicy
import com.huawei.agconnect.AGConnectInstance
import com.huawei.agconnect.AGConnectOptionsBuilder
import com.huawei.agconnect.api.AGConnectApi
import com.huawei.agconnect.auth.AGConnectAuth
import com.huawei.agconnect.auth.AGConnectAuthCredential
import com.huawei.hmf.tasks.Task
import com.huawei.hms.analytics.HiAnalytics
import com.huawei.hms.analytics.HiAnalyticsInstance
import com.huawei.hms.analytics.HiAnalyticsTools
import com.huawei.hms.analytics.type.HAEventType
import com.huawei.hms.analytics.type.HAParamType
import com.huawei.hms.api.HuaweiMobileServicesUtil
import com.huawei.hms.common.ApiException
import com.huawei.hms.jos.AppParams
import com.huawei.hms.jos.JosApps
import com.huawei.hms.jos.JosStatusCodes
import com.huawei.hms.jos.games.Games
import com.huawei.hms.jos.games.GamesStatusCodes
import com.huawei.hms.jos.games.buoy.BuoyClient
import com.huawei.hms.support.account.request.AccountAuthParams
import com.huawei.hms.utils.ResourceLoaderUtil
import org.json.JSONObject


/**
 * @author #Suyghur.
 * Created on 2022/01/26
 */
class ChannelSdkHuawei : IFeature, IApplication, ILifeCycle, IFloatBall {

    private lateinit var activity: Activity
    private lateinit var loginCallback: (Int, String) -> Unit
    private lateinit var floatBallLogout: (Int, String) -> Unit
    private lateinit var analytics: HiAnalyticsInstance
    private lateinit var initTask: Task<Void>

    private var isLandscape = false
    private var loginChannel = -1

    private var buoyClient: BuoyClient? = null
    private var loginDialog: HuaweiLoginDialog? = null
    private var linkDialog: HuaweiLinkDialog? = null
    private var loadingDialog: ScaleLoadingDialog? = null

    private val floatBallCallback = object : FloatBall.FloatBallCallback {
        override fun onUpdateBallView(ballView: ImageView, isLeftLocation: Boolean, isHide: Boolean) {
            val resId = if (isHide) {
                ballView.alpha = 0.8f
                if (isLeftLocation) {
                    ResUtils.getResId(activity, "yyxx_float_logo_left_img", "drawable")
                } else {
                    ResUtils.getResId(activity, "yyxx_float_logo_right_img", "drawable")
                }
            } else {
                ballView.alpha = 1.0f
                ResUtils.getResId(activity, "yyxx_float_logo_img", "drawable")
            }
            ballView.setBackgroundResource(resId)
        }

        override fun onInitMenuData(): MutableList<FloatBallMenu.FloatBallMenuItem> {
            val items = mutableListOf<FloatBallMenu.FloatBallMenuItem>()
            items.add(FloatBallMenu.FloatBallMenuItem(FloatFeature.FEATURE_SWITCH))
            items.add(FloatBallMenu.FloatBallMenuItem(FloatFeature.FEATURE_LINK))
            items.add(FloatBallMenu.FloatBallMenuItem(FloatFeature.FEATURE_CLOSE))
            return items
        }

        override fun onMenuItemClick(ball: FloatBall, item: FloatBallMenu.FloatBallMenuItem, pos: Int) {
            when (item.type) {
                FloatFeature.FEATURE_SWITCH -> {
                    floatBallLogout(0, "浮标切换账号")
                    FloatCenterServiceManager.instance.detach()
                }
                FloatFeature.FEATURE_LINK -> {
                    linkDialog?.apply {
                        dismiss()
                        linkDialog = null
                    }
                    linkDialog = HuaweiLinkDialog(activity, isLandscape)

                    linkDialog?.apply {
                        when (loginChannel) {
                            AGConnectAuthCredential.HMS_Provider -> {
                                ivHw.visibility = View.GONE
                                ivGoogle.visibility = View.VISIBLE
                                ivFacebook.visibility = View.VISIBLE
                            }
                            AGConnectAuthCredential.Google_Provider -> {
                                ivHw.visibility = View.VISIBLE
                                ivGoogle.visibility = View.GONE
                                ivFacebook.visibility = View.VISIBLE
                            }
                            AGConnectAuthCredential.Facebook_Provider -> {
                                ivHw.visibility = View.VISIBLE
                                ivGoogle.visibility = View.VISIBLE
                                ivFacebook.visibility = View.GONE
                            }
                        }
                        ivClose.setThrottleListener {
                            linkDialog?.apply {
                                dismiss()
                                linkDialog = null
                            }
                        }
                        ivHw.setThrottleListener {
                            doLink(activity, AGConnectAuthCredential.HMS_Provider)
                        }
                        ivGoogle.setThrottleListener {
                            doLink(activity, AGConnectAuthCredential.Google_Provider)
                        }
                        ivFacebook.setThrottleListener {
                            doLink(activity, AGConnectAuthCredential.Facebook_Provider)
                        }

                        show()
                    }
                }
                FloatFeature.FEATURE_CLOSE -> ball.dismissMenu()
            }
        }

        override fun onDismissMenu(ball: FloatBall) {
            ball.dismissMenu()
        }
    }

    override fun attachBaseContext(application: Application, context: Context) {

    }

    override fun initApplication(application: Application) {
        HuaweiMobileServicesUtil.setApplication(application)
        // 创建AGConnectOptionsBuilder对象
        val builder = AGConnectOptionsBuilder()
        // 设置数据处理位置，比如将默认数据处理位置从CHINA修改为GERMANY
        builder.routePolicy = AGCRoutePolicy.SINGAPORE
        builder.inputStream = application.assets.open("agconnect-services.json")
        // 初始化AGC框架
        AGConnectInstance.initialize(application, builder)
        HiAnalyticsTools.enableLog()
        analytics = HiAnalytics.getInstance(application)
    }

    override fun initialize(activity: Activity, isLandscape: Boolean, callback: (Int, String) -> Unit) {
        this.activity = activity
        this.isLandscape = isLandscape
        ResourceLoaderUtil.setmContext(activity)
        this.initTask = JosApps.getJosAppsClient(activity).init(AppParams(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM_GAME) {
            // 该回调会在如下两种情况下返回:
            // 1.未成年人实名帐号在白天登录游戏，华为会弹框提示玩家不允许游戏，玩家点击“确定”，华为返回回调
            // 2.未成年实名帐号在国家允许的时间登录游戏，到晚上9点，华为会弹框提示玩家已到时间，玩家点击“知道了”，华为返回回调
            // 您可在此处实现游戏防沉迷功能，如保存游戏、调用帐号退出接口或直接游戏进程退出(如System.exit(0))
        })
        initTask.addOnSuccessListener {
            // 游戏初始化成功后需要调用一次浮标显示接口
            // showFloatWindowNewWay();
            // 必须在init成功后，才可以实现登录功能
            // signIn();
            Logger.d("Sdk init on success")

            AGConnectApi.getInstance().activityLifecycle().onCreate(activity)

            buoyClient = Games.getBuoyClient(activity)

            AGConnectAuth.getInstance().addTokenListener {
                if (TextUtils.isEmpty(it.token)) {
                    return@addTokenListener
                }
                val jsonObject = JSONObject()
                jsonObject.put("access_token", it.token)
                loginCallback(0, jsonObject.toString())
            }
            FloatCenterServiceManager.instance.init(activity, floatBallCallback)

            callback(0, "Sdk初始化成功")
        }.addOnFailureListener { e ->
            Logger.d("Sdk init on failure")
            if (e is ApiException) {
                Logger.d("Sdk init on failure, code: ${e.statusCode}, msg: ${e.localizedMessage}")
                when (e.statusCode) {
                    JosStatusCodes.JOS_PRIVACY_PROTOCOL_REJECTED -> {
                        // 错误码为7401时表示用户未同意华为联运隐私协议
                        // 此处您需禁止玩家进入游戏
                        Logger.e("has reject the protocol")
                    }
                    JosStatusCodes.JOS_PRIVACY_PROTOCOL_NO_AGREE -> {
                        Logger.e("has reject the protocol")
                    }
                    GamesStatusCodes.GAME_STATE_NETWORK_ERROR -> {
                        // 错误码7002表示网络异常
                        // 此处您可提示玩家检查网络，请不要重复调用init接口，否则断网情况下可能会造成手机高耗电。
                        Logger.e("Network error")
                    }

                    else -> {
                        // 在此处实现其他错误码的处理
                    }
                }
            }
        }
    }

    override fun login(activity: Activity, callback: (Int, String) -> Unit) {
        this.activity = activity
        this.loginCallback = callback
        AGConnectAuth.getInstance().signOut()
        loginDialog?.apply {
            dismiss()
            loginDialog = null
        }
        loginDialog = HuaweiLoginDialog(activity, isLandscape)
        loginDialog?.apply {
            ivHw.setThrottleListener {
                doSignIn(activity, AGConnectAuthCredential.HMS_Provider)
            }
            ivGoogle.setThrottleListener {
                doSignIn(activity, AGConnectAuthCredential.Google_Provider)
            }
            ivFacebook.setThrottleListener {
                doSignIn(activity, AGConnectAuthCredential.Facebook_Provider)
            }
            show()
        }
    }

    override fun logout(activity: Activity, callback: (Int, String) -> Unit) {
        this.activity = activity
        AGConnectAuth.getInstance().signOut()
        analytics.onEvent(HAEventType.SIGNOUT, null)
        FloatCenterServiceManager.instance.detach()
        callback(0, "用户登出成功")
    }

    override fun charge(activity: Activity, chargeInfo: SdkChargeInfo, callback: (Int, String) -> Unit) {
        this.activity = activity
        HuaweiInAppPay.instance.charge(activity, chargeInfo, object : HuaweiInAppPay.InAppPayCallback {
            override fun onResult(code: Int, result: String) {
                callback(code, result)
            }
        })
    }

    override fun hasExitView(activity: Activity): Boolean {
        this.activity = activity
        return false
    }

    override fun openExitView(activity: Activity, callback: (Int, String) -> Unit) {
        this.activity = activity
    }

    override fun onDestroy(activity: Activity) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onDestroy()
        FloatCenterServiceManager.instance.release()
    }

    override fun getChannelVersion(): String = "6.3.0.301"

    override fun getChannelName(): String = "huawei"

    override fun onStart(activity: Activity) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onStart()
    }

    override fun onResume(activity: Activity) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onResume()
        buoyClient?.showFloatWindow()
        FloatCenterServiceManager.instance.attach()
    }

    override fun onReStart(activity: Activity) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onRestart()
    }

    override fun onPause(activity: Activity) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onPause()
        buoyClient?.hideFloatWindow()
        FloatCenterServiceManager.instance.detach()
    }

    override fun onStop(activity: Activity) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onStop()
    }

    override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onActivityResult(requestCode, resultCode, data)
        HuaweiInAppPay.instance.onActivityResult(activity, requestCode, resultCode, data)
    }

    override fun onNewIntent(activity: Activity, intent: Intent?) {
        this.activity = activity
        AGConnectApi.getInstance().activityLifecycle().onNewIntent(intent)
    }

    private fun doSignIn(activity: Activity, channel: Int) {
        showLoadingDialog(activity)
        AGConnectAuth.getInstance().signIn(activity, channel).addOnSuccessListener {
            dismissLoadingDialog()
            loginDialog?.apply {
                dismiss()
                loginDialog = null
            }
            val channelName = when (channel) {
                AGConnectAuthCredential.HMS_Provider -> "huawei"
                AGConnectAuthCredential.Google_Provider -> "google"
                AGConnectAuthCredential.Facebook_Provider -> "facebook"
                else -> ""
            }
            val bundle = Bundle()
            bundle.putString(HAParamType.LOANCHANNEL, channelName)
            analytics.onEvent(HAEventType.SIGNIN, bundle)
            this.loginChannel = channel
        }.addOnFailureListener { e ->
            // onFailure
            if (e is ApiException && e.statusCode == JosStatusCodes.JOS_PRIVACY_PROTOCOL_NO_AGREE) {
                Logger.e("reInit...")
                this.initTask = JosApps.getJosAppsClient(activity).init(AppParams(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM_GAME))
                doSignIn(activity, channel)
            } else {
                dismissLoadingDialog()
                loginCallback(-1, "登录失败")
            }
        }
    }

    private fun doLink(activity: Activity, channel: Int) {
        AGConnectAuth.getInstance().currentUser.link(activity, channel).addOnSuccessListener {
            ToastUtils.toastInfo(activity, "賬號關聯成功")
            Logger.d("賬號關聯成功")
            linkDialog?.apply {
                dismiss()
                linkDialog = null
            }
        }.addOnFailureListener {
            // onFail
            ToastUtils.toastInfo(activity, "賬號關聯失敗，${it.localizedMessage}")
            Logger.d("賬號關聯失敗, ${it.localizedMessage}")
        }
    }


    private fun showLoadingDialog(context: Context) {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
        loadingDialog = ScaleLoadingDialog(context, "")
        loadingDialog?.show()
    }

    private fun dismissLoadingDialog() {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
    }

    override fun showFloatBall(activity: Activity) {
        FloatCenterServiceManager.instance.attach()
    }

    override fun hideFloatBall(activity: Activity) {
        FloatCenterServiceManager.instance.detach()
    }

    override fun onFloatBallLogout(callback: (Int, String) -> Unit) {
        floatBallLogout = callback
    }
}