package com.gh.gamecenter

import android.annotation.SuppressLint
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.AndroidViewModel
import com.gh.common.util.DeviceTokenUtils
import com.gh.common.util.LunchType
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.entity.DeviceDialogEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList

class SplashScreenViewModel(application: Application) : AndroidViewModel(application) {

    private val mApi by lazy { RetrofitManager.getInstance().api }

    /**
     * 获取游戏弹窗列表
     */
    @SuppressLint("CheckResult")
    fun deviceDialogSetting() {
        mApi.deviceDialogs()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<DeviceDialogEntity>>() {
                override fun onSuccess(data: List<DeviceDialogEntity>) {
                    if (data.isNotEmpty()) {
                        SPUtils.setString(Constants.SP_DEVICE_REMIND, GsonUtils.toJson(data))
                    }
                }
            })
    }

    /**
     * 获取礼仪考试开关状态
     */
    @SuppressLint("CheckResult")
    fun regulationTestStatus() {
        mApi.regulationTestStatus
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    try {
                        val obj = JSONObject(data.string())
                        SPUtils.setString(Constants.SP_REGULATION_TEST_STATUS, obj.getString("status"))
                    } catch (e: Throwable) {
                        e.printStackTrace()
                    }
                }
            })
    }

    /**
     * 获取游戏详情过滤标签数据
     */
    fun filterDetailTags() {
        mApi.filterDetailTags
            .subscribe(object : Response<ArrayList<String?>?>() {
                override fun onResponse(response: ArrayList<String?>?) {
                    super.onResponse(response)
                    SPUtils.setString(Constants.SP_FILTER_TAGS, GsonUtils.toJson(response))
                }
            })
    }


    /**
     * 判断新老用户
     */
    @SuppressLint("CheckResult")
    fun postMark(mIsNewForThisVersion: Boolean) {
        // 安装相应包名以后不需请求接口获取返回数据
        if (PackageUtils.isInstalled(HaloApp.getInstance().application, "com.enotary.cloud")) {
            HaloApp.getInstance().serverUserMark = "new"
            return
        }
        val body: RequestBody
        val map = HashMap<String, String>()
        if (mIsNewForThisVersion) {
            // gid 不存在 (因网络延迟还没获取到时，本地生成一个临时 id 供这个接口用)
            if (TextUtils.isEmpty(HaloApp.getInstance().gid)
                && TextUtils.isEmpty(HaloApp.getInstance().temporaryLocalDeviceId)
            ) {
                val localTemporaryDeviceId = UUID.randomUUID().toString()
                HaloApp.getInstance().setLocalTemporaryDeviceId(localTemporaryDeviceId)
                SPUtils.setString(Constants.SP_TEMPORARY_DEVICE_ID, localTemporaryDeviceId)
            }
            map["launch_type"] = DeviceTokenUtils.getLaunchType().name
        } else if (HaloApp.getInstance().isReinstallTheSameVersion) {
            map["launch_type"] = LunchType.UPDATE.toString()
        }
        body = map.toRequestBody()
        mApi.postMark(body)
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    try {
                        val obj = JSONObject(data.string())
                        HaloApp.getInstance().serverUserMark = obj.getString("mark")
                    } catch (e: Throwable) {
                        e.printStackTrace()
                    }
                }
            })
    }
}