package com.halo.assistant.fragment.user

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.utils.DeviceUtils
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.feature.entity.MobileAuthEntity
import com.gh.gamecenter.login.user.UserRepository
import com.gh.gamecenter.login.utils.LoginUtils
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

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

    private val api = RetrofitManager.getInstance().api

    var nextLiveData = MutableLiveData<Boolean>()
    var finishLiveData = MutableLiveData<Boolean>()
    private var mServiceId = ""

    @SuppressLint("CheckResult")
    fun verifyPhoneOne(phoneNum: String, context: Context) {
        val device = DeviceUtils.getLoginDevice(getApplication())
        val params: MutableMap<String, String> = HashMap()
        params["mobile"] = phoneNum
        val jsonObject = JSONObject(params as Map<*, *>)
        jsonObject.put("device", device)
        val body: RequestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())

        api.verifyPhone(1, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    val body = JSONObject(data.string())
                    mServiceId = body.getString("service_id") ?: ""
                    nextLiveData.postValue(true)
                }

                override fun onFailure(e: Exception) {
                    super.onFailure(e)
                    if (e is HttpException) {
                        try {
                            val responseBody = e.response().errorBody()
                            val string = responseBody!!.string()
                            val content = JSONObject(string)
                            when (val code = content.getInt("code")) {
                                403202 -> LoginUtils.captchaErrorHint(context, content)
                                else -> LoginUtils.outputErrorHint(context, code)
                            }
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                            Utils.toast(context, "无法获取验证码，请检查你的网络状态")
                        }
                    }
                }
            })
    }

    @SuppressLint("CheckResult")
    fun verifyPhoneTwo(phoneNum: String, code: String, context: Context) {
        val device = DeviceUtils.getLoginDevice(getApplication())
        val params: MutableMap<String, String> = HashMap()
        params["mobile"] = phoneNum
        params["service_id"] = mServiceId
        params["code"] = code
        val jsonObject = JSONObject(params as Map<*, *>)
        jsonObject.put("device", device)
        val body: RequestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())

        api.verifyPhone(2, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    val cachedUserInfo = UserRepository.getInstance().cacheUserInfoEntity
                    if (cachedUserInfo != null) {
                        val body = JSONObject(data.string())
                        val entity = body.getString("mobile_auth").toObject() ?: MobileAuthEntity()
                        cachedUserInfo.mobileAuth = entity.apply {
                            remark = cachedUserInfo.mobileAuth?.remark ?: LinkEntity()
                        }
                        UserRepository.getInstance().cacheAndNotifyUserInfo(cachedUserInfo, true)
                    }
                    finishLiveData.postValue(true)
                    NewFlatLogUtils.logPhoneNumberVerifyDialogSuccess()
                }

                override fun onFailure(e: Exception) {
                    super.onFailure(e)
                    if (e is HttpException) {
                        try {
                            val responseBody = e.response().errorBody()
                            val string = responseBody!!.string()
                            val content = JSONObject(string)
                            when (val code = content.getInt("code")) {
                                403202 -> LoginUtils.captchaErrorHint(context, content)
                                else -> LoginUtils.outputErrorHint(context, code)
                            }
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                            Utils.toast(context, "无法完成验证，请检查你的网络状态")
                        }
                    }
                }
            })
    }
}