package com.gh.gamecenter.energy.utils

import android.annotation.SuppressLint
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.debugOnly
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.energy.R
import com.gh.gamecenter.energy.entity.EnergyTaskCompleteEntity
import com.gh.gamecenter.energy.retrofit.RetrofitManager
import com.gh.gamecenter.energy.view.EnergyCenterActivity
import com.lightgame.utils.AppManager
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import org.json.JSONObject

/**
 * 上报光能任务辅助类
 */
object EnergyTaskHelper {

    @JvmStatic
    fun postEnergyTask(action: String) {
        postEnergyTask(action, null, null, null)
    }

    @JvmStatic
    fun postEnergyTask(action: String, id: String) {
        postEnergyTask(action, id, null, null)
    }

    @JvmStatic
    fun postEnergyTask(action: String, id: String, packageName: String) {
        postEnergyTask(action, id, packageName, null)
    }

    @JvmStatic
    fun postEnergyTaskForWeb(action: String, url: String) {
        postEnergyTask(action, null, null, url)
    }

    @JvmStatic
    fun postEnergyTaskForShare(type: String, id: String, url: String) {
        when (type) {
            "游戏详情" -> postEnergyTask("share_game_detail", id)

            "视频" -> postEnergyTask("share_video", id)

            "资讯文章" -> postEnergyTask("share_article", id)

            "问题详情" -> postEnergyTask("share_question", id)

            "回答详情" -> postEnergyTask("share_answer", id)

            "文章详情" -> postEnergyTask("share_community_article", id)

            "工具箱" -> postEnergyTask("share_toolkit", id)

            "web链接" -> postEnergyTaskForWeb("share_web", url)
        }
    }

    @SuppressLint("CheckResult")
    @JvmStatic
    fun postEnergyTask(action: String, id: String? = null, packageName: String? = null, url: String? = null) {
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            val taskParams = JSONObject()
            taskParams.put("action", action)

            val actionParams = JSONObject()
            if (id != null) actionParams.put("_id", id)
            if (packageName != null) actionParams.put("package", packageName)
            if (url != null) actionParams.put("url", url)
            taskParams.put("action_param", actionParams)

            debugOnly { Utils.log("EnergyTaskHelper -> $taskParams") }

            val body = RequestBody.create(MediaType.parse("application/json"), taskParams.toString())
            RetrofitManager.getInstance()
                .api.postEnergyTask(UserManager.getInstance().userId, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BiResponse<List<EnergyTaskCompleteEntity>>() {
                    override fun onSuccess(data: List<EnergyTaskCompleteEntity>) {
                        data.forEach { showCompletePopup(it) }
                    }
                })
        }
    }

    @SuppressLint("CheckResult")
    @JvmStatic
    fun postInviteCodeTask(code: String, from: String, callback: (() -> Unit)?) {
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            val taskParams = JSONObject()
            taskParams.put("action", "enter_invite_code")

            val actionParams = JSONObject()
            actionParams.put("code", code)
            actionParams.put("type", "new")
            actionParams.put("from", from)
            taskParams.put("action_param", actionParams)

            debugOnly { Utils.log("EnergyTaskHelper -> $taskParams") }

            val body = RequestBody.create(MediaType.parse("application/json"), taskParams.toString())
            RetrofitManager.getInstance()
                .api.postEnergyTask(UserManager.getInstance().userId, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BiResponse<List<EnergyTaskCompleteEntity>>() {
                    override fun onSuccess(data: List<EnergyTaskCompleteEntity>) {
                        SPUtils.setBoolean(Constants.SP_HAS_COMPLETE_INVITE_CODE, true)
                        callback?.invoke()
                        data.forEach { showCompletePopup(it) }
                    }
                })
        }
    }

    // 完成弹窗
    @JvmStatic
    fun showCompletePopup(entity: EnergyTaskCompleteEntity) {
        tryWithDefaultCatch {
            val currentActivity = AppManager.getInstance().recentActiveActivity
            val popWindow = PopupWindow(LinearLayout.LayoutParams.MATCH_PARENT, 88F.dip2px())

            currentActivity?.run {
                val contentView = View.inflate(this, R.layout.popup_energy_task, null)
                contentView.run {
                    findViewById<TextView>(R.id.taskDesc).text = "恭喜你！完成任务：${entity.name}"
                    findViewById<TextView>(R.id.taskEnergy).text = "+${entity.energy}光能"
                    isFocusable = true
                    isFocusableInTouchMode = true
                    setOnClickListener {
                        if (popWindow != null && popWindow.isShowing) {
                            popWindow.dismiss()
                        }
                        if (currentActivity !is EnergyCenterActivity) {
                            currentActivity.startActivity(EnergyCenterActivity.getIntent(currentActivity))
                        }
                    }
                }

                popWindow.contentView = contentView
                currentActivity.window.decorView.post {
                    popWindow.showAtLocation(currentActivity.window.decorView, Gravity.TOP, 0, 0)
                }

                contentView.postDelayed({
                    tryCatchInRelease {
                        if (popWindow != null && popWindow.isShowing) {
                            popWindow.dismiss()
                        }
                    }
                }, 3000)
            }
        }
    }
}