package com.gh.gamecenter.personalhome

import android.annotation.SuppressLint
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.common.util.ErrorHelper
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.createRequestBody
import com.gh.gamecenter.R
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.google.gson.JsonObject
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

class UserHomeViewModel(application: Application, var userId: String) : AndroidViewModel(application) {

    var userInfo = MutableLiveData<PersonalEntity>()
    var networkError = MutableLiveData<Boolean>()
    var badges = MutableLiveData<List<BadgeEntity>>()
    var availableBadge = MutableLiveData<BadgeEntity>()
    var availableBadgeCount = MutableLiveData<Int>()
    var playGamesCount = MutableLiveData<Int>()
    var level = MutableLiveData<Int>()

    fun getUserInfo() {
        RetrofitManager.getInstance()
            .api.getPersonalData(userId, HaloApp.getInstance().channel, Utils.getTime(getApplication()))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : com.gh.gamecenter.common.retrofit.Response<PersonalEntity>() {
                override fun onResponse(response: PersonalEntity?) {
                    userInfo.value = response
                }

                override fun onFailure(e: HttpException?) {
                    networkError.value = true
                }
            })
    }

    fun follow() {
        followingCommand(true)
    }

    fun unFollow() {
        followingCommand(false)
    }


    @SuppressLint("CheckResult")
    fun getUserPlayedGameCount() {
        RetrofitManager.getInstance()
            .api.getPlayedGamesCount(userId, Utils.getTime(getApplication()))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<retrofit2.Response<ResponseBody>>() {
                override fun onSuccess(data: retrofit2.Response<ResponseBody>) {
                    var countContent = data.headers().get("Total")
                    playGamesCount.postValue(if (TextUtils.isEmpty(countContent)) 0 else countContent?.toInt() ?: 0)
                }
            })
    }

    private fun followingCommand(isFollow: Boolean) {
        val observable = if (isFollow) {
            RetrofitManager.getInstance().api.postFollowing(userId)
        } else {
            RetrofitManager.getInstance().api.deleteFollowing(userId)
        }
        observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : com.gh.gamecenter.common.retrofit.Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    if (isFollow) {
                        Utils.toast(getApplication(), R.string.concern_success)   // 关注成功
                    }

                    userInfo.value?.let {
                        it.me.isFollower = isFollow
                        it.count.fans = if (isFollow) it.count.fans + 1 else it.count.fans - 1
                        userInfo.postValue(it)
                    }

                    EventBus.getDefault().post(EBUserFollow(userId, isFollow))
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    Utils.toast(getApplication(), R.string.loading_failed_hint)
                }
            })
    }

    fun getBadgeList() {
        RetrofitManager.getInstance()
            .api.getBadges(userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : com.gh.gamecenter.common.retrofit.Response<List<BadgeEntity>>() {
                override fun onResponse(response: List<BadgeEntity>?) {
                    super.onResponse(response)
                    badges.postValue(response)
                }
            })
    }

    fun availableBadges() {
        RetrofitManager.getInstance()
            .api.availableBadges(userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : com.gh.gamecenter.common.retrofit.Response<List<BadgeEntity>>() {
                override fun onResponse(response: List<BadgeEntity>?) {
                    super.onResponse(response)
                    availableBadge.postValue(if (response.isNullOrEmpty()) null else response[0])
                    availableBadgeCount.postValue(response?.count() ?: 0)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getUserLevel() {
        RetrofitManager.getInstance()
            .api.getUserLevels(userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<JsonObject>() {
                override fun onSuccess(data: JsonObject) {
                    level.postValue(data["level"].asInt)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun postReport(reason: String, desc: String) {
        val requestMap = hashMapOf<String, String>()
        requestMap["reason"] = reason
        if (reason == "其他原因") {
            requestMap["description"] = desc
        }
        RetrofitManager.getInstance()
            .api.reportUser(userId, requestMap.createRequestBody())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    ToastUtils.showToast("举报成功")
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    if (exception is HttpException) {
                        ErrorHelper.handleError(
                            HaloApp.getInstance().application,
                            exception.response().errorBody()?.string()
                        )
                    }
                }
            })
    }

    class Factory(
        private val mApplication: Application,
        private val mUserId: String
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return UserHomeViewModel(mApplication, mUserId) as T
        }
    }

}