package com.halo.assistant.fragment.user

import android.annotation.SuppressLint
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.json.json
import com.gh.common.util.*
import com.gh.gamecenter.core.utils.GsonUtils.fromJson
import com.gh.download.DownloadManager
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.login.entity.IdCardEntity
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.login.retrofit.RetrofitManager
import com.gh.gamecenter.login.user.UserRepository
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

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

    val certificateResultLiveData = MutableLiveData<Int>()

    fun getUserInfo(): UserInfoEntity? {
        var userInfoEntity = UserManager.getInstance().userInfoEntity
        val certificationOnlyInfoEntity: UserInfoEntity?
        val deviceCertificationInfoString =
            SPUtils.getString(Constants.SP_DEVICE_CERTIFICATION_PREFIX + HaloApp.getInstance().gid)
        if (!TextUtils.isEmpty(deviceCertificationInfoString)) {
            certificationOnlyInfoEntity = deviceCertificationInfoString.toObject()
            if (userInfoEntity?.idCard == null && certificationOnlyInfoEntity != null) {
                userInfoEntity = certificationOnlyInfoEntity
            }

            userInfoEntity?.idCard?.revise = certificationOnlyInfoEntity?.idCard?.revise
        }

        return userInfoEntity
    }

    @SuppressLint("CheckResult")
    fun postCertification(content: String, gameId: String, isForced: Boolean) {
        val idCardEntity = fromJson(content, IdCardEntity::class.java)
        val json = json {
            "id_card" to json {
                "id" to idCardEntity.id
                "name" to idCardEntity.name
            }
            if (gameId.isNotBlank()) {
                "game_id" to gameId
            }
        }
        RetrofitManager.getInstance().api.postCertification(json.toRequestBody())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody?>() {
                override fun onFailure(exception: Exception) {
                    ErrorHelper.handleErrorWithCustomizedHandler(
                        HaloApp.getInstance(),
                        (exception as? HttpException)?.response()?.errorBody()?.string()
                    ) {
                        if (it == 400012) {
                            NewLogUtils.logCertificationResult(isForced, 3)
                            SensorsBridge.trackEvent(
                                "VerificationComplete",
                                "source_entrance",
                                if (gameId.isNotEmpty() || isForced) "游戏实名" else "主动进入",
                                "result",
                                "认证中"
                            )
                            certificateResultLiveData.postValue(RESULT_PROGRESSING)
                            return@handleErrorWithCustomizedHandler true
                        } else {
                            NewLogUtils.logCertificationResult(isForced, 0)
                            SensorsBridge.trackEvent(
                                "VerificationComplete",
                                "source_entrance",
                                if (gameId.isNotEmpty() || isForced) "游戏实名" else "主动进入",
                                "result",
                                "认证失败"
                            )
                            certificateResultLiveData.postValue(RESULT_UNQUALIFIED)
                            return@handleErrorWithCustomizedHandler false
                        }
                    }
                }

                override fun onSuccess(data: ResponseBody?) {
                    val cachedUserInfo =
                        UserRepository.getInstance().cacheUserInfoEntity

                    // 登录状态下更新实名认证信息
                    if (cachedUserInfo != null) {
                        cachedUserInfo.idCard = content.toObject()
                        UserRepository.getInstance()
                            .cacheAndNotifyUserInfo(cachedUserInfo, true)
                    }

                    tryWithDefaultCatch {
                        val `object` = JSONObject(data?.string() ?: "")
                        val isUnQualified = `object`.getBoolean("minor")
                        var qualifyInt = 1
                        if (!isUnQualified) {
                            qualifyInt = 2
                        }
                        NewLogUtils.logCertificationResult(isForced, qualifyInt)
                        SensorsBridge.trackEvent(
                            "VerificationComplete",
                            "source_entrance",
                            if (gameId.isNotEmpty() || isForced) "游戏实名" else "主动进入",
                            "result",
                            if (qualifyInt == 1) "未成年" else "成年"
                        )
                    }

                    DataUtils.getDeviceCertification(HaloApp.getInstance().gid)

                    certificateResultLiveData.postValue(RESULT_SUCCESS)

                    // 安装因为实名延迟的游戏
                    resumeInstallationIfNeeded()
                    // 重启因为实名认证而处于等待中的任务
                    DownloadManager.getInstance()
                        .resumeAllInvisiblePendingTask()
                }
            })
    }

    /**
     * 安装因为实名延迟的游戏
     */
    private fun resumeInstallationIfNeeded() {
        val pendingInstallation = RealNameHelper.pendingInstallPkgPath
        if (pendingInstallation.isNotEmpty()) {
            val pendingDownloadEntity =
                DownloadManager.getInstance().allDownloadEntity.firstOrNull {
                    it.path == pendingInstallation
                }

            PackageInstaller.install(HaloApp.getInstance(), pendingDownloadEntity)
            RealNameHelper.pendingInstallPkgPath = ""
        }
    }

    companion object {
        const val RESULT_SUCCESS = 1 // 认证成功，通过
        const val RESULT_UNQUALIFIED = 2 // 内容不合规，或其它
        const val RESULT_PROGRESSING = 3 // 实名认证中
    }

}