package xn.xxp.main

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.Message
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import xn.xxp.main.msds.InstructionActivity
import com.kongzue.dialogx.dialogs.InputDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import core.ui.activity.BaseSignActivity
import core.ui.widget.SwipeAction
import core.ui.widget.SwipeTouchListener
import core.ui.widget.decoration.NoLastLineItemDecoration
import core.util.FastClickDelegate
import core.util.OnWeakListener
import core.util.WeakHandler
import http.client.ApiRepository
import http.vo.request.BannerImageReq
import http.vo.request.NoticeReq
import http.vo.response.BannerImageBean
import http.vo.response.CheckMachineVo
import http.vo.response.LaboratoryVo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import xn.xxp.R
import xn.xxp.app.LabApp
import xn.xxp.home.setting.SettingActivity
import xn.xxp.databinding.ActivityMainBinding
import xn.xxp.main.monitor.MonitorActivity
import xn.xxp.main.person.LaboratoryPersonActivity
import xn.xxp.main.risk.RiskListActivity
import xn.xxp.main.rule.RuleActivity
import xn.xxp.main.things.ThingsActivity
import xn.xxp.main.things.ThingsListActivity
import xn.xxp.mqtt.event.BannerEvent
import xn.xxp.mqtt.event.BulletinBoardEvent
import xn.xxp.mqtt.event.CheckMachineEvent
import xn.xxp.mqtt.event.WarningEvent
import xn.xxp.room.RoomTool
import xn.xxp.room.bean.LabConfig
import xn.xxp.room.bean.NoticeSummary
import xn.xxp.utils.QrTool
import xn.xxp.utils.Tool
import xn.xxp.widget.ITitleBar
import xn.xxp.widget.LooperLayoutManager
import xn.xxp.widget.NavViewCompat
import xn.xxp.widget.WaringDialog
import java.math.BigDecimal

/**
 * 首页
 *
 * @author ReiChin_
 */
class MainActivity :
    BaseSignActivity<ActivityMainBinding>(),
    OnWeakListener {

    companion object {
        // 文化图15s -> 整改信息30s -> 消息通知15s
        private const val BANNER_TIME_WORKBENCH = 15 * 1000L // 文化图15s
        private const val BANNER_TIME_REFORM_INFO = 30 * 1000L // 整改信息30s
        private const val BANNER_TIME_NOTICE_INFO = 15 * 1000L // 消息通知15s

        private const val WHAT_WORKBENCH = 1 // 实验室文化图
        private const val WHAT_REFORM_INFO = 2 // 整改信息
        private const val WHAT_NOTICE_INFO = 3 // 消息通知

        private const val LOAD_NET_WORKBENCH = true // 是否从网络上加载实验室文化图

        private const val SENSOR_SPLASH_TIME = 3000L // 传感器面板1.5s自动滚动
    }

    override fun createViewBinding() = ActivityMainBinding.inflate(layoutInflater)
    override fun getMTitleBar(): ITitleBar {
        return binding.titleBar
    }

    override fun getMNavView(): NavViewCompat? {
        return null
    }

    override fun enabledBackCountDown(): Boolean {
        return true
    }

    private val mBulletinBoardAdapter = MainBoardAdapter(R.layout.item_bulletin_board)

    private val mCheckMachineMsgAdapter = CheckMachineMsgAdapter(R.layout.item_check_machine_msg)
    private var mCheckMachineList: List<CheckMachineVo>? = null

    private var mBannerImageData: List<BannerImageBean>? = null

    private var mNoticeList: List<NoticeSummary>? = null

//    private val mSerialPortHelper by lazy {
//        SerialPortHelper(this, object : OnSerialScanListener {
//            override fun onServiceConnected() {
//                RcLog.info("MainActivity# isRelationGuard=${LabApp.sLabConfig?.isRelationGuard}")
//                if ("1" == LabApp.sLabConfig?.isRelationGuard) {
//                    // 有门禁，登录成功后自动开门
//                    RcLog.info("MainActivity# auto open door")
//                    handleOpenDoor()
//                }
//            }
//        })
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        mSerialPortHelper.bindService()

        // 实验室文化图 > 文化图
        val message = mBannerHandler.obtainMessage(WHAT_WORKBENCH)
        mBannerHandler.sendMessageDelayed(message, BANNER_TIME_WORKBENCH)
        EventBus.getDefault().register(this)
    }


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


    private val mBannerHandler by lazy { WeakHandler(this) }

    override fun onWeakHandleMessage(msg: Message) {
        when (msg.what) {
            // 实验室文化图
            WHAT_WORKBENCH -> handleWorkbench(msg)

            // 整改信息
            WHAT_REFORM_INFO -> handleReformInfo(msg)

            // 消息通知
            WHAT_NOTICE_INFO -> handleNoticeInfo(msg)
        }
    }

    private fun handleWorkbench(msg: Message) {
        val handler = msg.target
        binding.companyImg.visibility = View.VISIBLE
        binding.reformInfo.visibility = View.GONE
        binding.noticeInfo.visibility = View.GONE
        if (LOAD_NET_WORKBENCH) {
            // 显示文化图，并切换至下一张文化图
            if (!mBannerImageData.isNullOrEmpty()) {
                var index = msg.obj as? Int ?: 0
                showImage(index)

                index++
                if (index < mBannerImageData!!.size) {
                    val message = handler.obtainMessage(WHAT_WORKBENCH, index)
                    handler.sendMessageDelayed(message, BANNER_TIME_WORKBENCH)
                    return
                }
            } else {
                showDefaultImg()
            }
        }
        val message = if (mCheckMachineList.isNullOrEmpty()) {
            // 没有整改信息
            if (mNoticeList.isNullOrEmpty()) {
                // 没有消息通知，任然显示文化图
                handler.obtainMessage(WHAT_WORKBENCH)
            } else {
                // 有消息通知，显示消息通知
                handler.obtainMessage(WHAT_NOTICE_INFO)
            }
        } else {
            // 有整改信息，显示整改信息
            handler.obtainMessage(WHAT_REFORM_INFO)
        }
        handler.sendMessageDelayed(message, BANNER_TIME_WORKBENCH)
    }

    private fun handleReformInfo(msg: Message) {
        val handler = msg.target
        if (mCheckMachineList.isNullOrEmpty()) {
            // 没有整改信息
            if (mNoticeList.isNullOrEmpty()) {
                // 没有消息通知，任然显示文化图
                handler.obtainMessage(WHAT_WORKBENCH).sendToTarget()
            } else {
                // 有消息通知，显示消息通知
                handler.obtainMessage(WHAT_NOTICE_INFO).sendToTarget()
            }
            return
        }
        binding.companyImg.visibility = View.GONE
        binding.reformInfo.visibility = View.VISIBLE
        binding.noticeInfo.visibility = View.GONE

        val index = msg.obj as? Int ?: 0
        val newlyData = when {
            mCheckMachineList.isNullOrEmpty() -> null
            index >= mCheckMachineList!!.size - 1 -> mCheckMachineList!!.last()
            else -> mCheckMachineList!![index]
        }
        showReformInfo(newlyData)

        if (mCheckMachineList.isNullOrEmpty()) {
            // 没有整改信息
            if (mNoticeList.isNullOrEmpty()) {
                // 没有消息通知，任然显示文化图
                handler.obtainMessage(WHAT_WORKBENCH).sendToTarget()
            } else {
                // 有消息通知，显示消息通知
                handler.obtainMessage(WHAT_NOTICE_INFO).sendToTarget()
            }
            return
        } else {
            binding.reformPage.visibility = View.VISIBLE
            binding.reformPage.text = "${index + 1}/${mCheckMachineList!!.size}"
        }

        if (mCheckMachineList.isNullOrEmpty()) {
            // 没有整改信息
            if (mNoticeList.isNullOrEmpty()) {
                // 没有消息通知，任然显示文化图
                handler.obtainMessage(WHAT_WORKBENCH).sendToTarget()
            } else {
                // 有消息通知，显示消息通知
                handler.obtainMessage(WHAT_NOTICE_INFO).sendToTarget()
            }
        } else {
            val message = if (index >= mCheckMachineList!!.size - 1) {
                // 最后一条整改信息
                if (mNoticeList.isNullOrEmpty()) {
                    // 没有消息通知，切换到显示文化图
                    handler.obtainMessage(WHAT_WORKBENCH)
                } else {
                    // 有消息通知，切换到消息通
                    handler.obtainMessage(WHAT_NOTICE_INFO)
                }
            } else {
                handler.obtainMessage(WHAT_REFORM_INFO, index + 1)
            }
            handler.sendMessageDelayed(message, BANNER_TIME_REFORM_INFO)
        }
    }

    private fun handleNoticeInfo(msg: Message) {
        val handler = msg.target
        if (mNoticeList.isNullOrEmpty()) {
            // 没有消息通知，显示文化图
            handler.obtainMessage(WHAT_WORKBENCH).sendToTarget()
            return
        }
        binding.companyImg.visibility = View.GONE
        binding.reformInfo.visibility = View.GONE
        binding.noticeInfo.visibility = View.VISIBLE

        val index = msg.obj as? Int ?: 0
        val newlyData = when {
            mNoticeList.isNullOrEmpty() -> null
            index >= mNoticeList!!.size - 1 -> mNoticeList!!.last()
            else -> mNoticeList!![index]
        }
        showNoticeInfo(newlyData)
        if (mNoticeList.isNullOrEmpty()) {
            // 没有消息通知，显示文化图
            handler.obtainMessage(WHAT_WORKBENCH).sendToTarget()
            return
        } else {
            binding.noticePage.visibility = View.VISIBLE
            binding.noticePage.text = "${index + 1}/${mNoticeList!!.size}"
        }

        if (mNoticeList.isNullOrEmpty()) {
            // 没有消息通知，显示文化图
            handler.obtainMessage(WHAT_WORKBENCH).sendToTarget()
        } else {
            val message = if (index >= mNoticeList!!.size - 1) {
                // 最后一条整改信息
                handler.obtainMessage(WHAT_WORKBENCH)
            } else {
                handler.obtainMessage(WHAT_NOTICE_INFO, index + 1)
            }
            handler.sendMessageDelayed(message, BANNER_TIME_NOTICE_INFO)
        }
    }

    private fun showNoticeInfo(data: NoticeSummary?) {
        // 显示通知信息：通知发布人，发布时间，通知内容
        binding.issuePerson.text = data?.userName
        binding.issueTime.text = data?.sendTime
        binding.noticeContent.text = data?.content
    }

    @SuppressLint("SetTextI18n")
    private fun showReformInfo(data: CheckMachineVo?) {
        mCheckMachineMsgAdapter.setNewInstance(data?.detailList)
        binding.nestedScrollView.fullScroll(View.FOCUS_UP)
        if (data?.details.isNullOrEmpty()) {
            mCheckMachineMsgAdapter.setEmptyView(R.layout.view_list_empty)
        }
        binding.createTime.text = "检查时间：${data?.createTime ?: ""}"
        binding.jcRyxm.text = "检查人：${data?.jcRyxm ?: ""}"
    }

    override fun initListener() {
        binding.titleBar.setTitleInfoFromSp()
        binding.titleBar.setOnLongClickListener {
            if (AppUtils.isAppDebug()) {
                val intent = Intent(this, SettingActivity::class.java)
                startActivity(intent)
            } else {
                InputDialog.show("Tips", "请输入密码", "确认")
                    .setOkButtonClickListener { dialog: MessageDialog, v1: View? ->
                        val inputText = dialog.inputText
                        if ("admin@098&" == inputText || inputText == deviceConfig.adminPas) {
                            ActivityUtils.startActivity(SettingActivity::class.java)
                        } else {
                            showToast("密码错误")
                        }
                        false
                    }.show()
            }

            true
        }
        // 视频监控
        binding.monitor.setOnClickListener(FastClickDelegate {
            val intent = Intent(this, MonitorActivity::class.java)
            startActivity(intent)
        })
        // 人员信息(老师)/实验人员(学生)
        binding.labPerson.setOnClickListener(FastClickDelegate {
            val intent = Intent(this, LaboratoryPersonActivity::class.java)
            startActivity(intent)
        })
        // 规章制度
        binding.safetyRegulation.setOnClickListener(FastClickDelegate {
            val intent = Intent(this, RuleActivity::class.java)
            startActivity(intent)
        })
        // MSDS
        binding.learnMaterial.setOnClickListener(FastClickDelegate {
            val intent = Intent(this, InstructionActivity::class.java)
            startActivity(intent)
        })
        // 危险源
        binding.sourceOfRisk.setOnClickListener(FastClickDelegate {
            val intent = Intent(this, RiskListActivity::class.java)
            startActivity(intent)
        })
        // 物联控制
        binding.things.setOnClickListener(FastClickDelegate {
            val intent = Intent(this, ThingsListActivity::class.java)
            startActivity(intent)
        })
        // 签到
        binding.signIn.setOnClickListener(FastClickDelegate {
            dispatchSignIn()
        })
        // 离开
        binding.leave.setOnClickListener(FastClickDelegate {
            dispatchSignOut()
        })
        // 开门
        binding.openDoor.setOnClickListener(FastClickDelegate {
            Tool.INSTANCE.openDoor()
        })
        // 返回
        binding.back.setOnClickListener(FastClickDelegate {
            logoutCountDownFinish()
        })

        binding.bulletinBoardView.layoutManager = LooperLayoutManager(RecyclerView.HORIZONTAL)
        val decor = NoLastLineItemDecoration(this, DividerItemDecoration.HORIZONTAL)
        decor.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_item_divider_middle)!!)
        binding.bulletinBoardView.addItemDecoration(decor)
        binding.bulletinBoardView.adapter = mBulletinBoardAdapter

        binding.reformRecyclerView.layoutManager = LinearLayoutManager(this)
        binding.reformRecyclerView.isNestedScrollingEnabled = false
        binding.reformRecyclerView.adapter = mCheckMachineMsgAdapter

        binding.noticeContent.setOnTouchListener(SwipeTouchListener(this) { action ->
            switchNoticeContent(action)
        })
    }

    private fun switchNoticeContent(action: SwipeAction) {
        if (mNoticeList.isNullOrEmpty()) return

        val index = BigDecimal(binding.noticePage.text.split("/")[0]).toInt()
        when (action) {
            SwipeAction.PREV -> switchNoticePrev(index)
            SwipeAction.NEXT -> switchNoticeNext(index)
        }
    }

    private fun switchNoticePrev(index: Int) {
        if (index > 1) {
            mBannerHandler.removeMessages(WHAT_NOTICE_INFO)
            val message = mBannerHandler.obtainMessage(WHAT_NOTICE_INFO, index - 2)
            handleNoticeInfo(message)
        }
    }

    private fun switchNoticeNext(index: Int) {
        if (index < mNoticeList!!.size) {
            mBannerHandler.removeMessages(WHAT_NOTICE_INFO)
            val message = mBannerHandler.obtainMessage(WHAT_NOTICE_INFO, index)
            handleNoticeInfo(message)
        }
    }

    lateinit var labConfig: LabConfig
    override fun initData() {
        Tool.INSTANCE.openDoor()
        labConfig = RoomTool.getInstance().labConfigDao().labConfig
        val laboratoryVo = LabApp.laboratory
        if (null == laboratoryVo || null == labConfig) {
            showToast("暂无实验室信息，即将重新获取")
            Tool.INSTANCE.reStartApp("暂无实验室信息，即将重新获取")
            return
        }
        binding.titleBar.setTitleInfoFromSp()

        initLaboratoryInfo(laboratoryVo)
        // 开门按钮显示控制
        if ("1" == labConfig.isRelationGuard) {
            binding.openDoor.visibility = View.VISIBLE
            val drawable =
                ContextCompat.getDrawable(this, R.drawable.divider_transparent_main_right)
            binding.rightContent.dividerDrawable = drawable
        } else {
            binding.openDoor.visibility = View.GONE
            val drawable =
                ContextCompat.getDrawable(this, R.drawable.divider_transparent_main_right_v2)
            binding.rightContent.dividerDrawable = drawable
        }
        // 视频监控按钮显示控制
        if ("1" == LabApp.userVo.pageType) {
            binding.monitorGroup.visibility = View.VISIBLE
        } else {
            binding.monitorGroup.visibility = View.GONE
        }

        if (LOAD_NET_WORKBENCH) {
            queryBanner()
        }

        queryBulletinBoard()
        queryCheckMachineMsgList()
        queryNoticeMsgList()
    }

    private fun queryBanner() {
        val param = BannerImageReq().apply {
            imgCategory = "2"
            pcType = "0"
        }
        val disposable = ApiRepository.bannerImages(param)
            .subscribe({
                preloadImage(it)
            }, {
                showDefaultImg()
            })
        addDisposable(disposable)
    }

    private val mBannerMap: MutableMap<Int, Boolean> = mutableMapOf()

    private fun preloadImage(data: List<BannerImageBean>?) {
        this.mBannerImageData = data
        this.mBannerMap.clear()
        if (data.isNullOrEmpty()) {
            showDefaultImg()
            return
        }
        // TODO
        data.forEachIndexed { index, item ->
            Glide.with(this)
                .load(item.imgUrl)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>,
                        isFirstResource: Boolean
                    ): Boolean {
                        mBannerMap[index] = false
                        showImage(0)
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable,
                        model: Any,
                        target: Target<Drawable>?,
                        dataSource: DataSource,
                        isFirstResource: Boolean
                    ): Boolean {
                        mBannerMap[index] = true
                        showImage(0)
                        return false
                    }
                })
                .preload()
        }
    }

    private fun showImage(index: Int) {
        if (mBannerImageData.isNullOrEmpty()
            || mBannerImageData!!.size != mBannerMap.size
        ) {
            showDefaultImg()
            return
        }

        val activeIndex = index % mBannerImageData!!.size
        if (true == mBannerMap[activeIndex]) {
            Glide.with(this)
                .load(mBannerImageData!![activeIndex].imgUrl)
                .into(binding.companyImg)
        } else {
            showDefaultImg()
        }
    }

    private fun showDefaultImg() {
        binding.companyImg.setImageResource(R.mipmap.img_sy_qywh)
    }

    private fun initLaboratoryInfo(laboratoryVo: LaboratoryVo) {
        val dangerColor = try {
            Color.parseColor(laboratoryVo.dangerColor)
        } catch (e: Exception) {
            Color.parseColor("#15CA48")
        }
        val bgDrawable = GradientDrawable()
        bgDrawable.cornerRadius = Tool.INSTANCE.dip2px(0.5f).toFloat()
        bgDrawable.setStroke(Tool.INSTANCE.dip2px(1.0f), dangerColor)

        binding.labLevel.background = bgDrawable
        binding.labLevel.setTextColor(dangerColor)
        binding.labLevel.text =
            "${laboratoryVo.dangerName ?: ""}\n${laboratoryVo.dangerLevel ?: ""}"

        binding.labName.text = laboratoryVo.address

        // 二维码
        GlobalScope.launch(Dispatchers.Main) {
            val bitmap = withContext(Dispatchers.IO) {
                QrTool.generateQRCode(laboratoryVo.qrCodeUrl, Tool.INSTANCE.dip2px(150f))
            }
            Glide.with(this@MainActivity)
                .asBitmap()
                .load(bitmap)
                .error(R.mipmap.img_error)
                .into(binding.qrCode)
        }
    }

    private fun queryBulletinBoard() {
        showLoading("加载中...")
        val disposable = ApiRepository.functionList(labConfig.labId.toString())
            .subscribe({ data ->
                dismissLoading()
                mBulletinBoardAdapter.setNewInstance(data.toMutableList())
                binding.bulletinBoardView.initTimer(4, data.size)
                binding.bulletinBoardView.startAuto(SENSOR_SPLASH_TIME)
                if (data.isNullOrEmpty()) {
                    mBulletinBoardAdapter.setEmptyView(R.layout.view_list_empty)
                }

                queryWarning()
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
                mBulletinBoardAdapter.setEmptyView(R.layout.view_list_empty)
            })
        addDisposable(disposable)
    }

    private fun queryWarning() {
        val disposable = ApiRepository.warnList(labConfig.labId.toString())
            .subscribe({ data ->
                mBulletinBoardAdapter.updateWaringValue(data)
            }, { throwable ->
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun queryCheckMachineMsgList() {
        // TODO ReiChin_ 功能隐藏，暂不对接
//        val disposable = ApiRepository.checkMachineMsgList(LabApp.sLabConfig!!.labId)
//            .subscribe({ response ->
//                mCheckMachineList = response
//                if (mCheckMachineList.isNullOrEmpty()) {
//                    mCheckMachineMsgAdapter.setNewInstance(null)
//                    mCheckMachineMsgAdapter.setEmptyView(R.layout.view_list_empty)
//                    binding.reformPage.visibility = View.GONE
//                } else {
//                    showReformInfo(mCheckMachineList!![0])
//                    binding.reformPage.visibility = View.VISIBLE
//                    binding.reformPage.text = "1/${mCheckMachineList!!.size}"
//                }
//            }, { throwable ->
//                mCheckMachineList = null
//                throwable.printStackTrace()
//                showNetError(throwable)
//                mCheckMachineMsgAdapter.setEmptyView(R.layout.view_list_empty)
//                binding.reformPage.visibility = View.GONE
//            })
//        addDisposable(disposable)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCheckMachineEvent(event: CheckMachineEvent) {
        queryCheckMachineMsgList()
    }

    private fun queryNoticeMsgList() {
        val param = NoticeReq().apply {
            businessTypeList.let {
                it.add(0)
                it.add(1)
                it.add(13)
            }
            subIds = labConfig.labId.toString()
            page = 1
            pageSize = 100
        }
        val disposable = ApiRepository.newMsgGroup(param)
            .subscribe({ response ->
                RoomTool.getInstance().noticeSummaryDao()
                    .insert(*response.toTypedArray<NoticeSummary>())
                mNoticeList = response
                if (mNoticeList.isNullOrEmpty()) {
                    showNoticeInfo(null)
                    binding.noticePage.visibility = View.GONE
                } else {
                    showNoticeInfo(mNoticeList!![0])
                    binding.noticePage.visibility = View.VISIBLE
                    binding.noticePage.text = "1/${mNoticeList!!.size}"
                }
            }, { throwable ->
                mNoticeList = null
                throwable.printStackTrace()
                showNetError(throwable)
                showNoticeInfo(null)
                binding.noticePage.visibility = View.GONE
            })
        addDisposable(disposable)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBannerEvent(event: BannerEvent) {
        if (LOAD_NET_WORKBENCH) {
            queryBanner()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBulletinBoardEvent(event: BulletinBoardEvent) {
        mBulletinBoardAdapter.updateSensorValue(event.data)
    }

    private var mWaringDialog: WaringDialog? = null

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWarningEvent(event: WarningEvent) {
        if (null == mWaringDialog) {
            if (!event.data.isNullOrEmpty()) {
                mWaringDialog = WaringDialog(this, event.data).apply {
                    setOnDismissListener {
                        mWaringDialog = null
                    }
                }
                mWaringDialog!!.show()
            }
        } else {
            if (event.data.isNullOrEmpty()) {
                mWaringDialog!!.dismiss()
            } else {
                mWaringDialog!!.updateWaringValue(event.data)
            }
        }

        mBulletinBoardAdapter.updateWaringValue(event.data)
    }

}
