package com.wdkl.app.ncs.callingbed.activity

//import com.wdkl.app.ncs.callingbed.sip.SipHelper
//import com.wdkl.app.ncs.callingbed.sip.SipStatus
//import com.vvsip.ansip.IVvsipServiceListener
//import com.vvsip.ansip.VvsipCall
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.*
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import com.alibaba.fastjson.JSONObject
import com.enation.javashop.android.jrouter.external.annotation.Router
import com.enation.javashop.net.engine.model.NetState
import com.google.gson.Gson
import com.wdkl.app.ncs.callingbed.BuildConfig
import com.wdkl.app.ncs.callingbed.R
import com.wdkl.app.ncs.callingbed.adapter.NurseConfigAdpter
import com.wdkl.app.ncs.callingbed.agreement.CallingbedAgreement
import com.wdkl.app.ncs.callingbed.databinding.CallingbedMainLayBinding
import com.wdkl.app.ncs.callingbed.fragment.CostFragment
import com.wdkl.app.ncs.callingbed.fragment.MainFragment
import com.wdkl.app.ncs.callingbed.fragment.QrCodeFragment
import com.wdkl.app.ncs.callingbed.fragment.SkyCallFragment
import com.wdkl.app.ncs.callingbed.helper.*
import com.wdkl.app.ncs.callingbed.launch.CallingbedLaunch
import com.wdkl.app.ncs.callingbed.settings.SettingConfig
import com.wdkl.ncs.android.lib.base.BaseActivity
import com.wdkl.ncs.android.lib.base.BaseApplication
import com.wdkl.ncs.android.lib.utils.AppTool
import com.wdkl.ncs.android.lib.utils.TimeHandle
import com.wdkl.ncs.android.lib.utils.push
import com.wdkl.ncs.android.lib.utils.showMessage
import com.wdkl.ncs.android.lib.vo.filter
import com.wdkl.ncs.android.middleware.common.Constant
import com.wdkl.ncs.android.middleware.common.MessageEvent
import com.wdkl.ncs.android.middleware.common.SipStatus
import com.wdkl.ncs.android.middleware.logic.contract.callingbed.CallingbedActivityContract
import com.wdkl.ncs.android.middleware.logic.presenter.callingbed.CallingbedActivityPresenter
import com.wdkl.ncs.android.middleware.model.ServerInfo
import com.wdkl.ncs.android.middleware.model.ThirdServerInfo
import com.wdkl.ncs.android.middleware.model.dos.AppVersionDO
import com.wdkl.ncs.android.middleware.model.dos.DeviceDO
import com.wdkl.ncs.android.middleware.model.dos.PartSettingDO
import com.wdkl.ncs.android.middleware.model.dto.NurseConfigDto
import com.wdkl.ncs.android.middleware.model.dto.TcpSeverDTO
import com.wdkl.ncs.android.middleware.model.vo.BedDeviceInfoVO
import com.wdkl.ncs.android.middleware.model.vo.InteractionVO
import com.wdkl.ncs.android.middleware.tcp.TcpClient
import com.wdkl.ncs.android.middleware.tcp.channel.OtherUtil
import com.wdkl.ncs.android.middleware.tcp.channel.VoiceUtil
import com.wdkl.ncs.android.middleware.tcp.dto.TcpModel
import com.wdkl.ncs.android.middleware.tcp.enums.TcpAction
import com.wdkl.ncs.android.middleware.tcp.enums.TcpType
import com.wdkl.ncs.android.middleware.udp.ServerInfoUtil
import com.wdkl.ncs.android.middleware.utils.CommonUtils
import com.wdkl.ncs.android.middleware.utils.StringUtil
import com.wdkl.ncs.janus.util.JanusConstant
import kotlinx.android.synthetic.main.callingbed_main_lay.*
import kotlinx.android.synthetic.main.view_title_layout.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import serialporttest.utils.SerialPortUtil
import java.io.*
import java.lang.Process
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit


/**
 * CallingbedActivity :BaseActivity<CallingbedActivityPresenter, Callingbed2MainLayBinding>
 *     CallingbedActivityPresenter: 位置com.wdkl.ncs.android.middleware.logic.presenter.callingbed
 *     CallingbedMainLayBinding: 位置callingbed_main_lay.xml,需要添加<layout>..</layout>标签
 *     CallingbedActivityContract: 位置com.wdkl.ncs.android.middleware.logic.contract.callingbed
 */

@Router(path = "/callingbed/main")
class CallingbedActivity :BaseActivity<CallingbedActivityPresenter, CallingbedMainLayBinding>(), CallingbedAgreement, CallingbedActivityContract.View, /*IVvsipServiceListener,*/
        SerialPortUtil.ISerialPortBedOnclickEvent, SerialPortUtil.ISerialPortBedOnclickString {
    val TAG = CallingbedActivity::class.java.getSimpleName()

    private lateinit var receiver: TimeReceiver
    private lateinit var curFragment: String

    private var isTimeWorking = true
    private lateinit var timeThread: TimeThread
    //一定时间无操作返回主界面
    private var backTimeout = 0

    private lateinit var linearLayout : LinearLayoutManager
    private lateinit var nurseConfigAdpter : NurseConfigAdpter
    private var configList = ArrayList<NurseConfigDto>()
    private var sipServiceRunning :Boolean = false
    private var initialized :Boolean = false
    private var updating :Boolean = false
    private var hasNurseValue :Boolean = false
    private var tcpConnect: Boolean = false
    private var loaded: Boolean = false

    //通话界面fragment
    private var skyCallFragment: Fragment? = null

    //网络异常计数
    private var netErrCount : Int = 0
    private var clickSosTime : Long = 0
    private var pressTime : Long = 0

    private var serverSuccess = false

    //主信息
    private val mainFragment = "main_fragment"
    //医嘱
    //private val doctorFragment = "doctor_fragment"
    //费用
    private val costFragment = "cost_fragment"
    //二维码
    private val qrCodeFragment = "qrcode_fragment"
    //请求增援
    //private val supportFragment = "support_fragment"
    //呼叫护工
    //private val callCareFragment = "call_care_fragment"
    //呼叫护士
    //private val callNurseFragment = "call_nurse_fragment"

    private val uninstallApk = false
    private var copyDone = false

    companion object {
        private const val TIME_WHAT = 1000
    }

    override fun getLayId(): Int {
        return R.layout.callingbed_main_lay;
    }

    override fun bindDagger() {
        CallingbedLaunch.component.inject(this)
    }

    override fun init() {
        //开始ping网络，30秒ping一次
        //NetHelper.startNetCheck()

        //获取mac地址
        Constant.LOCAL_MAC = NetHelper.getInstance().macAddress

        //presenter.loadTcpServerHost()

        //sip初始化
        //initSip()

        //注册广播
        regReceiver()
        //串口监听
        setSerialListener()
        //音频初始化
        SoundPoolHelper.getInstance().init(applicationContext)

        AppTool.Time.delay(1500) {
            //打开手柄mic
            SerialPortHelper.setHandsMIC(true)
            SerialPortHelper.setSosLight("0")
            //初始化灭掉护理灯
            SerialPortHelper.dismissNurseLedLight()
            //默认门灯白色
            SerialPortHelper.setDoorLight(1, "111")
        }

        EventBus.getDefault().register(this)

        initNurseConfig()
        updateNetState()

        //启动时间线程
        timeThread = TimeThread()
        timeThread.start()

        //启动主fragment
        //switchToMainFragment()

        //先显示二维码界面，若设备已注册并启用了再切换到主界面
        hideRightMenu(false)
        switchToFragment(R.id.callingbed_main_frame, QrCodeFragment(), qrCodeFragment)

        //打开网络调试
        AppTool.Time.delay(120000) {
            openNetwrokDebug()
        }

        //卸载原来二代系统床头分机apk
        if (uninstallApk) {
            //卸载老的5寸分机app
            Thread {
                if (checkAppExist()) {
                    uninstallApp()
                }
            }.start()
        }

        checkServer()

        if ("rk3128".equals(Build.MODEL)) {
            checkLaunch()
        }
    }

    //检查launch版本
    private fun checkLaunch() {
        Log.d(TAG, "start check launch")
        val pm = packageManager
        val packageInfo = pm.getInstalledPackages(0)
        var launchExist = false
        for (pInfo in packageInfo) {
            val launchName = "com.wdkl.launch"
            val launchVersion = "1.3"
            if (launchName == pInfo.packageName) {
                launchExist = true
                Log.d(TAG, "start check launch app: " + pInfo.versionName)
                if (launchVersion != pInfo.versionName) {
                    Log.d(TAG, "need update launch, app name: " + pInfo.packageName + ", app version: " + pInfo.versionName)
                    updateLaunchApk()
                }
            }
        }
        Log.d(TAG, "launch app exist: $launchExist")
    }

    private fun updateLaunchApk() {
        Thread {
            val apkName = "launch.apk"
            copyAssetsToDst(applicationContext, apkName, Environment.getExternalStorageDirectory().path + "/" + Environment.DIRECTORY_DOWNLOADS)
            if (copyDone) {
                val fileName = Environment.getExternalStorageDirectory().path + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + apkName
                //升级
                AppUpdateHelper.rootSilenceInstall(fileName)
                //5分钟后重启设备
                AppTool.Time.delay(300000) {
                    AppUpdateHelper.reboot(BaseApplication.appContext)
                }
            }
        }.start()
    }

    //拷贝assets下面的文件到sd卡
    private fun copyAssetsToDst(context: Context, fileName: String, dstPath: String) {
        try {
            copyDone = false
            val file = File(dstPath)
            if (!file.exists()) {
                file.mkdirs()
            }
            val outFile = File("$dstPath/$fileName")
            val `is` = context.assets.open(fileName)
            val fos = FileOutputStream(outFile)
            val buffer = ByteArray(1024)
            var byteCount: Int
            while (`is`.read(buffer).also { byteCount = it } != -1) {
                fos.write(buffer, 0, byteCount)
            }
            fos.flush()
            `is`.close()
            fos.close()
            copyDone = true
        } catch (e: java.lang.Exception) {
            copyDone = false
            e.printStackTrace()
        }
    }


    private fun checkServer() {
        Thread {
            while (!serverSuccess) {
                val okHttpClient = OkHttpClient().newBuilder()
                    .connectTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
                    .readTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
                    .writeTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
                    .build()
                val url: String = CommonUtils.getUrl(BaseApplication.appContext)
                val port: String = CommonUtils.getUrlPort(BaseApplication.appContext)
                val request = Request.Builder()
                    .url("http://$url:$port/ncs_url/server_info")
                    .get()
                    .build()

                Log.d(TAG, "start checkServer: $url:$port")
                try {
                    val response = okHttpClient.newCall(request).execute()
                    if (response != null && response.isSuccessful) {
                        Log.d(TAG, "checkServer response success")
                        //接口数据获取成功
                        serverSuccess = true
                        presenter.loadServerInfo()
                    } else {
                        Log.e(TAG, "checkServer response fail")
                        //接口数据获取失败，可能服务器ip不对，尝试重新获取服务器ip
                        val info = ServerInfoUtil.get(Constant.LOCAL_MAC)
                        checkServerInfo(info)
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "checkServer exception: ")
                    e.printStackTrace()
                    //接口数据获取失败，可能服务器ip不对，尝试重新获取服务器ip
                    val info = ServerInfoUtil.get(Constant.LOCAL_MAC)
                    checkServerInfo(info)
                }

                try {
                    Thread.sleep(30000)
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
            }
        }.start()
    }

    private fun checkServerInfo(info: ThirdServerInfo?) {
        //检查获取到的服务器ip是否可用，可用则重启app重新初始化，不可用则什么都不做，等待下次重新获取服务器ip
        if (info != null) {
            if (info.thirdServer == null || info.thirdServerPort == null) {
                Log.d(TAG, "server info data null")
                showMsgMain("get server data null")
            } else {
                val okHttpClient = OkHttpClient().newBuilder()
                    .connectTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
                    .readTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
                    .writeTimeout(15 * 1000L, TimeUnit.MILLISECONDS)
                    .build()
                val request = Request.Builder()
                    .url("http://${info.thirdServer}:${info.thirdServerPort}/ncs_url/server_info")
                    .get()
                    .build()

                try {
                    val response = okHttpClient.newCall(request).execute()
                    if (response != null && response.isSuccessful) {
                        //接口数据获取成功，稍后重启app
                        serverSuccess = true
                        CommonUtils.setUrl(activity, info.thirdServer)
                        CommonUtils.setUrlPort(activity, info.thirdServerPort.toString())
                        showMsgMain("restart...")
                        handler.postDelayed({
                            AppUpdateHelper.restartApp(activity)
                        }, 10000)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    showMsgMain("server error or net error")
                }
            }
        } else {
            Log.d(TAG, "server info null")
            showMsgMain("get server null")
        }
    }

    private fun showMsgMain(msg: String) {
        runOnUiThread {
            showMessage(msg)
        }
    }

    //开启网络调试
    private fun openNetwrokDebug() {
        val commands = arrayListOf(
            "/system/bin/sh",
            "setprop service.adb.tcp.port 5555",
            "stop adbd",
            "start adbd"
        )
        try {
            RunAsRoot(commands)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


    private fun RunAsRoot(cmds: ArrayList<String>) {
        val p = Runtime.getRuntime().exec("su")
        val os = DataOutputStream(p.outputStream)
        for (tmpCmd in cmds) {
            os.writeBytes(
                """
            $tmpCmd
            
            """.trimIndent()
            )
        }
        os.writeBytes("exit\n")
        os.flush()
    }

    private fun checkAppExist() : Boolean {
        val packageInfo = packageManager.getInstalledPackages(0)
        var appExist = false
        for (pInfo in packageInfo) {
            val appName = "com.wdkl.callingbed"
            if (appName == pInfo.packageName) {
                appExist = true
                break
            }
        }
        Log.e("callingbed", "callingbed app exist: " + appExist)
        return appExist
    }

    private fun uninstallApp() {
        val process: Process
        val printWriter: PrintWriter
        try {
            process = Runtime.getRuntime().exec("su")
            printWriter = PrintWriter(process.outputStream)
            printWriter.println("pm uninstall com.wdkl.callingbed")
            printWriter.flush()
            printWriter.close()
            Log.e("uninstall", "uninstall end")
        } catch (e: java.lang.Exception) {
            Log.e("uninstall", "uninstall e:" + e.message)
        }
    }

    override fun bindEvent() {
    }

    override fun destory() {
        SerialPortUtil.getInstance().closeHeart()
        SerialPortUtil.getInstance().closeSerialPort()
        //SipHelper.getInstance().unRegisterSip()
        SoundPoolHelper.getInstance().release()
        EventBus.getDefault().unregister(this)
        unRegReceiver()
        handler.removeCallbacksAndMessages(null)
        isTimeWorking = false
    }

    fun initDevice() {
        if (!TextUtils.isEmpty(Constant.LOCAL_MAC)) {
            presenter.loadDeviceInfo(Constant.LOCAL_MAC)
        }
    }

    private fun initNurseConfig() {
        //初始化默认护理项
        for (index in 1..5) {
            var item = NurseConfigDto()
            item.nurseConfigName = StringUtil.getResString(R.string.default_nurse_config_name)
            item.nurseOptionName = StringUtil.getResString(R.string.str_empty)
            item.nurseColorRbg = "2F9DF1"
            configList.add(item)
        }

        linearLayout = LinearLayoutManager(activity)
        nurseConfigAdpter = NurseConfigAdpter(activity, configList)
        rv_left_list.layoutManager = linearLayout
        rv_left_list.adapter = nurseConfigAdpter
    }

    //数据加载错误
    override fun onError(message: String, type: Int) {
        //dismissDialog()
        showMessage(message)
        //加载失败，重置customid
        //Constant.CUSTOM_ID = -1
    }

    //数据加载完成
    override fun complete(message: String, type: Int) {
        //dismissDialog()

    }

    //开始获取数据
    override fun start() {
        //showDialog()
    }

    //没有网络
    override fun onNoNet() {
        showMessage("No network")
        //加载失败，重置customid
        //Constant.CUSTOM_ID = -1
    }

    //网络监听
    override fun networkMonitor(state: NetState) {
        state.filter(onMobile = {

        },onWifi = {

        },offline = {

        })
    }

    override fun setTcpServerHost(tcpSeverDTO: TcpSeverDTO) {
        /*if (loaded) {
            return
        }
        loaded = true

        Constant.TCP_SERVER_URL = tcpSeverDTO.localIp
        Constant.TCP_PORT = tcpSeverDTO.tcpPort
        Constant.TCP_HEART_BEAT = tcpSeverDTO.readerIdleTime

        //开启TCP连接
        startTcp()
        showMessage("tcp开始连接...host: " + Constant.TCP_SERVER_URL + ", port: " + Constant.TCP_PORT)

        Thread(Runnable {
            while (!initialized) {
                runOnUiThread(Runnable {
                    initDevice()
                })
                try {
                    Thread.sleep(15000)
                } catch (e: Exception) {
                    //
                }
            }
        }).start()*/
    }

    override fun setServerInfo(data: ServerInfo) {
        if (loaded) {
            return
        }
        loaded = true

        Constant.TCP_SERVER_URL = data.tcpLocalIp
        Constant.TCP_PORT = data.tcpPort
        Constant.TCP_HEART_BEAT = data.tcpIdleSeconds

        JanusConstant.JANUS_URL = "ws://" + data.rtcLocalIp + ":" + data.rtcPort
        JanusConstant.STUN_SERVER = arrayOf<String>(data.stunServer)
        //JanusConstant.TURN_SERVER = data.turnServer

        var needReboot = false
        if ("cn".equals(data.lang)) {
            //中文
            if (SettingConfig.getLanguageId(activity) != 2) {
                needReboot = true
            }
            SettingConfig.setLanguageId(activity, 2)
        } else if ("en".equals(data.lang)) {
            //英文
            if (SettingConfig.getLanguageId(activity) != 1) {
                needReboot = true
            }
            SettingConfig.setLanguageId(activity, 1)
        } else if ("es".equals(data.lang)) {
            //西班牙语
            if (SettingConfig.getLanguageId(activity) != 3) {
                needReboot = true
            }
            SettingConfig.setLanguageId(activity, 3)
        }

        if (needReboot) {
            AppTool.Time.delay(5000) {
                AppUpdateHelper.restartApp(activity)
            }
        }

        //开启TCP连接
        startTcp()
        showMessage("tcp connect --> host: " + Constant.TCP_SERVER_URL + ", port: " + Constant.TCP_PORT)

        Thread(Runnable {
            while (!initialized) {
                runOnUiThread(Runnable {
                    initDevice()
                })
                try {
                    Thread.sleep(20000)
                } catch (e: Exception) {
                    //
                }
            }
        }).start()
    }

    //显示设备信息
    override fun showDeviceInfo(deviceInfo: BedDeviceInfoVO) {
        Constant.SIP_ID = deviceInfo.sipId
        Constant.DEVICE_ID = deviceInfo.id
        Constant.PART_ID = deviceInfo.partId
        Constant.BED_NAME = deviceInfo.fullName

        Constant.DEVICE_TYPE = deviceInfo.deviceType
        Constant.DEVICE_CODE = deviceInfo.code
        Constant.DEVICE_MODEL = deviceInfo.model
        Constant.DEVICE_SOFT_VER = deviceInfo.softVer
        Constant.DEVICE_HARD_VER = deviceInfo.hardVer
        Constant.DEVICE_NAME = deviceInfo.name
        if (deviceInfo.status != null) {
            Constant.DEVICE_STATUS = deviceInfo.status
        }

        initialized = true
        view_title_layout_tv_hospital_name.text = deviceInfo.partDisplay
        view_title_layout_tv_no.text = "ID:" + deviceInfo.id

        if (deviceInfo.customerId != null) {
            Constant.CUSTOM_ID = deviceInfo.customerId
        }
        //EventBus.getDefault().post(MessageEvent("updateCustom", Constant.EVENT_UPDATE_CUSTOM))

        if (TextUtils.isEmpty(Constant.SIP_ID)) {
            showMessage("SIP ID empty")
        }
        if (Constant.DEVICE_STATUS == 0) {
            showMessage(StringUtil.getResString(R.string.device_disable))
        } else if (Constant.DEVICE_STATUS == 1) {
            //启动主fragment
            switchToMainFragment()
        }

        //加载分机所绑定紧急按钮设备信息
        if (deviceInfo.frameId != null) {
            presenter.getEmergencyDeviceInfo(deviceInfo.frameId)
        }

        presenter.loadPartSettings(Constant.PART_ID)

    }

    override fun setPartSettings(partSetting: PartSettingDO) {
        try {
            //设置白昼起止时间
            SettingConfig.setInitialDayTime(this, partSetting.dayStart.substring(0,5))
            SettingConfig.setEndOfDay(this,partSetting.nightStart.substring(0,5))

            //分机白天夜晚亮度
            SettingConfig.setExtensionDaytimeBrightness(this, partSetting.dayLight)
            SettingConfig.setExtensionNightBrightness(this, partSetting.nightLight)

            //分机白天夜晚护理灯 也就是LED灯的亮度
            SettingConfig.setExtensionDaytimeLEDBrightness(this, partSetting.dayNurseLed)
            SettingConfig.setExtensionNightLEDBrightness(this, partSetting.nightNurseLed)

            //分机白天夜晚系统音量
            SettingConfig.setExtensionDaytimeSystemVolume(this, partSetting.dayBedVol)
            SettingConfig.setExtensionNightSystemVolume(this, partSetting.nightBedVol)

            //分机通话音量  没做白昼区分
            SettingConfig.setExtensionCallVolume(this, partSetting.dayBedVol)

            SettingConfig.setSipOverTime(this, partSetting.sipOvertime)
            SettingConfig.setSleepTime(this, partSetting.sleepSecondsBed)

            Constant.doctorTitle = partSetting.doctorTitle
            Constant.nurseTitle = partSetting.nurseTitle
            if (partSetting.doctorValid != null) {
                Constant.doctorValid = partSetting.doctorValid
            }
            if (partSetting.nurseValid != null) {
                Constant.nurseValid = partSetting.nurseValid
            }

            VoiceManagerUtil.setCallVoice(activity, partSetting.dayBedVol)
        } catch (ex: Exception) {
            showMessage(StringUtil.getResString(R.string.setting_params_error) + ex.message)
            ex.printStackTrace()
        }

        updateSettings(true)

        EventBus.getDefault().post(MessageEvent("updateCustom", Constant.EVENT_UPDATE_CUSTOM))
    }

    override fun updateNurseConfig(list: List<NurseConfigDto>) {
        if (list.isNotEmpty()) {
            for ((index, e) in list.withIndex()) {
                if (index < configList.size) {
                    configList.set(index, e)
                } else {
                    configList.add(e)
                }
            }
            nurseConfigAdpter.updateData(configList)
            //护理灯刷新
            hasNurseValue = true
            if (Constant.day_state == 0) {
                SerialPortHelper.setNurseLedLight2(SettingConfig.getExtensionDaytimeLEDBrightness(activity), configList)
            } else {
                SerialPortHelper.setNurseLedLight2(SettingConfig.getExtensionNightLEDBrightness(activity), configList)
            }
        }
    }

    fun addCallFragment(fragment: Fragment) {
        //先切换到首页
        if (!mainFragment.equals(curFragment)) {
            switchToMainFragment()
        }

        skyCallFragment = fragment
        supportFragmentManager.beginTransaction()
            .setCustomAnimations(R.anim.slide_down_in, R.anim.slide_up_out)
            .add(R.id.call_frame, fragment)
            .commit()
    }

    fun removeCallFragment() {
        if (skyCallFragment != null) {
            supportFragmentManager.beginTransaction()
                //.setCustomAnimations(R.anim.slide_down_in, R.anim.slide_down_out)
                .remove(skyCallFragment)
                .commit()
            skyCallFragment = null
        }
    }

    //切换fragment
    private fun switchToFragment(layId: Int, fragment: Fragment, tag: String) {
        supportFragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
                .replace(layId, fragment, tag)
                .commit()
        curFragment = tag
    }

    //切到主信息界面
    private fun switchToMainFragment() {
        hideRightMenu(false)
        switchToFragment(R.id.callingbed_main_frame, MainFragment(), mainFragment)
    }

    //启动TCP连接
    fun startTcp() {
        if (Constant.TCP_SERVER_URL != null && !tcpConnect) {
            tcpConnect = true
            Thread(Runnable { TcpClient.getInstance().init(Constant.TCP_SERVER_URL, Constant.TCP_PORT, Constant.TCP_HEART_BEAT) }).start()
        }
    }

    //设置串口监听
    private fun setSerialListener() {
        SerialPortUtil.getInstance().setOnDataReceiveListener(this)
        SerialPortUtil.getInstance().setOnDataReceiveStringListener(this)
        //开启串口心跳
        SerialPortUtil.getInstance().startHeartBeat()
    }

    //注册时间监听广播
    private fun regReceiver() {
        receiver = TimeReceiver()
        var intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_TIME_TICK)
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(receiver, intentFilter)
    }

    private fun unRegReceiver() {
        unregisterReceiver(receiver)
    }

    fun checkAppVersion() {
        Constant.APP_PATH = ""
        //获取APP版本信息，5寸分机type=4
        if (Constant.PART_ID != null) {
            presenter.getAppVersion(Constant.PART_ID, 4)
        }
        Log.d("AppUpdate", "checkAppVersion =====>>  Constant.PART_ID: " + Constant.PART_ID)
    }

    private fun updateSettings(forceSet: Boolean) {
        val  currentTimestamp = System.currentTimeMillis()

        //白天起始时间戳
        val date = TimeHandle.getDateTime("yyyy-MM-dd")
        val dayStartTimeStamp = TimeHandle.dateToStamp(date+" "+SettingConfig.getInitialDayTime(this)+":00", "yyyy-MM-dd HH:mm:ss")
        //白天结束时间戳
        val endOfDayTimeStamp = TimeHandle.dateToStamp(date+" "+SettingConfig.getEndOfDay(this)+":00", "yyyy-MM-dd HH:mm:ss")

        val curInday = dayStartTimeStamp < currentTimestamp && currentTimestamp < endOfDayTimeStamp

        if (curInday) {
            //当前是白天并且原来不是白天
            if (Constant.day_state != 0 || forceSet) {
                //设置白天亮度
                ScreenManagerUtil().setScreenBrightness(this, Math.ceil(2.54 * SettingConfig.getExtensionDaytimeBrightness(this)).toInt())
                //设置白天系统音量和响铃音
                VoiceManagerUtil.setSystemVoice(this, SettingConfig.getExtensionDaytimeSystemVolume(this))
                VoiceManagerUtil.setMusicVoice(this, SettingConfig.getExtensionDaytimeSystemVolume(this))
                view_title_layout_iv_day_night.setImageResource(R.mipmap.ic_daylight)

                if (hasNurseValue) {
                    SerialPortHelper.setNurseLedLight2(SettingConfig.getExtensionDaytimeLEDBrightness(activity), configList)
                }

                //白天灭掉紧急按钮灯
                AppTool.Time.delay(2000) {
                    SerialPortHelper.setSosLight("0")
                }
            }
            Constant.day_state = 0
        } else {
            //当前是夜晚并且原来不是夜晚
            if (Constant.day_state != 1 || forceSet) {
                //设置晚上亮度
                ScreenManagerUtil().setScreenBrightness(this, Math.ceil(2.54 * SettingConfig.getExtensionNightBrightness(this)).toInt())
                //设置晚上系统音量和响铃音
                VoiceManagerUtil.setSystemVoice(this, SettingConfig.getExtensionNightSystemVolume(this))
                VoiceManagerUtil.setMusicVoice(this, SettingConfig.getExtensionNightSystemVolume(this))
                view_title_layout_iv_day_night.setImageResource(R.mipmap.ic_night)

                if (hasNurseValue) {
                    SerialPortHelper.setNurseLedLight2(SettingConfig.getExtensionNightLEDBrightness(activity), configList)
                }

                //晚上打开紧急按钮灯
                AppTool.Time.delay(2000) {
                    SerialPortHelper.setSosLight("1")
                }
            }
            Constant.day_state = 1
        }
    }

    override fun loadAppVersion(appInfo: AppVersionDO) {
        val newAppVersion = appInfo.versionCode.substring(1)
        Log.d("AppUpdate", "loadAppVersion =====>>  newAppVersion: " + newAppVersion + ", curAppVersion: " + BuildConfig.VERSION_NAME + ", path: " + appInfo.appPath)
        showMessage("current version: " + BuildConfig.VERSION_NAME + "_" + BuildConfig.VERSION_CODE + ", new version: " + newAppVersion + "_" + appInfo.versionNo)

        if (BuildConfig.VERSION_CODE < appInfo.versionNo) {
            if (!updating) {
                //showMessage("即将升级...")
                Constant.APP_PATH = appInfo.appPath
                updating = true
                AppTool.Time.delay(200) {
                    push("/callingbed/update")
                }
            } else {
                showMessage(R.string.updating)
            }
        } else {
            showMessage(R.string.update_no_required)
        }
    }

    override fun showEmergencyInfo(deviceInfo: DeviceDO) {
        if (deviceInfo.id != null) {
            Constant.EMERGENCY_ID = deviceInfo.id
        }
    }

    override fun serialPortBedOnclick(buffer: ByteArray) {
        Log.d("serialPortBedOnclick", "buffer[0]:" + buffer[0] + ", buffer[1]:" + buffer[1] + ", buffer[2]:" + buffer[2]
                + ", buffer[3]:" + buffer[3] + ", buffer[4]:" + buffer[4] + ", buffer[5]:" + buffer[5] + ", buffer[6]:" + buffer[6]
                + ", buffer[7]:" + buffer[7] + ", buffer[8]:" + buffer[8])
        //首页
        if (buffer[0].toInt() == 1 || buffer[0].toInt() == 2) {
            if (skyCallFragment == null) {
                runOnUiThread {
                    clickVHome()
                }
            }
        }

        //费用
        else if (buffer[1].toInt() == 1 || buffer[1].toInt() == 2) {
            if (skyCallFragment == null) {
                runOnUiThread {
                    clickVCost()
                }
            }
        }

        //更多
        else if (buffer[2].toInt() == 1 || buffer[2].toInt() == 2) {
            if (skyCallFragment == null) {
                if (System.currentTimeMillis() - pressTime > 3000) {
                    checkAppVersion()
                } else {
                    runOnUiThread {
                        clickVQrcode()
                    }
                }
            }
        } else if (buffer[2].toInt() == 0) {
            //长按二维码按键检查版本升级
            pressTime = System.currentTimeMillis()
        }

        //增援
        else if (buffer[3].toInt() == 1 || buffer[3].toInt() == 2) {
            if (skyCallFragment == null) {
                runOnUiThread {
                    clickVSupport()
                }
            }
        }

        //呼叫
        else if (buffer[4].toInt() == 1 || buffer[4].toInt() == 2) {
            runOnUiThread {
                clickVCall(true)
            }
        }

        //呼叫护士键短按或长按松开
        else if (buffer[5].toInt() == 1 || buffer[5].toInt() == 2) {
            runOnUiThread {
                clickVCall(false)
            }
        }

        //手柄呼叫键短按或长按松开
        else if (buffer[6].toInt() == 1 || buffer[6].toInt() == 2) {
            runOnUiThread {
                clickCall()
            }
        }

        //紧急呼叫
        else if (buffer[7].toInt() == 1 || buffer[7].toInt() == 2) {
            //卫生间紧急按钮: 一定时间内重复多次按无效
            if (System.currentTimeMillis() - clickSosTime > 10000) {
                runOnUiThread {
                    clickSosTime = System.currentTimeMillis()
                    if (Constant.TCP_CONNECTED) {
                        SOSHelper.sosStart()
                    }
                }
            }
        }
    }

    override fun serialPortBedOnclickString(str: String) {
        try {
            val newStr = str.substring(str.indexOf("$") + 1, str.indexOf("#"))
            Log.d("serialPortBedOnclickString", "newStr==$newStr")
            if (newStr.startsWith("V")) {
                Constant.MCU_VERSION_NUMBER = newStr.substring(newStr.indexOf(",") + 1, 16)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun isVisible(v: View) : Boolean {
        return v.visibility == View.VISIBLE
    }

    private fun clickVHome() {
        //重置超时时间
        backTimeout = 0
        if (mainFragment.equals(curFragment)) {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
            } else {
                showRightMenu()
            }
        } else {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
                switchToMainFragment()
            } else {
                showRightMenu()
            }
        }
    }

    private fun clickVCost() {
        //重置超时时间
        backTimeout = 0
        if (costFragment.equals(curFragment)) {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
            } else {
                showRightMenu()
            }
        } else {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
                switchToFragment(R.id.callingbed_main_frame, CostFragment(), costFragment)
            } else {
                showRightMenu()
            }
        }
    }

    private fun clickVQrcode() {
        //重置超时时间
        backTimeout = 0
        if (qrCodeFragment.equals(curFragment)) {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
            } else {
                showRightMenu()
            }
        } else {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
                switchToFragment(R.id.callingbed_main_frame, QrCodeFragment(), qrCodeFragment)
            } else {
                showRightMenu()
            }
        }
    }

    private fun clickVSupport() {
        //重置超时时间
        backTimeout = 0
        if (isVisible(right_menu)) {
            hideRightMenu(true)
            showMessage(R.string.support_sent)
            if (Constant.TCP_CONNECTED) {
                if (Constant.DEVICE_ID != -1) {
                    OtherUtil.sendReinforce(Constant.DEVICE_ID)
                } else {
                    showMessage("no device id!")
                }
            } else {
                showMessage(R.string.net_error)
            }
        } else {
            showRightMenu()
        }
    }

    private fun clickVCall(checkMenu: Boolean) {
        //重置超时时间
        backTimeout = 0
        //当前为待机状态,显示呼叫
        if (Constant.CALL_STATE == Constant.CALL_STANDBY) {
            if (checkMenu) {
                if (isVisible(right_menu)) {
                    hideRightMenu(true)
                    if (!TextUtils.isEmpty(Constant.SIP_ID)) {
                        //没有摄像头则只能拨打语音
                        startCall(Constant.VOICE_CALL)
                    } else {
                        showMessage(R.string.no_custom)
                    }
                } else {
                    showRightMenu()
                }
            } else {
                if (isVisible(right_menu)) {
                    hideRightMenu(true)
                }
                if (!TextUtils.isEmpty(Constant.SIP_ID)) {
                    //没有摄像头则只能拨打语音
                    startCall(Constant.VOICE_CALL)
                } else {
                    showMessage(R.string.no_custom)
                }
            }
        } else if (Constant.CALL_STATE == Constant.CALL_CALLING) {
            //通话中挂断
            EventBus.getDefault().post(MessageEvent("handoff", Constant.EVENT_SERIAL_EVENT))
            Constant.CALL_STATE = Constant.CALL_STANDBY
        } else if (Constant.CALL_STATE == Constant.CALL_OUTGOING) {
            //呼叫取消
            EventBus.getDefault().post(MessageEvent("cancel", Constant.EVENT_SERIAL_EVENT))
            Constant.CALL_STATE = Constant.CALL_STANDBY
        } else if (Constant.CALL_STATE == Constant.CALL_INCOMING) {
            //来电接听
            EventBus.getDefault().post(MessageEvent("accept", Constant.EVENT_SERIAL_EVENT))
        }
    }

    private fun clickCall() {
        //重置超时时间
        backTimeout = 0
        //当前为待机状态,显示呼叫
        if (Constant.CALL_STATE == Constant.CALL_STANDBY) {
            if (isVisible(right_menu)) {
                hideRightMenu(true)
            }
            if (!TextUtils.isEmpty(Constant.SIP_ID)) {
                //没有摄像头则只能拨打语音
                startCall(Constant.VOICE_CALL)
            } else {
                showMessage(R.string.no_custom)
            }
        } else if (Constant.CALL_STATE == Constant.CALL_INCOMING) {
            //来电接听
            EventBus.getDefault().post(MessageEvent("accept", Constant.EVENT_SERIAL_EVENT))
        } else if (Constant.CALL_STATE == Constant.CALL_CALLING) {
            //挂断
            EventBus.getDefault().post(MessageEvent("handoff", Constant.EVENT_SERIAL_EVENT))
        }
    }


    /**
     * 显示右侧菜单栏
     */
    protected fun showRightMenu() {
        val animation = AnimationUtils.loadAnimation(applicationContext, R.anim.in_righttoleft)
        right_menu.setAnimation(animation)
        right_menu.setVisibility(View.VISIBLE)
    }

    /**
     * 隐藏右侧菜单栏
     */
    protected fun hideRightMenu(haveAnimation: Boolean) {
        if (haveAnimation) {
            val animation = AnimationUtils.loadAnimation(applicationContext, R.anim.in_lefttoright)
            right_menu.setAnimation(animation)
        }
        right_menu.setVisibility(View.GONE)
    }

    //开始呼叫
    fun startCall(type: Int) {
        //通话之前先判断webrtc socket和tcp是否连接正常，否则不能建立通话
        if (Constant.TCP_CONNECTED && !TextUtils.isEmpty(Constant.SIP_ID)) {
            //去电界面
            Constant.CALL_TYPE = type
            Constant.CALL_STATE = Constant.CALL_OUTGOING
            var fragment = SkyCallFragment()
            var bundle = Bundle()
            bundle.putInt("call_state", 0)
            fragment.arguments = bundle
            addCallFragment(fragment)
        } else {
            showMessage(R.string.call_init_error)
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMoonEvent(messageEvent: MessageEvent) {
        synchronized(Unit) {
            handleTcpModel(messageEvent)
        }
    }

    fun handleTcpModel(messageEvent: MessageEvent) {
        when (messageEvent.getType()) {
            //退出通话界面
            Constant.EVENT_REMOVE_CALL_FRAGMENT -> {
                if (skyCallFragment != null) {
                    Constant.CALL_STATE = Constant.CALL_STANDBY
                    removeCallFragment()
                }
            }

            //Sip注册状态
            Constant.EVENT_SIP_REGISTER_STATUS -> {
                if (messageEvent.message is String) run {
                    val status = messageEvent.message as String
                    Log.d("sip", "sip regist status: " + status)
                    updateStatus(status)
                }
            }

            //网络ping状态
            /*Constant.EVENT_INTERNETPING -> {
                //SipHelper.getInstance().obtainSipInfo()
                if (NetHelper.NetConn && NetHelper.getInstance().networkType == ConnectivityManager.TYPE_ETHERNET) {
                    view_title_layout_iv_ethernet.setImageResource(R.mipmap.ic_etherneted)
                } else {
                    view_title_layout_iv_ethernet.setImageResource(R.mipmap.ic_no_ethernet)
                }
                view_title_layout_iv_wifi.setImageResource(R.mipmap.ic_wifi_nor)
            }*/

            //返回主界面
            Constant.EVENT_BACK_MAIN -> {
                switchToMainFragment()
            }

            //TCP连接状态
            Constant.EVENT_TCP_STATE -> {
                updateTcpState()
            }

            Constant.EVENT_RESTART_APP -> {
                AppUpdateHelper.restartApp(activity)
            }

            //TCP消息处理
            Constant.EVENT_TCP_MSG -> {
                if (messageEvent.message is TcpModel) {
                    val tcpModel = messageEvent.message as TcpModel
                    Log.d("TCP", "received tcp action: " + tcpModel.action + ", type: " + tcpModel.type)
                    if (tcpModel.getType() == TcpType.VOICE) {
                        if (tcpModel.data != null) {
                            val interactionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                            if (tcpModel.action == TcpAction.VoiceAction.CALL) {
                                Constant.fromId = tcpModel.fromId
                                Constant.interactionId = interactionVO.id
                                Constant.TARGET_SIP = interactionVO.fromSipId
                                Constant.CALL_STATE = Constant.CALL_INCOMING
                                //通话之前先判断webrtc socket是否连接上，否则不能建立通话
                                if (Constant.TCP_CONNECTED && !TextUtils.isEmpty(Constant.SIP_ID)) {
                                    //来电界面
                                    var fragment = SkyCallFragment()
                                    var bundle = Bundle()
                                    bundle.putInt("call_state", 1)
                                    bundle.putSerializable("tcp_model", tcpModel)
                                    fragment.arguments = bundle
                                    addCallFragment(fragment)
                                } else {
                                    showMessage(R.string.call_init_error)
                                    Constant.CALL_STATE = Constant.CALL_STANDBY
                                    VoiceUtil.rejectAudioCall(
                                        Constant.DEVICE_ID,
                                        Constant.fromId,
                                        Constant.interactionId
                                    )
                                }
                            }
                        }
                    } else if (tcpModel.type == TcpType.SIDE) {
                        if (tcpModel.action == TcpAction.SideAction.NURSING) {
                            //如果该房间是在护理状态且当前有呼叫或通话则结束掉，此时该房间分机将当成临时主机接收呼叫
                            if (Constant.CALL_STATE == Constant.CALL_CALLING) {
                                //通话中挂断
                                EventBus.getDefault().post(MessageEvent("handoff", Constant.EVENT_SERIAL_EVENT))
                                Constant.CALL_STATE = Constant.CALL_STANDBY
                            } else if (Constant.CALL_STATE == Constant.CALL_OUTGOING) {
                                //呼叫取消
                                EventBus.getDefault().post(MessageEvent("cancel", Constant.EVENT_SERIAL_EVENT))
                                Constant.CALL_STATE = Constant.CALL_STANDBY
                            } else if (Constant.CALL_STATE == Constant.CALL_INCOMING) {
                                //来电拒绝
                                EventBus.getDefault().post(MessageEvent("reject", Constant.EVENT_SERIAL_EVENT))
                                Constant.CALL_STATE = Constant.CALL_STANDBY
                            }
                        } else {
                            DoorLightHelper.handleDoorLight(tcpModel)
                        }
                    } else if (tcpModel.type == TcpType.SOS) {
                        if (tcpModel.action == TcpAction.SOSAction.CANCEL) {
                            //紧急呼叫已处理
                            SOSHelper.sosStop()
                        }
                    } else if (tcpModel.type == TcpType.DEVICE) {
                        //检查APP版本
                        if (tcpModel.getAction() == TcpAction.DeviceAction.APP_UPDATE) {
                            checkAppVersion()
                        } else if (tcpModel.action == TcpAction.DeviceAction.RESTART) {
                            //收到重启app指令，若当前处于正常待机状态则直接重启app，否则等待通话结束再重启
                            if (Constant.CALL_STATE == Constant.CALL_STANDBY) {
                                AppUpdateHelper.restartApp(activity)
                            } else {
                                Constant.LATER_RESTART = true
                            }
                        } else if (tcpModel.action == TcpAction.DeviceAction.SYSTEM_SETTING) {
                            presenter.loadPartSettings(Constant.PART_ID)
                        } else if (tcpModel.action == TcpAction.DeviceAction.SERVER_CHANGE) {
                            //服务器地址变更
                            if (tcpModel.data != null) {
                                val json = JSONObject.parseObject(tcpModel.data.toString())
                                val serverIp = json.getString("server_ip")
                                val serverPort = json.getString("server_port")
                                Log.e(TAG, "server ip:$serverIp, server port:$serverPort")
                                CommonUtils.setUrl(activity, serverIp)
                                CommonUtils.setUrlPort(activity, serverPort)
                                AppTool.Time.delay(2000) {
                                    AppUpdateHelper.restartApp(activity)
                                }
                            }
                        }
                    } else if (tcpModel.action == TcpAction.DataAction.REFRESH) {
                        //重新加载数据，比如出院，入院等
                        initDevice()
                    } else if (tcpModel.type == TcpType.TIME) {
                        if (tcpModel.action == TcpAction.TimeAction.SYNC) {
                            val time = tcpModel.data.toString().toLong() * 1000
                            try {
                                AppUtil.setSystemTime(BaseApplication.appContext, time)
                                Log.d("setTime", "set sys time1: $time")
                            } catch (e: Exception) {
                                //"20211213:092314"
                                val timeStr = TimeHandle.getDateTime(time, "yyyyMMdd.hhmmss")
                                AppUtil.setSysTime(timeStr)
                                Log.d("setTime", "set sys time2: $timeStr")
                            }
                        }
                    }

                    //探视
                    /*if (tcpModel.type == TcpType.VIDEO) {
                        val interactionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                        if (tcpModel.action == TcpAction.VideoAction.VIDEO_INVITE_JOIN) {
                            if (Constant.CALL_STATE != Constant.CALL_STANDBY) {
                                VideoUtil.videoInCalling(Constant.DEVICE_ID, tcpModel.fromId, interactionVO.id)
                            } else {
                                //收到探视请求，向探视机发起视频通话
                                Constant.interactionId = interactionVO.id
                                Constant.fromId = tcpModel.fromId
                                Constant.CALL_STATE = Constant.CALL_OUTGOING

                                //通话之前先判断webrtc socket是否连接上，否则不能建立通话
                                if (Constant.TCP_CONNECTED) {
                                    //探视界面
                                    var fragment = SkyCallFragment()
                                    var bundle = Bundle()
                                    bundle.putInt("call_state", 2)
                                    bundle.putSerializable("tcp_model", tcpModel)
                                    fragment.arguments = bundle
                                    addCallFragment(fragment)
                                } else {
                                    showMessage("服务未连接，请稍后")
                                    Constant.CALL_STATE = Constant.CALL_STANDBY
                                    VoiceUtil.rejectAudioCall(Constant.DEVICE_ID, Constant.fromId, Constant.interactionId)
                                }
                            }
                        } else if (tcpModel.action == TcpAction.VideoAction.HANDOFF) {
                            Constant.CALL_STATE = Constant.CALL_STANDBY
                        }
                    }*/
                }
            }
        }
    }

    /**
     * Sip状态灯显示
     *
     * @param state
     */
    private fun updateStatus(state: String) {
        runOnUiThread {
            when (state) {
                SipStatus.REGISTERING -> {
                    view_title_layout_tv_point.setBackgroundResource(R.color.yellow_color)
                }
                SipStatus.REGISTERFAIL -> {
                    view_title_layout_tv_point.setBackgroundResource(R.color.red_color)
                }
                SipStatus.REGISTERCOM -> {
                    view_title_layout_tv_point.setBackgroundResource(R.color.green)
                }
            }
        }
    }

    private fun updateNetState() {
        if (NetHelper.getInstance().networkType == ConnectivityManager.TYPE_WIFI) {
            view_title_layout_iv_wifi.visibility = View.VISIBLE
            view_title_layout_iv_wifi.setImageResource(R.mipmap.ic_wifi_success)
            view_title_layout_iv_ethernet.visibility = View.GONE
        } else if (NetHelper.getInstance().networkType == ConnectivityManager.TYPE_ETHERNET) {
            view_title_layout_iv_ethernet.visibility = View.VISIBLE
            view_title_layout_iv_ethernet.setImageResource(R.mipmap.ic_ethernet_success)
            view_title_layout_iv_wifi.visibility = View.GONE
        }

        /*if (NetHelper.isBTConnected()) {
            view_title_layout_iv_bt.visibility = View.VISIBLE
            view_title_layout_iv_bt.setImageResource(R.mipmap.ic_bt_success)
        } else {
            view_title_layout_iv_bt.visibility = View.GONE
        }*/

        /*
        * 检查网络情况，若tcp断开连接多次且IP也是空的则网络异常，重启设备
        * 仅对3128设备有效
         */
        if (Build.MODEL.equals("rk3128")) {
            var count = SettingConfig.getNetErrResetCount(this)
            if (!Constant.TCP_CONNECTED && TextUtils.isEmpty(NetHelper.getInstance().localIP)) {
                netErrCount++
            } else {
                netErrCount = 0
                if (count > 0) {
                    count = 0
                    SettingConfig.setNetErrResetCount(this, count)
                }
            }

            if (netErrCount >= 5) {
                //如果重启次数超过8次还是无网则不再重启
                if (count < 8) {
                    count++
                    SettingConfig.setNetErrResetCount(this, count)
                    Handler().postDelayed({
                        AppUpdateHelper.reboot(activity)
                    }, 5000)
                } else {
                    WarningDialogHelper.showDialog(activity)
                }
            }
        }
    }

    private fun updateTcpState() {
        if (Constant.TCP_CONNECTED) {
            view_title_layout_iv_tcp.setImageResource(R.mipmap.ic_tcp_success)
            view_title_layout_tv_point.setBackgroundResource(R.color.green)
        } else {
            view_title_layout_iv_tcp.setImageResource(R.mipmap.ic_tcp_fail)
            view_title_layout_tv_point.setBackgroundResource(R.color.red_color)
        }
    }

    inner class TimeReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == Intent.ACTION_TIME_TICK) {
                updateNetState()
                if (initialized) {
                    updateSettings(false)
                    updateTcpState()

                    if (Constant.LATER_RESTART && Constant.CALL_STATE == Constant.CALL_STANDBY) {
                        AppUpdateHelper.restartApp(activity)
                    }
                } /*else if (TextUtils.isEmpty(Constant.TCP_SERVER_URL)) {
                    //还未连接tcp服务器
                    presenter.loadTcpServerHost()
                }*/
            } else if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
                updateNetState()
            }
        }
    }


    private val handler = MyHandler(this)
    //时间线程
    inner class TimeThread : Thread() {
        override fun run() {
            while (isTimeWorking) {
                try {
                    sleep(1000)
                    val msg = handler.obtainMessage()
                    msg.what = TIME_WHAT
                    handler.sendMessage(msg)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
    }

    class MyHandler(activity: CallingbedActivity) : Handler() {
        // 弱引用 ，防止内存泄露
        private val weakReference: WeakReference<CallingbedActivity>

        init {
            weakReference = WeakReference<CallingbedActivity>(activity)
        }

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            // 通过软引用看能否得到activity示例
            val handlerMemoryActivity = weakReference.get()
            // 防止内存泄露
            if (handlerMemoryActivity != null) {
                when (msg.what) {
                    TIME_WHAT -> {
                        handlerMemoryActivity.backToMain()
                    }
                }
            } else {
                showMessage(R.string.tips_reboot)
            }
        }
    }

    fun backToMain() {
        backTimeout++
        if (backTimeout >= Constant.CALL_TIMEOUT) {
            //费用、二维码界面超时返回主界面
            if (costFragment.equals(curFragment) || qrCodeFragment.equals(curFragment)) {
                if (Constant.DEVICE_STATUS == 1) {
                    switchToMainFragment()
                }
            }
            //超时隐藏右侧菜单栏
            if (isVisible(right_menu)) {
                hideRightMenu(false)
            }
            backTimeout = 0
        }

        if (backTimeout >= 100000) {
            backTimeout = 0
        }
    }
}