package com.gh.gamecenter.qa.video.detail.desc

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.common.util.*
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.clickToastByStatus
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.entity.VideoDescItemEntity
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

class VideoDescViewModel(application: Application) :
    ListViewModel<ForumVideoEntity, VideoDescItemEntity>(application) {
    var topVideoDetail: ForumVideoEntity? = null
    var handleSuccessLiveData = MutableLiveData<Boolean>()

    override fun provideDataObservable(page: Int): Observable<MutableList<ForumVideoEntity>>? {
        return RetrofitManager.getInstance().api.getRecommendVideo(
            topVideoDetail?.id,
            page
        )
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { mergeListData(it) }
    }

    fun mergeListData(videoList: List<ForumVideoEntity>?) {
        val mergedList = arrayListOf<VideoDescItemEntity>().apply {
            if (topVideoDetail != null) {
                if (mResultLiveData.value?.firstOrNull() != null) {
                    add(mResultLiveData.value!![0])
                } else {
                    add(VideoDescItemEntity(topVideoInfo = topVideoDetail))
                }
            }
            videoList?.forEach {
                add(VideoDescItemEntity(recommendVideo = it))
            }
        }
        mResultLiveData.postValue(mergedList)
    }

    fun postVote() {
        if (topVideoDetail == null) return
        if (!UserManager.getInstance().isLoggedIn) {
            CheckLoginUtils.checkLogin(getApplication(), "视频详情-点赞") {}
            return
        }
        if (topVideoDetail!!.me.isVoted) {
            undoVoteVideo(topVideoDetail?.id ?: "")
        } else {
            clickToastByStatus(topVideoDetail?.status ?: "") {
                voteVideo(topVideoDetail?.id ?: "")
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun voteVideo(videoId: String) {
        RetrofitManager.getInstance()
            .api.voteVideo(videoId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    topVideoDetail?.let {
                        it.me.isVoted = true
                        it.count.vote = it.count.vote + 1
                        handleSuccessLiveData.postValue(true)
                        ToastUtils.showToast("点赞爆棚，视频能让更多人看见！")
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                videoId,
                                SyncFieldConstants.ARTICLE_VOTE,
                                true,
                                checkFieldEntity = true
                            )
                        )
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                videoId,
                                SyncFieldConstants.ARTICLE_VOTE_COUNT,
                                it.count.vote,
                                checkFieldEntity = true
                            )
                        )
                    }
                }

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

    @SuppressLint("CheckResult")
    private fun undoVoteVideo(videoId: String) {
        RetrofitManager.getInstance()
            .api.undoVoteVideo(videoId)
            .subscribeOn(Schedulers.io())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    topVideoDetail?.let {
                        it.me.isVoted = false
                        it.count.vote = it.count.vote - 1
                        handleSuccessLiveData.postValue(true)
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                videoId,
                                SyncFieldConstants.ARTICLE_VOTE,
                                false,
                                checkFieldEntity = true
                            )
                        )
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                videoId,
                                SyncFieldConstants.ARTICLE_VOTE_COUNT,
                                it.count.vote,
                                checkFieldEntity = true
                            )
                        )
                    }
                }

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

    fun postFavorite() {
        if (topVideoDetail == null) return
        if (!UserManager.getInstance().isLoggedIn) {
            CheckLoginUtils.checkLogin(getApplication(), "视频详情") {}
            return
        }
        if (topVideoDetail!!.me.isVideoFavorite) {
            undoFavoriteVideo(topVideoDetail?.id ?: "")
        } else {
            clickToastByStatus(topVideoDetail?.status ?: "") {
                favoriteVideo(topVideoDetail?.id ?: "")
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun favoriteVideo(videoId: String) {
        RetrofitManager.getInstance()
            .api.collectVideo(UserManager.getInstance().userId, videoId)
            .compose(singleToMain())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    topVideoDetail?.let {
                        it.me.isVideoFavorite = true
                        it.count.favorite++
                        handleSuccessLiveData.postValue(true)
                    }
                    ToastUtils.toast("收藏成功")
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    Utils.toast(getApplication(), exception.localizedMessage)
                }
            })
    }

    @SuppressLint("CheckResult")
    private fun undoFavoriteVideo(videoId: String) {
        RetrofitManager.getInstance()
            .api.undoCollectVideo(UserManager.getInstance().userId, videoId)
            .compose(singleToMain())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    topVideoDetail?.let {
                        it.me.isVideoFavorite = false
                        it.count.favorite--
                        handleSuccessLiveData.postValue(true)
                    }
                    ToastUtils.toast("取消收藏")
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    Utils.toast(getApplication(), exception.localizedMessage)
                }
            })
    }

    fun followCommand() {
        if (topVideoDetail == null) return
        if (!UserManager.getInstance().isLoggedIn) {
            CheckLoginUtils.checkLogin(getApplication(), "视频详情") {}
            return
        }
        val observable = if (topVideoDetail?.me?.isFollower == false) {
            RetrofitManager.getInstance().api.postFollowing(topVideoDetail?.user?.id)
        } else {
            RetrofitManager.getInstance().api.deleteFollowing(topVideoDetail?.user?.id)
        }
        observable
            .compose(observableToMain())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    topVideoDetail?.let {
                        if (!it.me.isFollower) {
                            ToastUtils.showToast("关注成功")
                        }
                        it.me.isFollower = !it.me.isFollower
                    }
                    handleSuccessLiveData.postValue(true)

                    topVideoDetail?.run {
                        SyncPageRepository.postSyncData(
                            SyncDataEntity(
                                id,
                                SyncFieldConstants.IS_FOLLOWER,
                                me.isFollower,
                                checkFieldEntity = true
                            )
                        )
                        EventBus.getDefault().post(EBUserFollow(user.id, me.isFollower))
                    }
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    ToastUtils.showToast("加载失败，请检查网络状态")
                }
            })
    }
}