package com.gh.gamecenter.qa.answer.edit

import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.*
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.syncpage.SyncDataEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.common.syncpage.SyncPageRepository
import com.gh.gamecenter.R
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.mvvm.Resource
import com.gh.base.BaseRichEditorViewModel
import com.gh.base.RichType
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.qa.entity.AnswerDraftEntity
import com.gh.gamecenter.qa.entity.Questions
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.energy.EnergyBridge
import com.lightgame.utils.Utils
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import okhttp3.internal.http.RealResponseBody
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import org.json.JSONObject
import retrofit2.HttpException

@Deprecated("V5.0废弃")
class AnswerEditViewModel(
    application: Application,
    var answerId: String?, // 以mAnswerId为标识，如果mAnswerId不为空则是-修改答案(不需要保存草稿) 为空则是-编写答案
    var answerContent: String?,
    var draftId: String?,
    var question: Questions
) : BaseRichEditorViewModel(application) {
    private var mPostDraftsCount: Int = 0
    var cacheAnswerContent: String? = null
    val postLiveData = MediatorLiveData<Resource<String>>()
    val deleteDraftLiveDate = MediatorLiveData<Boolean>()
    val draftsLiveData = MediatorLiveData<String>()
    val saveDraftsLiveData = MediatorLiveData<Boolean>() // 自动保存不会回调

    fun postAnswer(editContent: String) {
        processDialog.postValue(WaitingDialogFragment.WaitingDialogData("提交中...", true))

        val content = JSONObject()
        try {
            content.put("content", editContent)
        } catch (e: Throwable) {
            e.printStackTrace()
        }

        val body = RequestBody.create(MediaType.parse("application/json"), content.toString())
        val observable = if (!TextUtils.isEmpty(answerId)) {
            if (editContent == answerContent) { // 内容不变不需要请求服务器，直接返回成功即可
                val responseBody = RealResponseBody("", 0, null)
                Single.just<ResponseBody>(responseBody).toObservable()
            } else {
                mApi.patchQuestionAnswer(body, answerId)
            }
        } else {
            mApi.postQuestionAnswer(body, question.id)
        }
        observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    processDialog.postValue(WaitingDialogFragment.WaitingDialogData("提交中...", false))
                    val data = response?.string()
                    postLiveData.postValue(Resource.success(data))
                    EventBus.getDefault().post(EBReuse(AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG))

                    if (TextUtils.isEmpty(answerId)) {
                        syncAnswerCount()

                        tryWithDefaultCatch {
                            EnergyBridge.postEnergyTask("post_answer", JSONObject(data).optString("_id"))
                        }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    processDialog.postValue(WaitingDialogFragment.WaitingDialogData("提交中...", false))
                    postLiveData.postValue(Resource.error(e))
                }
            })
    }

    private fun syncAnswerCount() {
        SyncPageRepository.postSyncData(
            SyncDataEntity(
                question.id,
                SyncFieldConstants.ANSWER_COUNT,
                ++question.answerCount,
                checkInherited = true,
                checkFieldEntity = true
            )
        )
    }

    fun deleteAnswerDraft() {
        if (draftId.isNullOrEmpty()) {
            deleteDraftLiveDate.postValue(true)
            return
        }

        processDialog.postValue(WaitingDialogFragment.WaitingDialogData("删除中...", true))
        mApi
            .deleteAnswerDrafts(UserManager.getInstance().userId, draftId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    processDialog.postValue(WaitingDialogFragment.WaitingDialogData("删除中...", false))
                    deleteDraftLiveDate.postValue(true)
                    EventBus.getDefault().post(EBReuse(AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG))
                }

                override fun onFailure(e: HttpException?) {
                    processDialog.postValue(WaitingDialogFragment.WaitingDialogData("删除中...", false))
                    deleteDraftLiveDate.postValue(false)
                    Utils.toast(getApplication(), R.string.loading_network_error)
                }
            })
    }

    fun getUserAnswerDrafts() {
        mApi
            .getUserAnswerDrafts(
                question.id,
                UrlFilterUtils.getFilterQuery("answer_id", answerId),
                Utils.getTime(getApplication())
            )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<AnswerDraftEntity>() {
                override fun onResponse(draft: AnswerDraftEntity?) {
                    if (draft?.content != null) {
                        draftsLiveData.postValue(draft.content)
                        cacheAnswerContent = draft.content
                    }

                    draftId = draft?.id

                    if (!TextUtils.isEmpty(draft?.answerId)) { // answerId不为空 表示已经提交过答案了
                        answerId = draft?.answerId
                    }
                }
            })
    }

    fun saveAnswerDrafts(editContent: String, forcedExit: Boolean) {
        val content = JSONObject()
        try {
            content.put("content", editContent)
            content.put("question_id", question.id)
            if (!answerId.isNullOrEmpty()) {
                content.put("answer_id", answerId)
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }

        val body = RequestBody.create(MediaType.parse("application/json"), content.toString())
        mApi
            .postAnswerDrafts(body, UserManager.getInstance().userId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    if (forcedExit) {
                        saveDraftsLiveData.postValue(true)
                        if (checkIsAllUploadedAndToast()) {
                            Utils.toast(getApplication(), "回答已保存到草稿箱")
                        }
                        EventBus.getDefault().post(EBReuse(AnswerEditActivity.ANSWER_DRAFT_CHANGE_TAG))
                    } else {
                        if (mPostDraftsCount >= AnswerEditActivity.SAVE_DRAFTS_TOAST_COUNT) {
                            mPostDraftsCount = 0
                            Utils.toast(getApplication(), "回答已保存到草稿箱")
                        } else {
                            mPostDraftsCount++
                        }
                        cacheAnswerContent = editContent
                    }
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    if (forcedExit) saveDraftsLiveData.postValue(false)
                }
            })
    }

    override fun getRichType(): RichType = RichType.ANSWER

    class Factory(
        private val mApplication: Application,
        private val answerId: String?,
        private val answerContent: String?,
        private val draftId: String?,
        private val question: Questions
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return AnswerEditViewModel(mApplication, answerId, answerContent, draftId, question) as T
        }
    }
}