package com.eyuancomm.demo

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 androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import cn.yyxx.eyuancomm.comm.EYuanCommSdk
import cn.yyxx.eyuancomm.comm.entity.SdkChargeInfo
import cn.yyxx.eyuancomm.comm.entity.SdkRoleInfo
import cn.yyxx.eyuancomm.comm.internal.ICallback
import cn.yyxx.support.hawkeye.LogUtils
import cn.yyxx.support.hawkeye.ToastUtils
import kotlin.system.exitProcess


/**
 * @author #Suyghur.
 * Created on 2021/06/09
 */
class DemoActivity : AppCompatActivity(), View.OnClickListener {

    private val events = mutableListOf(
        Item(0, "00 接口环境切换"),
        Item(1, "01 登录"),
        Item(2, "02 切换账号"),
        Item(3, "03 角色创建上报"),
        Item(4, "04 角色登录上报"),
        Item(5, "05 角色升级上报"),
        Item(6, "06 应用内购"),
        Item(7, "07 crashlytics崩溃测试"),
//        Item(8, "08 当前账号取消关联")
    )

    private lateinit var layout: LinearLayout
    private lateinit var mTextView: TextView
    private var cacheRoleInfo: CacheRoleInfo.RoleInfo? = null

    private val message: StringBuilder by lazy {
        StringBuilder()
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        LogUtils.handler = handler
        EYuanCommSdk.getInstance().initialize(this, true, object : ICallback {
            override fun onResult(code: Int, result: String) {
                ToastUtils.toastInfo(this@DemoActivity, "---- demo提示不做翻译 ----\ncode : $code\n msg : $result\n ---- demo提示不做翻译 ----")
                if (code == 0) {
                    EYuanCommSdk.getInstance().setOnFloatBallLogout(object : ICallback {
                        override fun onResult(code: Int, result: String) {
                            ToastUtils.toastInfo(this@DemoActivity, "---- demo提示不做翻译 ----\ncode : $code\n msg : $result\n ---- demo提示不做翻译 ----")
                        }
                    })
                }
            }
        })
    }

    private fun initView() {
        layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL

        initButton()
        mTextView = TextView(this)
        with(mTextView) {
            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)
            }
        }
    }

    override fun onClick(v: View?) {
        mTextView.text = ""
        message.clear()
        v?.apply {
            when (tag as Int) {
                0 -> EnvActivity.start(this@DemoActivity)
                1 -> {
                    EYuanCommSdk.getInstance().login(this@DemoActivity, object : ICallback {
                        override fun onResult(code: Int, result: String) {
                            ToastUtils.toastInfo(this@DemoActivity, "---- demo提示不做翻译 ----\ncode : $code\n msg : $result\n ---- demo提示不做翻译 ----")
                            if (code == 0) {
                                cacheRoleInfo = CacheRoleInfo.getDemoRoleInfo(this@DemoActivity, EYuanCommSdk.getInstance().getCurrentUserId())
                            }
                        }
                    })
                }
                2 -> {
                    EYuanCommSdk.getInstance().logout(this@DemoActivity, object : ICallback {
                        override fun onResult(code: Int, result: String) {
                            if (code == 0) {
                                EYuanCommSdk.getInstance().login(this@DemoActivity, object : ICallback {
                                    override fun onResult(code: Int, result: String) {
                                        ToastUtils.toastInfo(this@DemoActivity, "---- demo提示不做翻译 ----\ncode : $code\n msg : $result\n ---- demo提示不做翻译 ----")
                                    }
                                })
                            }
                        }
                    })
                }
                3 -> {
                    cacheRoleInfo = null
                    cacheRoleInfo = CacheRoleInfo.setDemoRoleInfo(this@DemoActivity, EYuanCommSdk.getInstance().getCurrentUserId())
                    EYuanCommSdk.getInstance().roleCreate(this@DemoActivity, getGameRoleInfo())
                }
                4 -> EYuanCommSdk.getInstance().roleLauncher(this@DemoActivity, getGameRoleInfo())
                5 -> EYuanCommSdk.getInstance().roleLevelUp(this@DemoActivity, getGameRoleInfo())
                6 -> {
                    EYuanCommSdk.getInstance().charge(this@DemoActivity, getGameChargeInfo(), object : ICallback {
                        override fun onResult(code: Int, result: String) {
                            ToastUtils.toastInfo(this@DemoActivity, "---- demo提示不做翻译 ----\ncode : $code\n msg : $result\n ---- demo提示不做翻译 ----")
                        }

                    })
                }
                7 -> throw RuntimeException("Test Crashlytics Feature")
//                8 -> {
//                    AGConnectAuth.getInstance().deleteUser()
//                    EYuanCommSdk.getInstance().logout(this@DemoActivity, object : ICallback {
//                        override fun onResult(code: Int, result: String) {
//                            ToastUtils.toastInfo(this@DemoActivity, "---- demo提示不做翻译 ----\n取消关联后将登出当前账号，请重新登录\n ---- demo提示不做翻译 ----")
//                        }
//                    })
//                }

            }
        }
    }


    private fun getGameRoleInfo(): SdkRoleInfo {
        val gameRoleInfo = SdkRoleInfo()
        //用户ID
        gameRoleInfo.userId = EYuanCommSdk.getInstance().getCurrentUserId()
        cacheRoleInfo?.apply {
            //角色ID
            gameRoleInfo.roleId = roleId
            //角色名称
            gameRoleInfo.roleName = roleName
            //角色等级
            gameRoleInfo.roleLevel = roleLevel
            gameRoleInfo.roleCTime = roleCTime
            //服务器ID
            gameRoleInfo.serverId = serverCode
            //服务器名
            gameRoleInfo.serverName = serverName
            //用户VIP等级，无该字段则传空串""
            gameRoleInfo.vipLevel = vipLevel
            //当前角色游戏币余额
            gameRoleInfo.balance = balance
            gameRoleInfo.totalPurchase = totalPurchase
        }
        return gameRoleInfo
    }

    private fun getGameChargeInfo(): SdkChargeInfo {
        val gameChargeInfo = SdkChargeInfo()
        val orderId = "order_" + System.currentTimeMillis()
        //用户ID
        gameChargeInfo.userId = EYuanCommSdk.getInstance().getCurrentUserId()
        cacheRoleInfo?.apply {
            //角色ID
            gameChargeInfo.roleId = roleId
            //角色名称
            gameChargeInfo.roleName = roleName
            //角色等级
            gameChargeInfo.roleLevel = roleLevel
            //创角时间戳
            gameChargeInfo.roleCTime = roleCTime
            //服务器ID
            gameChargeInfo.serverId = serverCode
            //服务器名
            gameChargeInfo.serverName = serverName
        }
        //游戏的订单号
        gameChargeInfo.cpOrderId = orderId
        //透传字段，会在回调地址中原样返回
        gameChargeInfo.cpExt = "cp_callback_info||$orderId"
        //金额，单位分，币种美金
        gameChargeInfo.amount = 100
        //商品ID，计费点
//        gameChargeInfo.productId = "com.shzd.1usd"
        gameChargeInfo.productId = "p.1yuan"
        //商品名称
        gameChargeInfo.productName = "60元寶"
        //商品描述
        gameChargeInfo.productDesc = "60元寶"
        gameChargeInfo.cpPayTime = System.currentTimeMillis() / 1000
        gameChargeInfo.cpPaySign = "test123"
        return gameChargeInfo
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (EYuanCommSdk.getInstance().hasExitView(this)) {
                EYuanCommSdk.getInstance().openExitView(this, object : ICallback {
                    override fun onResult(code: Int, result: String) {
                        if (code == 0) {
                            finish()
                        }
                    }
                })
            } else {
                val exitDialog = AlertDialog.Builder(this)
                    .setCancelable(true)
                    .setMessage("您确定退出游戏吗？")
                    .setNeutralButton("下次再见") { dialog, _ ->
                        dialog.dismiss()
                        finish()
                    }
                    .setPositiveButton("再玩一下") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .create()
                exitDialog.show()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onStart() {
        super.onStart()
        EYuanCommSdk.getInstance().onStart(this)
    }

    override fun onResume() {
        super.onResume()
        EYuanCommSdk.getInstance().onResume(this)
    }

    override fun onRestart() {
        super.onRestart()
        EYuanCommSdk.getInstance().onRestart(this)
    }

    override fun onPause() {
        super.onPause()
        EYuanCommSdk.getInstance().onPause(this)
    }

    override fun onStop() {
        super.onStop()
        EYuanCommSdk.getInstance().onStop(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EYuanCommSdk.getInstance().onDestroy(this)
        exitProcess(0)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        EYuanCommSdk.getInstance().onActivityResult(this, requestCode, resultCode, data)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        EYuanCommSdk.getInstance().onNewIntent(this, intent)
    }
}

data class Item(val id: Int, val name: String)

