package com.demo.xinrui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.*
import cn.yyxx.support.hawkeye.LogUtils
import cn.yyxx.support.hawkeye.ToastUtils
import com.yyrh.constant.Constants
import com.yyrh.constant.RoleInfo
import com.yyrh.core.impl.HybridActivity
import com.yyrh.sdk.SDKEntry
import com.yyrh.sdk.callback.InitCallback
import com.yyrh.sdk.callback.LoginCallback
import com.yyrh.sdk.callback.LogoutCallback
import com.yyrh.sdk.callback.PayCallback
import kotlin.system.exitProcess

/**
 * @author #Suyghur.
 * Created on 2021/10/18
 */
class DemoActivity : Activity(), View.OnClickListener {

    private val events = arrayListOf(
        Item(1, "01 登录"),
        Item(2, "02 切换账号"),
        Item(3, "03 角色创建上报"),
        Item(4, "04 角色登录上报"),
        Item(5, "05 角色升级上报"),
        Item(6, "06 定额支付"),
        Item(7, "07 测试测试"),
    )

    private lateinit var layout: LinearLayout
    private lateinit var textView: TextView
    private lateinit var editText: EditText

    private var cacheRoleInfo: CacheRoleInfo.RoleInfo? = null

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                10001 -> {
                    with(textView) {
                        text = text.toString() + msg.obj.toString()
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        LogUtils.handler = handler
        SDKEntry.getSdkInstance().initSdk(this, object : InitCallback {
            override fun onInitSuccess(msg: String?) {
                ToastUtils.toastInfo(this@DemoActivity, "onInitSuccess: $msg")

                // 初始化成功后才设置回调
                SDKEntry.getSdkInstance().setSDKLogoutListener(this@DemoActivity, object : LogoutCallback {
                    override fun onLogoutSuccess() {
                        ToastUtils.toastInfo(this@DemoActivity, "onLogoutSuccess")
                        SDKEntry.getSdkInstance().login(this@DemoActivity, object : LoginCallback {
                            override fun onLoginSuccess(token: String?) {
                                ToastUtils.toastInfo(this@DemoActivity, "登录成功，token: $token")
                                cacheRoleInfo = CacheRoleInfo.getDemoRoleInfo(this@DemoActivity, SDKEntry.getSdkInstance().currentUserId)
                            }

                            override fun onLoginFailed(msg: String?) {
                                ToastUtils.toastInfo(this@DemoActivity, "登录失败，msg: $msg")
                            }

                            override fun onLoginError(msg: String?) {
                                ToastUtils.toastInfo(this@DemoActivity, "登录失败，msg: $msg")
                            }
                        })
                    }

                    override fun onLogoutFailed() {
                        ToastUtils.toastInfo(this@DemoActivity, "onLogoutFailed")
                    }
                })
            }

            override fun onInitFailed(msg: String?) {
                ToastUtils.toastInfo(this@DemoActivity, "onInitFailed: $msg")
            }

            override fun onInitError(msg: String?) {
                ToastUtils.toastInfo(this@DemoActivity, "onInitError: $msg")

            }

            override fun onGetOaid(isSuccess: Boolean, oaid: String?) {
                ToastUtils.toastInfo(this@DemoActivity, "onGetOaid: $oaid")
            }

            override fun onShowGameExit() {
            }
        }, true)


    }

    private fun initView() {
        layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL
        initButton()
        textView = TextView(this)
        with(textView) {
            text = ""
            this@DemoActivity.layout.addView(this)
        }
        val scrollView = ScrollView(this)
        scrollView.addView(layout)
        setContentView(scrollView)
    }

    private fun initButton() {
        for (event in events) {
            with(Button(this)) {
                text = event.name
                tag = event.id
                id = event.id
                setOnClickListener(this@DemoActivity)
                this@DemoActivity.layout.addView(this)
            }
            if (event.id == 6) {
                editText = EditText(this)
                editText.hint = "请输入金额，单位分"
                this.layout.addView(editText)
            }
        }
    }

    override fun onClick(v: View?) {
        v?.apply {
            when (id) {
                1 -> {
                    SDKEntry.getSdkInstance().login(this@DemoActivity, object : LoginCallback {
                        override fun onLoginSuccess(token: String?) {
                            ToastUtils.toastInfo(this@DemoActivity, "登录成功，token: $token")
                            cacheRoleInfo = CacheRoleInfo.getDemoRoleInfo(this@DemoActivity, SDKEntry.getSdkInstance().currentUserId)
                        }

                        override fun onLoginFailed(msg: String?) {
                            ToastUtils.toastInfo(this@DemoActivity, "登录失败，msg: $msg")
                        }

                        override fun onLoginError(msg: String?) {
                            ToastUtils.toastInfo(this@DemoActivity, "登录失败，msg: $msg")
                        }

                    })
                }
                2 -> {
                    SDKEntry.getSdkInstance().logout()
                    SDKEntry.getSdkInstance().login(this@DemoActivity, object : LoginCallback {
                        override fun onLoginSuccess(token: String?) {
                            ToastUtils.toastInfo(this@DemoActivity, "登录成功，token: $token")
                            cacheRoleInfo = CacheRoleInfo.getDemoRoleInfo(this@DemoActivity, SDKEntry.getSdkInstance().currentUserId)
                        }

                        override fun onLoginFailed(msg: String?) {
                            ToastUtils.toastInfo(this@DemoActivity, "登录失败，msg: $msg")
                        }

                        override fun onLoginError(msg: String?) {
                            ToastUtils.toastInfo(this@DemoActivity, "登录失败，msg: $msg")
                        }
                    })
                }
                3 -> {
                    cacheRoleInfo = null
                    cacheRoleInfo = CacheRoleInfo.setDemoRoleInfo(this@DemoActivity, SDKEntry.getSdkInstance().currentUserId)
                    SDKEntry.getSdkInstance().upLoadRoleInfo(Constants.UPLOADTYPE_CREATEROLE, this@DemoActivity, getGameRoleInfo())
                }
                4 -> SDKEntry.getSdkInstance().upLoadRoleInfo(Constants.UPLOADTYPE_ENTERGAME, this@DemoActivity, getGameRoleInfo())
                5 -> SDKEntry.getSdkInstance().upLoadRoleInfo(Constants.UPLOADTYPE_LEVELUP, this@DemoActivity, getGameRoleInfo())
                6 -> {
                    val order = HashMap<String, String>()
                    order["role_id"] = cacheRoleInfo?.roleId!!
                    order["role_name"] = getGameRoleInfo().roleName
                    order["role_level"] = getGameRoleInfo().roleLevel
                    order["server_id"] = getGameRoleInfo().serverId
                    order["server_name"] = getGameRoleInfo().serverName
                    order["role_id"] = getGameRoleInfo().roleId
                    order["role_id"] = getGameRoleInfo().roleId

                    SDKEntry.getSdkInstance().pay(getChargeInfo(), object : PayCallback {
                        override fun onPaySuccess(msg: String?) {
                        }

                        override fun onPayFailed(msg: String?) {
                        }
                    }, this@DemoActivity)
                }
                7 -> {
                    val url =
                        "http://testsdkapi.yyxxgame.com/wap_v1/pay.html?product_money=0.01&pmode=d2VpeGluaDV8d3h85b6u5L%2Bh5pSv5LuYI2FsaXBheXdhcHx6ZmJ85pSv5LuY5a6d&params=6478a55c41adf093bf7014cc9b152522f55c37056f0903c23e7500a64bcdee5acbf591df01bdb646677de4521a83df58&product_name=%E8%B4%AD%E4%B9%B010%E5%85%83%E5%AE%9D"

                    HybridActivity.start(this@DemoActivity, url)
                }
            }
        }
    }

    private fun getGameRoleInfo(): RoleInfo {
        val roleInfo = RoleInfo()
        cacheRoleInfo?.apply {
            roleInfo.roleId = roleId
            roleInfo.roleName = roleName
            roleInfo.roleLevel = roleLevel
            roleInfo.gender = gender
            roleInfo.serverId = serverId
            roleInfo.serverName = serverName
            roleInfo.hasGold = balance
            roleInfo.vipLevel = vipLevel
            roleInfo.rolePower = rolePower
            roleInfo.partyId = partyId
            roleInfo.partyName = partyName
            roleInfo.roleCreateTime = roleCTime
            roleInfo.reincarnationCount = reincarnationCount
            roleInfo.charge = totalPurchase
        }
        return roleInfo
    }

    private fun getChargeInfo(): HashMap<String, Any> {
        val order = HashMap<String, Any>()
        val ts = System.currentTimeMillis() / 1000
        cacheRoleInfo?.apply {
            order["role_id"] = roleId
            order["role_name"] = roleName
            order["role_level"] = roleLevel
            order["server_id"] = serverId
            order["server_name"] = serverName
            order["game_no"] = "order_id_$ts"
            order["pay_money"] = editText.text.toString()
            order["order_desc"] = "购买60元宝"
            order["order_name"] = "60元宝"
            order["product_name"] = "元宝"
            order["productId"] = "测试商品ID"
            order["ext"] = "callback_order_id_$ts"
            order["vip_level"] = vipLevel
            order["count"] = "60"
            order["radio"] = "10"
            order["reincarnationCount"] = reincarnationCount
            order["hasGold"] = balance
        }
        return order
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            SDKEntry.getSdkInstance().exitGame(this) {
                if (it) {
                    finish()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onStart() {
        super.onStart()
        SDKEntry.getSdkInstance().sdkOnStart(this)
    }

    override fun onResume() {
        super.onResume()
        SDKEntry.getSdkInstance().sdkOnResume(this)
    }

    override fun onRestart() {
        super.onRestart()
        SDKEntry.getSdkInstance().sdkOnRestart(this)
    }

    override fun onPause() {
        super.onPause()
        SDKEntry.getSdkInstance().sdkOnPause(this)
    }

    override fun onStop() {
        super.onStop()
        SDKEntry.getSdkInstance().sdkOnStop(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        SDKEntry.getSdkInstance().sdkOnDestroy(this)
        exitProcess(0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        SDKEntry.getSdkInstance().onActivityResult(this, requestCode, resultCode, data)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        SDKEntry.getSdkInstance().sdkOnNewIntent(this, intent)
    }
}