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

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
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.utils.*
import com.gh.gamecenter.common.utils.WXAPIProxyFactory.WXAPIProxy
import com.gh.gamecenter.common.utils.WXAPIProxyFactory.WXHandler
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.DialogServersDetailRemindBinding
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 java.text.SimpleDateFormat
import java.util.*

/**
 * 游戏开服-开服表详情-提醒详情弹窗
 */
class ServersCalendarDetailsRemindDialog : BottomSheetDialogFragment() {

    private lateinit var viewBinding: DialogServersDetailRemindBinding

    private lateinit var viewModel: ServersCalendarDetailsRemindViewModel

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

    private val parentViewModel by viewModels<ServersCalendarDetailViewModel>({
        parentFragment ?: this
    })

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())

    private val activityViewModel by activityViewModels<ServersCalendarViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, com.gh.gamecenter.common.R.style.DialogWindowTransparent)
        wxApi = WXAPIProxyFactory.createWXAPI(
            requireContext(),
            Config.WECHAT_APPID,
            object: 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
                }
            }
        )
        viewModel = viewModelProvider(
            ServersCalendarDetailsRemindViewModel.Factory(
                arguments?.getString(EntranceConsts.KEY_SERVER_CALENDAR_ID, "") ?: ""
            )
        )
        viewModel.initCalendarLiveData(parentViewModel.calendarEntityLiveData)
    }

    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 onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogServersDetailRemindBinding.inflate(inflater, container, false).also {
            viewBinding = it
        }.root
    }

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

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

        viewModel.serverCalendarEntityLiveData.observe(viewLifecycleOwner) { entity ->
            entity?.let {
                val serverName = if (it.getNote().isNullOrEmpty()) it.remark else it.getNote()

                viewModel.initData(it)

                viewBinding.serverName.text = serverName
                viewBinding.serverTime.text = dateFormat.format(viewModel.selectedNotifyTime)
                viewBinding.serverRemindTime.text = viewModel.selectedAdvancedTime.text

                viewBinding.appRemindCheckIv.isChecked = viewModel.appRemind
                viewBinding.wechatRemindCheckIv.isChecked = viewModel.wechatRemind

                val notifySetting = it.notifySetting
                if (notifySetting != null) {
                    viewBinding.serverTime.isEnabled = false
                    viewBinding.serverTime.setPadding(12F.dip2px(), 0, 0, 0)
                    viewBinding.serverTime.setDrawableEnd(null)
                    viewBinding.serverTime.background =
                        ContextCompat.getDrawable(requireContext(), R.drawable.bg_server_detail_remind_time_disabled)
                    viewBinding.serverTime.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.gh.gamecenter.common.R.color.text_tertiary
                        )
                    )

                    viewBinding.serverRemindTime.isEnabled = false
                    viewBinding.serverRemindTime.setPadding(12F.dip2px(), 0, 0, 0)
                    viewBinding.serverRemindTime.setDrawableEnd(null)
                    viewBinding.serverRemindTime.background =
                        ContextCompat.getDrawable(requireContext(), R.drawable.bg_server_detail_remind_time_disabled)
                    viewBinding.serverRemindTime.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.gh.gamecenter.common.R.color.text_tertiary
                        )
                    )

                    viewBinding.appRemindCheckIv.alpha = 0.4F
                    viewBinding.appRemind.isEnabled = false

                    viewBinding.wechatRemindCheckIv.alpha = 0.4F
                    viewBinding.wechatRemind.isEnabled = false

                    viewBinding.addOrCancelRemind.text = getString(R.string.servers_detail_cancel_remind)
                    viewBinding.addOrCancelRemind.background =
                        ContextCompat.getDrawable(requireContext(), R.drawable.bg_servers_detail_cancel_remind)
                    viewBinding.addOrCancelRemind.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.gh.gamecenter.common.R.color.text_secondary
                        )
                    )
                    viewBinding.addOrCancelRemind.setOnClickListener {
                        CheckLoginUtils.checkLogin(view.context, "游戏详情-开服日历表-已知服详情") {
                            NewLogUtils.logLaunchServerReminderCancel(
                                gameId = activityViewModel.game.id,
                                gameName = activityViewModel.game.name ?: "",
                                reminderTime = viewModel.selectedNotifySeconds - viewModel.selectedAdvancedTime.value,
                                reminderType = "已知服",
                                serverName = serverName ?: "",
                                launchServerTime = viewModel.selectedNotifySeconds,
                                isApp = viewModel.appRemind,
                                isWechat = viewModel.wechatRemind
                            )
                            SensorsBridge.trackLaunchServerReminderCancelClick(
                                gameId = activityViewModel.game.id,
                                gameName = activityViewModel.game.name ?: "",
                                gameType = activityViewModel.game.categoryChinese,
                                reminderType = "已知服"
                            )
                            viewModel.removeServerCalendarRemind(activityViewModel.game.id)
                        }
                    }
                } else {
                    viewBinding.serverTime.isEnabled = true
                    viewBinding.serverTime.setPadding(12F.dip2px(), 0, 12F.dip2px(), 0)
                    viewBinding.serverTime.background =
                        ContextCompat.getDrawable(requireContext(), R.drawable.bg_server_detail_remind_time)
                    viewBinding.serverTime.setDrawableEnd(R.drawable.ic_arrow_gray)
                    viewBinding.serverTime.setTextColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.text_secondary))

                    viewBinding.serverRemindTime.isEnabled = true
                    viewBinding.serverRemindTime.setPadding(12F.dip2px(), 0, 12F.dip2px(), 0)
                    viewBinding.serverRemindTime.background =
                        ContextCompat.getDrawable(requireContext(), R.drawable.bg_server_detail_remind_time)
                    viewBinding.serverRemindTime.setDrawableEnd(R.drawable.ic_arrow_gray)
                    viewBinding.serverRemindTime.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.gh.gamecenter.common.R.color.text_secondary
                        )
                    )

                    viewBinding.appRemindCheckIv.alpha = 1.0F
                    viewBinding.appRemind.isEnabled = true

                    viewBinding.wechatRemindCheckIv.alpha = 1.0F
                    viewBinding.wechatRemind.isEnabled = true

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

                            val selectedNotifyTime = viewModel.selectedNotifyTime
                            val selectedAdvancedTime = viewModel.selectedAdvancedTime.value
                            if (selectedNotifyTime - selectedAdvancedTime * 1000 < System.currentTimeMillis()) {
                                ToastUtils.showToast(getString(R.string.servers_calendar_remind_time_out_of_date))
                                return@checkLogin
                            }

                            NewLogUtils.logLaunchServerReminderAdd(
                                gameId = activityViewModel.game.id,
                                gameName = activityViewModel.game.name ?: "",
                                reminderTime = viewModel.selectedNotifySeconds - viewModel.selectedAdvancedTime.value,
                                reminderType = "已知服",
                                serverName = serverName ?: "",
                                launchServerTime = viewModel.selectedNotifySeconds,
                                isApp = viewModel.appRemind,
                                isWechat = viewModel.wechatRemind
                            )

                            SensorsBridge.trackLaunchServerReminderClick(
                                gameId = activityViewModel.game.id,
                                gameName = activityViewModel.game.name ?: "",
                                gameType = activityViewModel.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(activityViewModel.game.id)
                            }
                        }
                    }
                }
            }
        }

        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 = activityViewModel.game.id,
                    openId = it.openId,
                    templateId = it.templateID,
                    action = it.action,
                    reserved = UserManager.getInstance().userId,
                    scene = it.scene
                )
            }
        }

        viewBinding.close.setOnClickListener {
            dismissAllowingStateLoss()
        }

        viewBinding.serverTime.setOnClickListener {
            val entity = viewModel.serverCalendarEntityLiveData.value ?: return@setOnClickListener
            ServersCalendarTimeSettingDialog
                .create(viewModel.selectedNotifyTime, entity.getTime() * 1000) {
                    viewModel.selectedNotifyTime = it
                    viewBinding.serverTime.text = dateFormat.format(it)
                }
                .showNow(childFragmentManager, null)
        }

        viewBinding.serverRemindTime.setOnClickListener {
            ServersCalendarRemindTimeSettingDialog().also {
                it.setSelectCallback { time ->
                    viewModel.selectedAdvancedTime = time
                    viewBinding.serverRemindTime.text = time.text
                }
                it.showNow(childFragmentManager, null)
            }
        }

        viewBinding.appRemind.setOnClickListener {
            viewBinding.appRemindCheckIv.isChecked = !viewBinding.appRemindCheckIv.isChecked
            viewModel.appRemind = viewBinding.appRemindCheckIv.isChecked
            SPUtils.setBoolean(Constants.SP_SERVERS_CALENDAR_BY_APP, viewBinding.appRemindCheckIv.isChecked)
        }

        viewBinding.wechatRemind.setOnClickListener {
            viewBinding.wechatRemindCheckIv.isChecked = !viewBinding.wechatRemindCheckIv.isChecked
//            viewModel.wechatRemind = viewBinding.wechatRemindCheckIv.isChecked
            SPUtils.setBoolean(Constants.SP_SERVERS_CALENDAR_BY_WECHAT, viewBinding.wechatRemindCheckIv.isChecked)
        }

        viewModel.notifySettingChangeLiveData.observe(viewLifecycleOwner) {
            activityViewModel.dispatchNotifySettingChange(it.first, it.second)
        }
    }
}