package com.gh.common.util

import android.annotation.SuppressLint
import android.content.Context
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.Constants
import com.gh.common.repository.ReservationRepository
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.GlobalActivityManager.getCurrentPageEntity
import com.gh.gamecenter.common.base.GlobalActivityManager.getLastPageEntity
import com.gh.gamecenter.common.callback.CancelListener
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.entity.WechatConfigEntity
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.provider.IPushProvider
import com.gh.gamecenter.entity.ReserveReminderEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import okhttp3.ResponseBody

object ReservationHelper {

    @SuppressLint("CheckResult")
    @JvmStatic
    fun cancelReservation(
        game: GameEntity,
        refreshCallback: EmptyCallback
    ) {
        val retrofit = RetrofitManager.getInstance()
        retrofit.newApi
            .cancelGameReservation(
                game.id,
                getReserveRequestBody(game, context = HaloApp.getInstance().application)
            )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    ReservationRepository.removeReservationFromMemoryAndRefresh(game.id)
                    refreshCallback.onCallback()
                }

                override fun onFailure(exception: Exception) {
                    Utils.toast(HaloApp.getInstance().application, exception.message)
                    exception.printStackTrace()
                }
            })
    }

    @JvmStatic
    @SuppressLint("CheckResult")
    fun reserve(context: Context, game: GameEntity?, sourceEntrance: String = "其他", callback: EmptyCallback) {

        RetrofitManager.getInstance().newApi
            .createNewGameReservation(game?.id ?: "", getReserveRequestBody(game, context))
            .compose(singleToMain())
            .subscribe(object : BiResponse<ReserveReminderEntity>() {

                override fun onSuccess(data: ReserveReminderEntity) {
                    SensorsBridge.trackEvent(
                        "AppointmentGameResult",
                        "game_name", game?.name ?: "",
                        "game_id", game?.id ?: "",
                        "game_type", game?.categoryChinese ?: "",
                        "result", "成功",
                        "source_entrance", sourceEntrance,
                        "page_name", getCurrentPageEntity().pageName,
                        "page_id", getCurrentPageEntity().pageId,
                        "page_business_id", getCurrentPageEntity().pageBusinessId,
                        "last_page_name", getLastPageEntity().pageName,
                        "last_page_id", getLastPageEntity().pageId,
                        "last_page_business_id", getLastPageEntity().pageBusinessId,
                        "source", game?.exposureEvent?.source?.toString() ?: "",
                        "is_ad", if (game?.adGroupId.isNullOrEmpty() == true) "false" else "true",
                        "ad_group_id", game?.adGroupId ?: "",
                        *game?.customPageTrackData?.toKV() ?: arrayOf()
                    )

                    ReservationRepository.addReservationToMemoryAndRefresh(game?.id ?: "")
                    callback.onCallback()

                    checkWechatConfigEntityUpdated(data.wechatConfig)

                    game?.let {
                        SensorsBridge.trackAppointmentSuccessDialogShow(
                            it.id,
                            it.name ?: "",
                            it.categoryChinese,
                            data.wechatConfig.isReminderEnable,
                            if (data.hasSmsConfig) data.smsConfig.notice else null,
                            if (data.isEnableAutoDownload) data.wifiAutoDownload else null,
                            if (data.hasCalendarConfig) false else null
                        )
                    }

                    DialogUtils.showReserveReminderDialog(context, game, data)
                }

                override fun onFailure(exception: Exception) {
                    SensorsBridge.trackEvent(
                        "AppointmentGameResult",
                        "game_name", game?.name ?: "",
                        "game_id", game?.id ?: "",
                        "game_type", game?.categoryChinese ?: "",
                        "result", "失败",
                        "source_entrance", sourceEntrance,
                        "page_name", getCurrentPageEntity().pageName,
                        "page_id", getCurrentPageEntity().pageId,
                        "page_business_id", getCurrentPageEntity().pageBusinessId,
                        "last_page_name", getLastPageEntity().pageName,
                        "last_page_id", getLastPageEntity().pageId,
                        "last_page_business_id", getLastPageEntity().pageBusinessId,
                        "source", game?.exposureEvent?.source?.toString() ?: "",
                        "is_ad", if (game?.adGroupId.isNullOrEmpty() == true) "false" else "true",
                        "ad_group_id", game?.adGroupId ?: "",
                        *game?.customPageTrackData?.toKV() ?: arrayOf()
                    )
                    ToastUtils.showToast(exception.message ?: "")
                }
            })
    }

    @JvmStatic
    fun showCancelReservationDialog(context: Context, game: GameEntity?, emptyCallback: EmptyCallback) {
        showCancelReservationDialog(context, game, emptyCallback, null)
    }

    @JvmStatic
    fun showCancelReservationDialog(
        context: Context,
        game: GameEntity?,
        emptyCallback: EmptyCallback,
        cancelListener: CancelListener?,
        dialogCancelCallback: (() -> Unit)? = null
    ) {
        if (game != null) {
            SensorsBridge.trackCancelAppointmentDialogShow(game.id, game.name ?: "", game.categoryChinese)
        }
        DialogHelper.showDialog(context, "取消预约",
            "取消之后你将无法收到游戏上线的通知，确定取消预约吗？",
            "确定取消",
            "暂不取消", confirmClickCallback = {
                if (game != null) {
                    SensorsBridge.trackCancelAppointmentDialogClick(
                        game.id,
                        game.name ?: "",
                        game.categoryChinese,
                        "确定取消"
                    )
                }
                emptyCallback.onCallback()
            }, cancelClickCallback = {
                if (game != null) {
                    SensorsBridge.trackCancelAppointmentDialogClick(
                        game.id,
                        game.name ?: "",
                        game.categoryChinese,
                        "暂不取消"
                    )
                }
                cancelListener?.onCancel()
            }, uiModificationCallback = {
                it.confirmTv.setTextColor(com.gh.gamecenter.common.R.color.secondary_red.toColor(context))
            }, extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true),
            dialogCancelCallback = {
                if (game != null) {
                    SensorsBridge.trackCancelAppointmentDialogClick(
                        game.id,
                        game.name ?: "",
                        game.categoryChinese,
                        "关闭弹窗"
                    )
                }
                dialogCancelCallback?.invoke()
            }
        )
    }

    private fun checkWechatConfigEntityUpdated(newWechatConfig: WechatConfigEntity) {
        val wechatConfig = SPUtils.getString(Constants.SP_WECHAT_CONFIG).toObject<WechatConfigEntity>()
        if (newWechatConfig.bind != wechatConfig?.bind
            || newWechatConfig.follow != wechatConfig.follow
            || newWechatConfig.notice != wechatConfig.notice
            || newWechatConfig.nickName != wechatConfig.nickName
        ) {
            SPUtils.setString(Constants.SP_WECHAT_CONFIG, newWechatConfig.toJson())
        }
    }

    @JvmStatic
    fun getReserveRequestBody(game: GameEntity?, context: Context): RequestBody {
        val jPushId =
            (TheRouter.get(IPushProvider::class.java))
                ?.getRegistrationId(context) ?: ""
        var mirrorPosition = game?.getMirrorPosition() ?: 0
        if (mirrorPosition == -1) {
            mirrorPosition = 0
        }
        val body = hashMapOf(
            "jpush_id" to jPushId,
            "mirror_type" to mirrorPosition
        ).toRequestBody()
        return body
    }
}