package com.gh.gamecenter.setting.compose.viewmodel

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.DeviceUtils
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.login.utils.LoginUtils
import com.gh.gamecenter.setting.compose.entity.ConflictUserEntity
import com.gh.gamecenter.setting.compose.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

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

    private val api = RetrofitManager.getInstance().api

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

    @SuppressLint("CheckResult")
    fun bindPhoneOne(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 = jsonObject.toString().toRequestBody(APPLICATION_JSON.toMediaTypeOrNull())

        api.bindPhone(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")) {
                                400150 -> phoneBoundLiveData.postValue(
                                    GsonUtils.fromJson(
                                        content.getJSONObject("detail").toString(), ConflictUserEntity::class.java
                                    )
                                )

                                403202 -> LoginUtils.captchaErrorHint(context, content)

                                else -> LoginUtils.outputErrorHint(context, code)
                            }
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                            Utils.toast(context, "无法获取验证码，请检查你的网络状态")
                        }
                    }
                }
            })
    }

    @SuppressLint("CheckResult")
    fun bindPhoneTwo(phoneNum: String, code: String, inviteCode: String, context: Context) {
        val device = DeviceUtils.getLoginDevice(getApplication())
        val params: MutableMap<String, String> = HashMap()
        params["mobile"] = phoneNum
        params["service_id"] = mServiceId
        params["code"] = code
        if (inviteCode.isNotBlank()) {
            params["invite_code"] = inviteCode
        }
        val jsonObject = JSONObject(params as Map<*, *>)
        jsonObject.put("device", device)
        val body: RequestBody = jsonObject.toString().toRequestBody(APPLICATION_JSON.toMediaTypeOrNull())

        api.bindPhone(2, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    ToastUtils.showToast("手机号绑定成功")
                    finishLiveData.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)

                                400302 -> finishLiveData.postValue(false)

                                403092 -> ToastUtils.showToast("填写邀请码错误")

                                else -> LoginUtils.outputErrorHint(context, code)
                            }
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                            Utils.toast(context, "无法完成绑定，请检查你的网络状态")
                        }
                    }
                }
            })
    }

    @SuppressLint("CheckResult")
    fun reBindPhoneOne(oldPhoneNum: String, phoneNum: String, context: Context) {
        val device = DeviceUtils.getLoginDevice(getApplication())
        val params: MutableMap<String, String> = HashMap()
        params["old_mobile"] = oldPhoneNum
        params["mobile"] = phoneNum
        val jsonObject = JSONObject(params as Map<*, *>)
        jsonObject.put("device", device)
        val body: RequestBody = jsonObject.toString().toRequestBody(APPLICATION_JSON.toMediaTypeOrNull())

        api.reBindPhone(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")) {
                                400150 -> phoneBoundLiveData.postValue(
                                    GsonUtils.fromJson(
                                        content.getJSONObject("detail").toString(), ConflictUserEntity::class.java
                                    )
                                )

                                403202 -> LoginUtils.captchaErrorHint(context, content)

                                else -> LoginUtils.outputErrorHint(context, code)
                            }
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                            Utils.toast(context, "无法获取验证码，请检查你的网络状态")
                        }
                    }
                }
            })
    }

    @SuppressLint("CheckResult")
    fun reBindPhoneTwo(oldPhoneNum: String, phoneNum: String, code: String, inviteCode: String, context: Context) {
        val device = DeviceUtils.getLoginDevice(getApplication())
        val params: MutableMap<String, String> = HashMap()
        params["old_mobile"] = oldPhoneNum
        params["mobile"] = phoneNum
        params["service_id"] = mServiceId
        params["code"] = code
        if (inviteCode.isNotBlank()) {
            params["invite_code"] = inviteCode
        }
        val jsonObject = JSONObject(params as Map<*, *>)
        jsonObject.put("device", device)
        val body: RequestBody = jsonObject.toString().toRequestBody(APPLICATION_JSON.toMediaTypeOrNull())

        api.reBindPhone(2, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    ToastUtils.showToast("手机号更换成功")
                    finishLiveData.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)

                                400302 -> finishLiveData.postValue(false)

                                403092 -> ToastUtils.showToast("填写邀请码错误")

                                else -> LoginUtils.outputErrorHint(context, code)
                            }
                        } catch (e1: Exception) {
                            e1.printStackTrace()
                            Utils.toast(context, "无法完成绑定，请检查你的网络状态")
                        }
                    }
                }
            })
    }

    companion object {
        private const val APPLICATION_JSON = "application/json"
    }
}