package com.wdkl.lcd_board.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.net.ConnectivityManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import com.alibaba.fastjson.JSON
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.lcd_board.BuildConfig
import com.wdkl.lcd_board.R
import com.wdkl.lcd_board.databinding.ActivityMainLayoutBinding
import com.wdkl.lcd_board.entity.Program
import com.wdkl.lcd_board.helper.AppUpdateHelper
import com.wdkl.lcd_board.helper.NetHelper
import com.wdkl.lcd_board.helper.ServerConfigDialogHelper
import com.wdkl.lcd_board.launch.MainLaunch
import com.wdkl.ncs.android.lib.base.BaseActivity
import com.wdkl.ncs.android.lib.base.BaseApplication
import com.wdkl.ncs.android.lib.utils.*
import com.wdkl.ncs.android.lib.vo.filter
import com.wdkl.ncs.android.middleware.api.UrlManager
import com.wdkl.ncs.android.middleware.common.Constant
import com.wdkl.ncs.android.middleware.common.MessageEvent
import com.wdkl.ncs.android.middleware.logic.contract.conversion_box.MainActivityContract
import com.wdkl.ncs.android.middleware.logic.presenter.conversion_box.MainActivityPresenter
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.PartSettingDO
import com.wdkl.ncs.android.middleware.model.dto.TcpSeverDTO
import com.wdkl.ncs.android.middleware.model.vo.DeviceNurseInfoVO
import com.wdkl.ncs.android.middleware.model.vo.InteractionVO
import com.wdkl.ncs.android.middleware.tcp.TcpClient
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.AppUtil
import com.wdkl.ncs.android.middleware.utils.CommonUtils
import kotlinx.android.synthetic.main.activity_main_layout.*
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 java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.TimeUnit


@Router(path = "/lcd_board/main")
class MainActivity :BaseActivity<MainActivityPresenter, ActivityMainLayoutBinding>(), MainActivityContract.View {
    private val TAG = "MainActivity"

    private val QR_CODE_PATH = "http://m.wdklian.com/care/apk/care.user?type=NCS_DEVICE"
    private lateinit var receiver: TimeReceiver
    private lateinit var animationIn: Animation

    private var updating :Boolean = false
    private var initialized :Boolean = false


    private var tcpConnect: Boolean = false
    private var loaded: Boolean = false

    private var serverIp = ""
    private var serverSuccess = false
    private val handler by lazy { Handler(Looper.getMainLooper()) }

    //需要显示的节目列表
    private val programs = ArrayList<Program>()
    private val callHandler = MyHandler(this)

    companion object {
        private const val NEW_CALL_WHAT = 1001
        private const val UPDATE_CALL_WHAT = 1002
        private const val DELAY_TIME: Long = 8000

        private const val BED_CALL = " 呼叫"
        private const val SOS_CALL = " 紧急呼叫"
    }

    private var curProgramIndex = 0

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

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

    override fun init() {

        //获取mac地址
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            Constant.LOCAL_MAC = NetHelper.getInstance().macAddress
        } else {
            Constant.LOCAL_MAC = NetHelper.getCPUSerial()
        }

        //注册广播
        regReceiver()

        EventBus.getDefault().register(this)

        //更新状态图标
        updateNetState()

        Thread{
            //val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.erlogo)
            var builder = StringBuilder()
            builder.append(QR_CODE_PATH)
            builder.append("&code=")
            builder.append(Constant.DEVICE_CODE)
            builder.append("&mac=")
            builder.append(Constant.LOCAL_MAC)
            builder.append("&model=")
            builder.append(Constant.DEVICE_MODEL)
            builder.append("&hard_ver=")
            builder.append(Constant.DEVICE_HARD_VER)
            builder.append("&soft_ver=")
            builder.append(Constant.DEVICE_SOFT_VER)
            builder.append("&device_type=")
            builder.append(Constant.DEVICE_TYPE)
            builder.append("&device_name=")
            builder.append(Constant.DEVICE_NAME)
            val code = EcodeHelper().createQRImage(builder.toString(),200, null)
            activity.runOnUiThread {
                home_view_qr_code?.setImageBitmap(code)
            }
        }.start()

        val buildUrl = UrlManager.build()
        Constant.LOCAL_IP = NetHelper.getInstance().localIP
        serverIp =  buildUrl.buyer.substringAfterLast("//").substringBefore(":")
        val str = ("MAC: " + Constant.LOCAL_MAC
                + "\r\nIP: " + Constant.LOCAL_IP + ", server: " + serverIp
                + "\r\nAPP版本: V" + BuildConfig.VERSION_NAME + "_" + BuildConfig.VERSION_CODE + "_" + Build.MODEL
                + "\r\n发布日期:" + BuildConfig.BUILD_TIME
                + "\r\nAndroid SDK: " + Build.VERSION.SDK_INT)
        device_init_info.text = str
        view_version_no.text = "V" + BuildConfig.VERSION_NAME

        Log.e(TAG, "local mac: " + Constant.LOCAL_MAC)

        checkServer()

        animationIn = AnimationUtils.loadAnimation(this@MainActivity, R.anim.slide_in)

        //test
        /*handler.postDelayed({
            val program1 = Program()
            program1.time = System.currentTimeMillis()
            program1.text = "01房01床" + BED_CALL
            programs.add(0, program1)
            callHandler.sendEmptyMessage(NEW_CALL_WHAT)
        }, 30000)

        handler.postDelayed({
            val program2 = Program()
            program2.time = System.currentTimeMillis()
            program2.text = "03房" + SOS_CALL
            programs.add(0, program2)
            callHandler.sendEmptyMessage(NEW_CALL_WHAT)
        }, 45000)*/
    }

    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()

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

                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)
        }
    }


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

    override fun bindEvent() {
        btn_set_server.setOnClickListener {
            ServerConfigDialogHelper.showPasswordDialog(activity)
        }

        btn_reboot.setOnClickListener {
            AppUpdateHelper.rebootDevice()
        }
    }

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


    override fun destory() {
        unRegReceiver()
        EventBus.getDefault().unregister(this)
        Constant.CALL_STATE = Constant.CALL_STANDBY

        handler.removeCallbacksAndMessages(null)
        callHandler.removeCallbacksAndMessages(null)
    }

    //数据加载错误
    override fun onError(message: String, type: Int) {
        //errorLog("error",message)
        showMessage("数据加载错误")
    }

    //没有网络
    override fun onNoNet() {
        showMessage("没有网络")
    }

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

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

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

        },onWifi = {

        },offline = {

        })
    }

    override fun setTcpServerHost(tcpSeverDTO: TcpSeverDTO) {
        //
    }

    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

        //开启TCP连接
        startTcp()
        showMessage("tcp开始连接...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: DeviceNurseInfoVO) {
        Constant.SIP_ID = deviceInfo.sipId
        Constant.DEVICE_ID = deviceInfo.id
        Constant.PART_ID = deviceInfo.partId

        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
        }

        view_title_layout_device_state.visibility = View.VISIBLE
        //设备启用，进入正常模式
        if (Constant.DEVICE_STATUS == 1) {
            tv_device_status.setText("设备状态: 已启用")
            tv_device_status.setTextColor(Color.parseColor("#00FF00"))
            view_title_layout_device_state.setImageResource(R.drawable.ic_call_state)
        } else {
            tv_device_status.setTextColor(Color.parseColor("#FF0000"))
            tv_device_status.setText("设备状态: 未注册或未启用")
            view_title_layout_device_state.setImageResource(R.drawable.ic_home_state)
        }

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

        /*if (Constant.PART_ID != null) {
            presenter.loadPartSettings(Constant.PART_ID)
        }*/

        //正式版本开机启动自动检查升级
        if (!BuildConfig.DEBUG) {
            checkAppVersion()
        }

        ll_register_view.visibility = View.GONE
        ll_board_view.visibility = View.VISIBLE
    }


    override fun setPartSettings(partSetting: PartSettingDO) {
        //
    }

    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("获取版本成功，当前版本: " + BuildConfig.VERSION_NAME + "_" + BuildConfig.VERSION_CODE + ", 服务器版本: " + newAppVersion + "_" + appInfo.versionNo)

        if (BuildConfig.VERSION_CODE < appInfo.versionNo) {
            if (!updating) {
                //showMessage("即将升级...")
                Constant.APP_PATH = appInfo.appPath
                updating = true
                AppTool.Time.delay(200) {
                    push("/lcd_board/update")
                }
            } else {
                showMessage("正在升级中...")
            }
        } else {
            showMessage("当前已是最新版本")
        }
    }

    fun startTcp() {
        if (!TextUtils.isEmpty(Constant.TCP_SERVER_URL) && !tcpConnect) {
            tcpConnect = true
            Thread(Runnable {
                TcpClient.getInstance().init(Constant.TCP_SERVER_URL, Constant.TCP_PORT, Constant.TCP_HEART_BEAT)
                TcpClient.getInstance().setTcpCallback {
                    //updateSendTcpInfo(it)
                }
            }).start()
        }
    }

    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)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMoonEvent(messageEvent: MessageEvent) {
        //代码同步
        synchronized(Unit) {
            handleTcpModel(messageEvent)
        }
    }

    private fun handleTcpModel(messageEvent: MessageEvent) {
        when (messageEvent.getType()) {
            //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.type == TcpType.VOICE) {
                        //设备未启用，不更新呼叫信息
                        if (Constant.DEVICE_STATUS != 1) {
                            return
                        }

                        if (tcpModel.action == TcpAction.VoiceAction.CALL) {
                            val callInteractionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                            val bedCall: String = callInteractionVO.fromFrameFullName + BED_CALL
                            for (program in programs) {
                                if (bedCall == program.text) {
                                    programs.remove(program)
                                }
                            }
                            val program1 = Program()
                            program1.time = System.currentTimeMillis()
                            program1.text = bedCall
                            programs.add(0, program1)
                            callHandler.sendEmptyMessage(NEW_CALL_WHAT)
                        } else if (tcpModel.action == TcpAction.VoiceAction.HANDOFF
                            || tcpModel.action == TcpAction.VoiceAction.CANCEL
                            || tcpModel.action == TcpAction.VoiceAction.REJECT
                            || tcpModel.action == TcpAction.VoiceAction.VOICE_OFF
                            || tcpModel.action == TcpAction.VoiceAction.ACCEPT) {
                            val callInteractionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                            val bedCall: String = callInteractionVO.fromFrameFullName + BED_CALL

                            deleteCall(bedCall)
                        }
                    } else if (tcpModel.type == TcpType.SOS) {
                        //设备未启用，不更新呼叫信息
                        if (Constant.DEVICE_STATUS != 1) {
                            return
                        }

                        if (tcpModel.action == TcpAction.SOSAction.CALL || tcpModel.action == TcpAction.SOSAction.ROOM_CALL) {
                            val sosInteractionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                            //优先使用data数据
                            val sosCall: String
                            if (sosInteractionVO.data != null) {
                                sosCall = sosInteractionVO.data
                            } else {
                                sosCall = sosInteractionVO.fromFrameFullName + SOS_CALL
                            }

                            for (program in programs) {
                                if (sosCall == program.text) {
                                    programs.remove(program)
                                }
                            }
                            val program2 = Program()
                            program2.time = System.currentTimeMillis()
                            program2.text = sosCall
                            programs.add(0, program2)
                            callHandler.sendEmptyMessage(NEW_CALL_WHAT)
                        } else if (tcpModel.action == TcpAction.SOSAction.CANCEL || tcpModel.action == TcpAction.SOSAction.CANCELED) {
                            val sosInteractionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                            val sosCall: String
                            if (sosInteractionVO.data != null) {
                                sosCall = sosInteractionVO.data
                            } else {
                                sosCall = sosInteractionVO.fromFrameFullName + SOS_CALL
                            }

                            deleteCall(sosCall)
                        } else if (tcpModel.action == TcpAction.SOSAction.RECEIVED
                            || tcpModel.action == TcpAction.SOSAction.NO_MATCH) {
                            //不处理
                        } else {
                            //其他类型紧急呼叫
                            if (tcpModel.data != null) {
                                val sosInteractionVO = Gson().fromJson(tcpModel.data.toString(), InteractionVO::class.java)
                                //优先使用data数据
                                val sosCall: String
                                if (sosInteractionVO.data != null) {
                                    sosCall = sosInteractionVO.data
                                } else {
                                    sosCall = sosInteractionVO.fromFrameFullName + SOS_CALL
                                }

                                for (program in programs) {
                                    if (sosCall == program.text) {
                                        programs.remove(program)
                                    }
                                }
                                val program2 = Program()
                                program2.time = System.currentTimeMillis()
                                program2.text = sosCall
                                programs.add(0, program2)
                                callHandler.sendEmptyMessage(NEW_CALL_WHAT)
                            }
                        }
                    } else if (tcpModel.type == TcpType.DEVICE) {
                        //检查APP版本
                        if (tcpModel.getAction() == TcpAction.DeviceAction.APP_UPDATE) {
                            checkAppVersion()
                        } else if (tcpModel.action == TcpAction.DeviceAction.SYSTEM_SETTING) {
                            /*if (Constant.PART_ID != null) {
                                presenter.loadPartSettings(Constant.PART_ID)
                            }*/
                        } else if (tcpModel.action == TcpAction.DeviceAction.RESTART) {
                            AppUpdateHelper.restartApp(activity)
                        } 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.type == TcpType.SIDE) {
                        //
                    } else if (tcpModel.action == TcpAction.DataAction.REFRESH) {
                        //重新加载数据，比如出院，入院等
                        initDevice()
                    } else if(tcpModel.action == TcpAction.TimeAction.SYNC){
                        //val time =  tcpModel.data.toString().toLong()*1000
                        //setSystemTime(time)

                        //设置系统时间
                        /*try {
                            AppUtil.setSystemTime(BaseApplication.appContext, time)
                            Log.d(TAG, "set sys time1: $time")
                        } catch (e: Exception) {
                            //"20211213:092314"
                            val time2 = TimeHandle.getDateTime(time, "yyyyMMdd.hhmmss")
                            AppUtil.setSysTime(time2)
                            Log.d(TAG, "set sys time2: $time2")
                        }*/

                        var time = 0L
                        var timeZone="Asia/Shanghai"
                        if (canParseJson(tcpModel.data.toString())) {
                            val json = JSON.parseObject(tcpModel.data.toString())
                            time = json.getLong("time")*1000
                            timeZone = json.getString("time_zone")
                        } else {
                            time = tcpModel.data.toString().toLong() * 1000
                        }

                        setSystemTime(time)

                        try {
                            AppUtil.setSystemTime(BaseApplication.appContext, time, timeZone)
                            Log.d("setTime", "set sys time1: $time, $timeZone")
                        } catch (e: Exception) {
                            //"20211213:092314"
                            val timeStr = TimeHandle.getDateTime(time, "yyyyMMdd.HHmmss")
                            AppUtil.setSysTime(timeStr, timeZone)
                            Log.d("setTime", "set sys time2: $timeStr, $timeZone")
                        }
                    }
                }
            }

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

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

    private fun canParseJson(str:String) : Boolean {
        var result = false
        try {
            JSON.parseObject(str)
            result=true
        }catch (e:java.lang.Exception){
            result=false
        }
        return result
    }

    private fun setSystemTime(time: Long) {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = time
        //当前年
        val year: Int = calendar.get(Calendar.YEAR)
        //当前月
        val month: Int = calendar.get(Calendar.MONTH) + 1
        //当前月的第几天：即当前日
        val day_of_month: Int = calendar.get(Calendar.DAY_OF_MONTH)
        //当前时：HOUR_OF_DAY-24小时制；HOUR-12小时制
        val hour: Int = calendar.get(Calendar.HOUR_OF_DAY)
        val minute: Int = calendar.get(Calendar.MINUTE)
        val second: Int = calendar.get(Calendar.SECOND)

        //showMsgMain("当前时间: " + year+month+day_of_month+hour+minute+second)

        val intent = Intent("android.intent.action.settime")
        val timeArray = intArrayOf(year, month, day_of_month, hour, minute, second)  //年月日时分秒
        intent.putExtra("settime", timeArray)
        intent.putExtra("enable", true)
        sendBroadcast(intent)
    }

    private fun updateNetState() {
        runOnUiThread {
            if (Constant.TCP_CONNECTED) {
                view_title_layout_tv_point.setBackgroundResource(R.color.green)
            } else if (NetHelper.getInstance().networkAvailable()) {
                view_title_layout_tv_point.setBackgroundResource(R.color.yellow_color)
            } else {
                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) {
                    updateNetState()
                    resetPrograms()
                }
            } else if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
                updateNetState()
            }
        }
    }


    class MyHandler(activity: MainActivity) : Handler() {
        // 弱引用 ，防止内存泄露
        private val weakReference: WeakReference<MainActivity> = WeakReference(activity)
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            // 通过软引用,看能否得到activity示例
            val handlerMemoryActivity = weakReference.get()
            // 防止内存泄露
            if (handlerMemoryActivity != null) {
                when (msg.what) {
                    NEW_CALL_WHAT -> {
                        //有新的呼叫进来，直接显示
                        if (handlerMemoryActivity.programs.size > 0) {
                            handlerMemoryActivity.curProgramIndex = 0
                            handlerMemoryActivity.tv_call_info.setTextColor(Color.RED)
                            handlerMemoryActivity.tv_call_info.setText(handlerMemoryActivity.programs.get(0).getText())
                            handlerMemoryActivity.tv_call_info.startAnimation(handlerMemoryActivity.animationIn)
                            handlerMemoryActivity.callHandler.removeMessages(UPDATE_CALL_WHAT)
                            handlerMemoryActivity.callHandler.sendEmptyMessageDelayed(UPDATE_CALL_WHAT, DELAY_TIME)
                        }
                    }

                    UPDATE_CALL_WHAT -> {
                        //有多个呼叫信息，交替显示
                        handlerMemoryActivity.curProgramIndex++
                        if (handlerMemoryActivity.curProgramIndex < handlerMemoryActivity.programs.size) {
                            handlerMemoryActivity.tv_call_info.setTextColor(Color.RED)
                            handlerMemoryActivity.tv_call_info.setText(handlerMemoryActivity.programs.get(handlerMemoryActivity.curProgramIndex).getText())
                            handlerMemoryActivity.tv_call_info.startAnimation(handlerMemoryActivity.animationIn)
                            handlerMemoryActivity.callHandler.sendEmptyMessageDelayed(UPDATE_CALL_WHAT, DELAY_TIME)
                        } else {
                            handlerMemoryActivity.curProgramIndex = 0
                            if (handlerMemoryActivity.programs.size > 0) {
                                val text: String = handlerMemoryActivity.programs.get(handlerMemoryActivity.curProgramIndex).getText()
                                if (text != handlerMemoryActivity.tv_call_info.getText().toString()) {
                                    handlerMemoryActivity.tv_call_info.setTextColor(Color.RED)
                                    handlerMemoryActivity.tv_call_info.setText(handlerMemoryActivity.programs.get(handlerMemoryActivity.curProgramIndex).getText())
                                    handlerMemoryActivity.tv_call_info.startAnimation(handlerMemoryActivity.animationIn)
                                }
                                handlerMemoryActivity.callHandler.sendEmptyMessageDelayed(UPDATE_CALL_WHAT, DELAY_TIME)
                            } else {
                                handlerMemoryActivity.tv_call_info.setTextColor(Color.WHITE)
                                handlerMemoryActivity.tv_call_info.setText("祝   您   安   康")
                                handlerMemoryActivity.tv_call_info.startAnimation(handlerMemoryActivity.animationIn)
                            }
                        }
                    }
                }
            } else {
                // 没有实例不进行操作
                showMessage("设备异常, 即将重启!")
                AppUpdateHelper.rebootDevice()
            }
        }
    }


    private fun deleteCall(callStr: String) {
        for (program in programs) {
            if (program.text == callStr) {
                programs.remove(program)
                callHandler.removeMessages(UPDATE_CALL_WHAT)
                callHandler.sendEmptyMessage(UPDATE_CALL_WHAT)
            }
        }
    }

    private fun resetPrograms() {
        val curTime = System.currentTimeMillis()
        for (program in programs) {
            if (curTime - program.time > 1800000) { //5分钟
                programs.remove(program)
                callHandler.removeMessages(UPDATE_CALL_WHAT)
                callHandler.sendEmptyMessage(UPDATE_CALL_WHAT)
                break
            }
        }
    }
}