package com.mints.goodmoney.ui.activitys

import android.os.Bundle
import android.view.View
import com.cmcm.cmgame.*
import com.google.gson.JsonParser
import com.mints.goodmoney.R
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.mvp.presenters.GamePresenter
import com.mints.goodmoney.mvp.views.GameView
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.goodmoney.utils.SpanUtils
import com.mints.library.utils.json.JsonUtil
import kotlinx.android.synthetic.main.activity_liebao_game.*
import kotlinx.android.synthetic.main.header_layout.*
import java.util.*

/**
 * 描述：猎豹游戏
 * 作者：孟崔广
 * 时间：2020/10/12 10:09
 */
class LiebaoGameActivity : BaseActivity()
        , View.OnClickListener, GameView,
        IAppCallback,
        IGamePlayTimeCallback,
        IGameAdCallback,
        IGameExitInfoCallback {

    val AIP_GAME_URL = "api/gametime/add" //退出游戏
    val STASTICIS_GAME_URL = "stasticis/game/add" //点击游戏

    private val gamePresenter by lazy { GamePresenter() }

    private var gameName = ""
    private var gameID = ""

    override fun getContentViewLayoutID() = R.layout.activity_liebao_game

    override fun isApplyKitKatTranslucency() = false

    override fun initViewsAndEvents() {
        tv_title.text = "游戏推荐"
        iv_left_icon.visibility = View.VISIBLE
        iv_left_icon.setImageResource(R.mipmap.ic_arrow_back)

        gamePresenter.attachView(this)

        initListener()
    }

    override fun onResume() {
        super.onResume()
        gamePresenter.getGameInfo()
    }

    override fun onDestroy() {
        super.onDestroy()

        CmGameSdk.removeGameClickCallback()
        CmGameSdk.setMoveView(null)
        CmGameSdk.removeGamePlayTimeCallback()
        CmGameSdk.removeGameAdCallback()
        CmGameSdk.removeGameExitInfoCallback()

        gamePresenter.detachView()
    }

    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.iv_left_icon -> finish()
        }
    }

    private fun initListener() {
        iv_left_icon.setOnClickListener(this)

        gvGameLiebao.inflate(this)
        // 默认游戏中心页面，点击游戏试，触发回调
        CmGameSdk.setGameClickCallback(this)
        // 点击游戏右上角或物理返回键，退出游戏时触发回调，并返回游戏时长
        CmGameSdk.setGamePlayTimeCallback(this)
        // 所有广告类型的展示和点击事件回调，仅供参考，数据以广告后台为准
        CmGameSdk.setGameAdCallback(this)
        // 返回游戏数据(json格式)，如：每玩一关，返回关卡数，分数，如钓钓乐，返回水深，绳子长度，不同游戏不一样
        // 该功能使用场景：媒体利用游戏数据，和app的功能结合做运营活动，比如：某每天前50名，得到某些奖励
        CmGameSdk.setGameExitInfoCallback(this)
    }

    override fun gameInfo(sumTime: Int, sumCoin: Int, gameTime: Int) {
        if(!isFinishing){
            tvGameHint.visibility = View.VISIBLE
            if (gameTime >= sumTime) {
                tvGameHint.setText("今日游戏任务已完成")
            } else {
                tvGameHint.setText(
                        SpanUtils()
                                .append("畅玩").append("${sumTime / 60}").setForegroundColor(mContext.resources.getColor(R.color.main_mints)).append("分钟, ")
                                .append("奖励").append("${sumCoin}").setForegroundColor(mContext.resources.getColor(R.color.red)).append("金币, ")
                                .append("已玩").append("${gameTime / 60}").setForegroundColor(mContext.resources.getColor(R.color.main_mints)).append("分钟")
                                .create())
            }
        }
    }

    override fun gameAddSuc(eventType: String?, data: Any?) {
        when (eventType) {
            Constant.EVENT_TYPE_TIME -> if (data != null) {
                val json = JsonUtil.toJson(data)
                val jsonObject = JsonParser().parse(json).asJsonObject
                val gameCoin = jsonObject["gameCoin"].asInt
                val bundle = Bundle()
                bundle.putInt(Constant.MAIN_CUR_COIN, gameCoin)
                bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_GAME)
                readyGo(AwardActivity::class.java, bundle)
            }
            Constant.EVENT_TYPE_GAMEINFO -> {
            }
            Constant.EVENT_TYPE_CLICK -> {
            }
        }
    }

    /**
     * 默认游戏中心页面，点击游戏试，触发回调   finish
     *
     * @param gameName
     * @param gameID
     */
    override fun gameClickCallback(gameName: String, gameID: String) {
        this.gameName = gameName
        this.gameID = gameID

        val eventTypeClick: String = Constant.EVENT_TYPE_CLICK
        val vo = HashMap<String, Any>()
        vo["gameName"] = gameID
        vo["gameId"] = gameID
        vo["gameSource"] = "liebao"
        vo["carrierType"] = Constant.CARRIER_GAME
        vo["eventType"] = eventTypeClick
        vo["num"] = 1
        vo["pkg"] = Constant.MINTS_PKG_NAME
        gamePresenter.gameAdd(STASTICIS_GAME_URL, eventTypeClick, vo)
    }

    /**
     * @param playTimeInSeconds 玩游戏时长，单位为秒 finish
     *
     *
     * 点击游戏右上角或物理返回键，退出游戏时触发回调，并返回游戏时长
     */
    override fun gamePlayTimeCallback(gameId: String?, playTimeInSeconds: Int) {
        val eventTypeTime: String = Constant.EVENT_TYPE_TIME
        if (playTimeInSeconds < 3) {
            val bundle = Bundle()
            bundle.putInt(Constant.MAIN_CUR_COIN, 0)
            bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_GAME)
            readyGo(AwardActivity::class.java, bundle)
        } else {
            val vo = HashMap<String, Any>()
            vo["gameName"] = gameID
            vo["gameId"] = gameID
            vo["gameSource"] = "liebao"
            vo["carrierType"] = Constant.CARRIER_GAME
            vo["eventType"] = eventTypeTime
            vo["playtimeinseconds"] = playTimeInSeconds
            vo["pkg"] = Constant.MINTS_PKG_NAME
            gamePresenter.gameAdd(AIP_GAME_URL, eventTypeTime, vo)
        }
    }

    /**
     * 广告曝光/点击回调   finish
     *
     * @param gameId   游戏Id
     * @param adType   广告类型：1：激励视频广告；2：Banner广告；3：原生Banner广告；4：全屏视频广告；
     * 5：原生插屏广告；6：开屏大卡广告；7：模板Banner广告；8：模板插屏广告；9：游戏列表信息流广告
     * 10：游戏列表模板插屏广告；11：游戏加载模板插屏广告；12：游戏列表信息流模板渲染广告；
     * 13：游戏退出推荐弹框信息流自渲染广告；14：游戏退出推荐弹框信息流模板渲染广告
     * @param adAction 广告操作：1：曝光；2：点击；3：关闭；4：跳过
     * @param adChannel 广告源：穿山甲，优量汇
     */
    override fun onGameAdAction(gameId: String?, adType: Int, adAction: Int, adChannel: String) {
        if (adAction != 1) {
            val vo = HashMap<String, Any>()
            vo["gameName"] = gameName
            vo["gameId"] = gameID
            vo["gameSource"] = "liebao"
            vo["carrierType"] = Constant.CARRIER_GAME
            var eventTypeView = "VIEW"
            when (adAction) {
                1 -> eventTypeView = "VIEW"
                2 -> eventTypeView = "CLICK"
                3 -> eventTypeView = "CLOSE"
                4 -> eventTypeView = "JUMP"
            }
            vo["adType"] = adType
            vo["adsource"] = adChannel
            vo["eventType"] = eventTypeView
            vo["pkg"] = Constant.MINTS_PKG_NAME
            gamePresenter.gameAdd(STASTICIS_GAME_URL, Constant.EVENT_TYPE_ADCLICK, vo)
        }
    }

    /**
     * 返回游戏数据(json格式)，如：每玩一关，返回关卡数，分数，如钓钓乐，返回水深，绳子长度，不同游戏不一样   finish
     * 该功能使用场景：媒体利用游戏数据，和app的功能结合做运营活动，比如：某每天前50名，得到某些奖励
     */
    override fun gameExitInfoCallback(gameExitInfo: String) {
//        val vo = HashMap<String, Any>()
//        vo["gameName"] = gameName
//        vo["gameId"] = gameID
//        vo["carrierType"] = Constant.CARRIER_GAME
//        vo["gameExitInfo"] = gameExitInfo
//        vo["pkg"] = Constant.MINTS_PKG_NAME
//        gamePresenter.gameAdd(AIP_GAME_URL, Constant.EVENT_TYPE_GAMEINFO, vo)
    }
}
