package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.annotation.SuppressLint
import androidx.lifecycle.*
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.livedata.NonStickyMutableLiveData
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.entity.CalendarEntity
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.feature.entity.ServerCalendarNotifySetting
import com.gh.gamecenter.feature.entity.WXSubscribeMsgConfig
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class ServersCalendarDetailsRemindViewModel(
    val id: String
) : ViewModel() {

    val error = NonStickyMutableLiveData<Throwable>()

    lateinit var serverCalendarEntityLiveData: LiveData<ServerCalendarEntity?>
        private set

    val notifySettingChangeLiveData = MutableLiveData<Pair<String, ServerCalendarNotifySetting?>>()

    val wxSubscribeMsgConfigLiveData = MutableLiveData<WXSubscribeMsgConfig>()

    private var isDataInit = false

    var selectedNotifyTime: Long = 0L

    var selectedAdvancedTime: ServersCalendarAdvancedTime = ServersCalendarAdvancedTime.IN_TIME

    var appRemind: Boolean = false

    val wechatRemind: Boolean = false

    val selectedNotifySeconds: Int get() = (selectedNotifyTime / 1000).toInt()

    fun initCalendarLiveData(source: LiveData<CalendarEntity?>) {
        serverCalendarEntityLiveData = Transformations.switchMap(source) {
            Transformations.distinctUntilChanged(
                MutableLiveData(
                    it?.server?.find { calendar ->
                        calendar.id == id
                    }
                )
            )
        }
    }

    fun initData(calendarEntity: ServerCalendarEntity) {
        if (isDataInit) return
        val notifySetting = calendarEntity.notifySetting
        selectedAdvancedTime = ServersCalendarAdvancedTime.valueOf(notifySetting?.secondsAdvance)
        selectedNotifyTime = (notifySetting?.notifyTime ?: calendarEntity.getTime()) * 1000
        appRemind = notifySetting?.byApp ?: SPUtils.getBoolean(Constants.SP_SERVERS_CALENDAR_BY_APP, true)
//        wechatRemind = notifySetting?.byWechat ?: SPUtils.getBoolean(Constants.SP_SERVERS_CALENDAR_BY_WECHAT, true)
        isDataInit = true
    }

    @SuppressLint("CheckResult")
    fun getServerCalenderRemind(gameId: String) {
        RetrofitManager.getInstance().newApi
            .getServerCalendarRemind(gameId, id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                notifySettingChangeLiveData.postValue(id to it)
            }, {
                notifySettingChangeLiveData.postValue(id to null)
            })
    }

    @SuppressLint("CheckResult")
    fun getWXSubscribeMsgConfig() {
        RetrofitManager.getInstance().newApi
            .getWxSubscribeMsgConfig(UrlFilterUtils.getFilterQuery("type", "server_open"))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    wxSubscribeMsgConfigLiveData.postValue(it)
                }, {
                    error.postValue(it)
                })
    }

    @SuppressLint("CheckResult")
    fun addServerCalendarRemind(gameId: String) {
        val requestBody = mapOf(
            "notify_time" to selectedNotifySeconds,
            "seconds_advance" to selectedAdvancedTime.value,
            "by_app" to appRemind,
            "by_wechat" to wechatRemind
        ).toRequestBody()

        RetrofitManager.getInstance().newApi
            .addServerCalendarRemind(gameId, id, requestBody)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                getServerCalenderRemind(gameId)
            }, {
                error.postValue(it)
            })
    }

    @SuppressLint("CheckResult")
    fun addServerCalendarRemindWithWechat(
        gameId: String,
        openId: String?,
        templateId: String?,
        action: String,
        reserved: String,
        scene: Int,
    ) {
        val requestBody = mapOf(
            "openid" to openId,
            "template_id" to templateId,
            "action" to action,
            "scene" to scene,
            "user_id" to reserved
        ).toRequestBody()

        RetrofitManager.getInstance().newApi
            .postWxSubscribeMsgCallback(UrlFilterUtils.getFilterQuery("type", "server_open"), requestBody)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                addServerCalendarRemind(gameId)
            }, {
                error.postValue(it)
            })
    }

    @SuppressLint("CheckResult")
    fun removeServerCalendarRemind(gameId: String) {
        RetrofitManager.getInstance().newApi
            .removeServerCalendarRemind(gameId, id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                getServerCalenderRemind(gameId)
            }, {
                error.postValue(it)
            })
    }

    class Factory(
        private val id: String
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ServersCalendarDetailsRemindViewModel(id) as T
        }
    }
}