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

import android.app.Dialog
import android.graphics.Paint
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import com.gh.common.constant.Config
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.WXAPIProxyFactory
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogServersCalendearDetailBinding
import com.gh.gamecenter.databinding.LayoutServersCalendarDetailNoDataBinding
import com.gh.gamecenter.feature.entity.ServerCalendarNotifySetting
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.gh.gamecenter.login.user.UserManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelbiz.SubscribeMessage
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

/**
 * 游戏开服-未知服详情弹窗
 */
class ServersCalendarDetailNoDataDialog : BottomSheetDialogFragment() {

    private val titleFormat = SimpleDateFormat("MM-dd", Locale.CHINA)

    private lateinit var detailViewBinding: DialogServersCalendearDetailBinding
    private lateinit var noDataViewBinding: LayoutServersCalendarDetailNoDataBinding

    private val parentViewModel by activityViewModels<ServersCalendarViewModel>()

    private lateinit var viewModel: ServersCalendarDetailNoDataViewModel

    private lateinit var wxApi: WXAPIProxyFactory.WXAPIProxy<SubscribeMessage.Req, SubscribeMessage.Resp>

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            window?.setWindowAnimations(com.gh.gamecenter.common.R.style.community_publication_animation)
            window?.setGravity(Gravity.BOTTOM)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        setStyle(DialogFragment.STYLE_NO_TITLE, com.gh.gamecenter.common.R.style.DialogWindowTransparent)
        Calendar.getInstance().apply {
            set(
                requireArguments().getInt(EntranceConsts.KEY_CALENDAR_YEAR, 0),
                requireArguments().getInt(EntranceConsts.KEY_CALENDAR_MONTH, 0) - 1,
                requireArguments().getInt(EntranceConsts.KEY_CALENDAR_DAY, 0),
                0, 0, 0
            )
            set(Calendar.MILLISECOND, 0)
            viewModel = viewModelProvider(ServersCalendarDetailNoDataViewModel.Factory(timeInMillis))
        }
        wxApi = WXAPIProxyFactory.createWXAPI(
            requireContext(),
            Config.WECHAT_APPID,
            object: WXAPIProxyFactory.WXHandler<SubscribeMessage.Req, SubscribeMessage.Resp> {
                private val reserved = System.currentTimeMillis().toString()

                override fun handleOnReq(req: SubscribeMessage.Req) {
                    req.reserved = reserved
                }

                override fun handleOnResp(resp: BaseResp): SubscribeMessage.Resp? {
                    if (resp is SubscribeMessage.Resp && reserved == resp.reserved) {
                        return resp
                    }
                    return null
                }
            }
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogServersCalendearDetailBinding.inflate(inflater, container, false)
            .also {
                detailViewBinding = it.apply {
                    content.layoutResource = R.layout.layout_servers_calendar_detail_no_data
                    noDataViewBinding = LayoutServersCalendarDetailNoDataBinding.bind(content.inflate())
                    content.layoutParams = content.layoutParams.apply {
                        height = LayoutParams.WRAP_CONTENT
                    }
                }
                it.container.layoutParams = it.container.layoutParams.apply {
                    height = LayoutParams.WRAP_CONTENT
                }
            }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        detailViewBinding.calendarHint.text = "${titleFormat.format(viewModel.serverTimeInMills)}详细开服"

        detailViewBinding.feedback.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        detailViewBinding.feedback.paint.isAntiAlias = true
        detailViewBinding.feedback.text = "意见反馈"
        detailViewBinding.feedback.setOnClickListener {
            HelpAndFeedbackBridge.startSuggestionActivity(
                it.context,
                SuggestType.GAME,
                null
            )
        }

        detailViewBinding.close.setOnClickListener {
            dismissAllowingStateLoss()
        }

        noDataViewBinding.appRemindCheckIv.setImageDrawable(DrawableView.getCheckSelectorDrawable(requireContext()))
        noDataViewBinding.wechatRemindCheckIv.setImageDrawable(DrawableView.getCheckSelectorDrawable(requireContext()))

        viewModel.getServerCalenderRemind(parentViewModel.game.id)
        viewModel.serverCalendarRemindLiveData.observe(viewLifecycleOwner) {
            bindNoDataView(it)
        }

        viewModel.wxSubscribeMsgConfigLiveData.observe(viewLifecycleOwner) {
            wxApi.sendReq(
                SubscribeMessage.Req().apply {
                    scene = it.scene
                    templateID = it.templateId
                    reserved = it.reserved
                }
            )
        }

        viewModel.error.observe(viewLifecycleOwner) {
            ToastUtils.showToast(getString(R.string.network_error_hint))
        }

        wxApi.liveData.observe(viewLifecycleOwner) {
            if (it.action == "confirm") {
                viewModel.addServerCalendarRemindWithWechat(
                    gameId = parentViewModel.game.id,
                    openId = it.openId,
                    templateId = it.templateID,
                    action = it.action,
                    reserved = UserManager.getInstance().userId,
                    scene = it.scene
                )
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if (reuse.type == Constants.LOGIN_TAG || reuse.type == Constants.LOGOUT_TAG) {
            viewModel.getServerCalenderRemind(parentViewModel.game.id)
        }
    }

    private fun bindNoDataView(notifySetting: ServerCalendarNotifySetting?) {
        viewModel.initData(notifySetting)
        noDataViewBinding.run {
            appRemindCheckIv.isChecked = viewModel.appRemind
            wechatRemindCheckIv.isChecked = viewModel.wechatRemind

            if (notifySetting != null) {
                appRemind.isEnabled = false
                appRemindCheckIv.alpha = 0.4F
                appRemind.setOnClickListener(null)

                wechatRemind.isEnabled = false
                wechatRemindCheckIv.alpha = 0.4F
                wechatRemind.setOnClickListener(null)

                addOrCancelRemind.text = getString(R.string.servers_detail_cancel_remind)
                addOrCancelRemind.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.bg_servers_detail_cancel_no_data)
                addOrCancelRemind.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        com.gh.gamecenter.common.R.color.text_secondary
                    )
                )
                addOrCancelRemind.setOnClickListener {
                    CheckLoginUtils.checkLogin(it.context, "游戏详情-开服日历表-未知服详情") {
                        viewModel.removeServerCalendarRemind(parentViewModel.game.id)
                        NewLogUtils.logLaunchServerReminderCancel(
                            gameId = parentViewModel.game.id,
                            gameName = parentViewModel.game.name ?: "",
                            reminderTime = viewModel.timeInSeconds,
                            reminderType = "未知服",
                            serverName = "",
                            launchServerTime = viewModel.timeInSeconds,
                            isApp = viewModel.appRemind,
                            isWechat = viewModel.wechatRemind
                        )
                        SensorsBridge.trackLaunchServerReminderCancelClick(
                            gameId = parentViewModel.game.id,
                            gameName = parentViewModel.game.name ?: "",
                            gameType = parentViewModel.game.categoryChinese,
                            reminderType = "未知服",
                        )
                    }
                }
            } else {
                appRemind.isEnabled = true
                appRemindCheckIv.alpha = 1.0F
                appRemind.setOnClickListener {
                    appRemindCheckIv.isChecked = !appRemindCheckIv.isChecked
                    viewModel.appRemind = appRemindCheckIv.isChecked
                    SPUtils.setBoolean(Constants.SP_SERVERS_CALENDAR_BY_APP, appRemindCheckIv.isChecked)
                }

                wechatRemind.isEnabled = true
                wechatRemindCheckIv.alpha = 1.0F
                wechatRemind.setOnClickListener {
                    wechatRemindCheckIv.isChecked = !wechatRemindCheckIv.isChecked
//                    viewModel.wechatRemind = wechatRemindCheckIv.isChecked
                    SPUtils.setBoolean(Constants.SP_SERVERS_CALENDAR_BY_WECHAT, wechatRemindCheckIv.isChecked)
                }

                addOrCancelRemind.text = getString(R.string.servers_detail_add_remind)
                addOrCancelRemind.setTextColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.white))
                addOrCancelRemind.background =
                    ContextCompat.getDrawable(requireContext(), com.gh.gamecenter.common.R.drawable.download_button_normal_style)
                addOrCancelRemind.setOnClickListener {
                    CheckLoginUtils.checkLogin(it.context, "游戏详情-开服日历表-未知服详情") {
                        if (!viewModel.wechatRemind && !viewModel.appRemind) {
                            ToastUtils.showToast(getString(R.string.servers_calendar_no_remind_checked_hint))
                            return@checkLogin
                        }

                        NewLogUtils.logLaunchServerReminderAdd(
                            gameId = parentViewModel.game.id,
                            gameName = parentViewModel.game.name ?: "",
                            reminderTime = viewModel.timeInSeconds,
                            reminderType = "未知服",
                            serverName = "",
                            launchServerTime = viewModel.timeInSeconds,
                            isApp = viewModel.appRemind,
                            isWechat = viewModel.wechatRemind
                        )
                        SensorsBridge.trackLaunchServerReminderClick(
                            gameId = parentViewModel.game.id,
                            gameName = parentViewModel.game.name ?: "",
                            gameType = parentViewModel.game.categoryChinese,
                            reminderType = "未知服",
                        )

                        if (viewModel.wechatRemind) {// 勾选微信订阅后需要微信授权一次性订阅消息
                            if (!wxApi.isWXAppInstalled) {
                                ToastUtils.showToast(getString(com.gh.gamecenter.core.R.string.wechat_not_install_toast))
                                return@checkLogin
                            }

                            viewModel.getWXSubscribeMsgConfig()
                        } else {
                            viewModel.addServerCalendarRemind(parentViewModel.game.id)
                        }
                    }
                }
            }
        }
    }
}