package com.easygbs.easygbd.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.location.LocationListener
import android.location.LocationManager
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.easygbs.easygbd.R
import com.easygbs.easygbd.application.App
import com.easygbs.easygbd.common.Constant
import com.easygbs.easygbd.dao.DCon
import com.easygbs.easygbd.dao.DOpe
import com.easygbs.easygbd.dao.bean.Chan
import com.easygbs.easygbd.databinding.ActivityMainBinding
import com.easygbs.easygbd.fragment.*
import com.easygbs.easygbd.logger.Logger
import com.easygbs.easygbd.push.MediaStream
import com.easygbs.easygbd.push.PushCallback
import com.easygbs.easygbd.util.PeUtil
import com.easygbs.easygbd.util.SPHelper
import com.easygbs.easygbd.util.ScrUtil
import com.easygbs.easygbd.viewmodel.activity.MainViewModel
import com.google.zxing.client.android.Intents
import com.gyf.immersionbar.ImmersionBar
import com.journeyapps.barcodescanner.ScanOptions
import kotlinx.coroutines.*
import org.easydarwin.bus.StartRecord
import org.easydarwin.bus.StopRecord
import org.easydarwin.util.SPUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pub.devrel.easypermissions.EasyPermissions
import java.io.File

class MainActivity : BaseActivity(), EasyPermissions.PermissionCallbacks {
    var TAG: String = MainActivity::class.java.getSimpleName()
    var mSPHelper: SPHelper? = null
    var mActivityMainlandBinding: ActivityMainBinding? = null
    lateinit var mMainViewModel: MainViewModel
    var mFragmentManager: FragmentManager? = null
    var mFragmentTransaction: FragmentTransaction? = null
    var mBasicSettingsFragment: BasicSettingsFragment? = null
    var mStreamingSettingsFragment: StreamingSettingsFragment? = null
    var mChannelSettingsFragment: ChannelSettingsFragment? = null
    var mAboutFragment: AboutFragment? = null
    var curfrag: Fragment? = null
    var lastfrag: Fragment? = null
    var selectTop: Int = 0
    var selectRecord: Int = 0
    var selectAbout: Int = 0
    var mDOpe: DOpe? = null
    var width: Int = 0
    var height: Int = 0
    var mMediaStream: MediaStream? = null
    var locman: LocationManager? = null

    override fun init() {
        mActivityMainlandBinding =
            DataBindingUtil.setContentView(this@MainActivity, R.layout.activity_main)

        EventBus.getDefault().register(this)

        val mWindowManager: WindowManager = this@MainActivity.getWindowManager()
        val display = mWindowManager.defaultDisplay
        width = display.width
        height = display.height

        mFragmentManager = getSupportFragmentManager()
        mFragmentTransaction = mFragmentManager!!.beginTransaction()
        mBasicSettingsFragment = BasicSettingsFragment()
        mStreamingSettingsFragment = StreamingSettingsFragment()
        mChannelSettingsFragment = ChannelSettingsFragment()
        mAboutFragment = AboutFragment();

        mFragmentTransaction!!.add(R.id.llcontent, mBasicSettingsFragment!!)
        mFragmentTransaction!!.add(R.id.llcontent, mStreamingSettingsFragment!!)
        mFragmentTransaction!!.add(R.id.llcontent, mChannelSettingsFragment!!)
        mFragmentTransaction!!.add(R.id.llcontent, mAboutFragment!!)

        curfrag = mBasicSettingsFragment

        mFragmentTransaction!!.show(mBasicSettingsFragment!!)
        mFragmentTransaction!!.hide(mStreamingSettingsFragment!!)
        mFragmentTransaction!!.hide(mChannelSettingsFragment!!)
        mFragmentTransaction!!.hide(mAboutFragment!!)
        mFragmentTransaction!!.commit()

        mHandler.sendEmptyMessage(Constant.REQUESTPER)

        mMainViewModel = MainViewModel(App.getInstance())
        mMainViewModel.setMainActivity(this@MainActivity)
        mActivityMainlandBinding!!.mMainViewModel = mMainViewModel

        ImmersionBar.with(this).statusBarDarkFont(true).init()

        val layoutParams =
            mActivityMainlandBinding!!.lltop.layoutParams as LinearLayout.LayoutParams
        layoutParams.topMargin = ScrUtil.getStatusBarHeight(this@MainActivity)
        mActivityMainlandBinding!!.lltop.layoutParams = layoutParams


        mMainViewModel!!.run {
            selectTopItem.observe(this@MainActivity) {
                if (selectTop == it) {
                    return@observe
                }

                selectTop = it

                mFragmentTransaction = mFragmentManager!!.beginTransaction()
                mFragmentTransaction!!.hide(curfrag!!)

                when (it) {
                    0 -> {
                        mActivityMainlandBinding!!.tvtopfrist.typeface = Typeface.DEFAULT_BOLD


                        mActivityMainlandBinding!!.vtopfirst.visibility = View.VISIBLE

                        mActivityMainlandBinding!!.tvtopsecond.typeface = Typeface.DEFAULT
                        mActivityMainlandBinding!!.vtopsecond.visibility = View.INVISIBLE

                        mActivityMainlandBinding!!.tvtopthird.typeface = Typeface.DEFAULT
                        mActivityMainlandBinding!!.vtopthird.visibility = View.INVISIBLE


                        mActivityMainlandBinding!!.tvtopfrist.setTextColor(Color.parseColor("#545a58"))
                        mActivityMainlandBinding!!.tvtopsecond.setTextColor(Color.parseColor("#FF595959"))
                        mActivityMainlandBinding!!.tvtopthird.setTextColor(Color.parseColor("#FF595959"))

                        isshowbottomObservableField.set(true)


                        curfrag = mBasicSettingsFragment
                        mFragmentTransaction!!.show(mBasicSettingsFragment!!)

                        mStreamingSettingsFragment!!.mStreamingSettingsViewModel!!.init()
                    }

                    1 -> {
                        mActivityMainlandBinding!!.tvtopfrist.typeface = Typeface.DEFAULT
                        mActivityMainlandBinding!!.vtopfirst.visibility = View.INVISIBLE

                        mActivityMainlandBinding!!.tvtopsecond.typeface = Typeface.DEFAULT_BOLD
                        mActivityMainlandBinding!!.vtopsecond.visibility = View.VISIBLE

                        mActivityMainlandBinding!!.tvtopthird.typeface = Typeface.DEFAULT
                        mActivityMainlandBinding!!.vtopthird.visibility = View.INVISIBLE


                        mActivityMainlandBinding!!.tvtopfrist.setTextColor(Color.parseColor("#FF595959"))
                        mActivityMainlandBinding!!.tvtopsecond.setTextColor(Color.parseColor("#545a58"))
                        mActivityMainlandBinding!!.tvtopthird.setTextColor(Color.parseColor("#FF595959"))



                        isshowbottomObservableField.set(false)

                        curfrag = mStreamingSettingsFragment

                        mFragmentTransaction!!.show(mStreamingSettingsFragment!!)

                        mStreamingSettingsFragment!!.mStreamingSettingsViewModel!!.init()
                    }

                    2 -> {
                        mActivityMainlandBinding!!.tvtopfrist.typeface = Typeface.DEFAULT
                        mActivityMainlandBinding!!.vtopfirst.visibility = View.INVISIBLE

                        mActivityMainlandBinding!!.tvtopsecond.typeface = Typeface.DEFAULT
                        mActivityMainlandBinding!!.vtopsecond.visibility = View.INVISIBLE

                        mActivityMainlandBinding!!.tvtopthird.typeface = Typeface.DEFAULT_BOLD
                        mActivityMainlandBinding!!.vtopthird.visibility = View.VISIBLE

                        mActivityMainlandBinding!!.tvtopfrist.setTextColor(Color.parseColor("#FF595959"))
                        mActivityMainlandBinding!!.tvtopsecond.setTextColor(Color.parseColor("#FF595959"))
                        mActivityMainlandBinding!!.tvtopthird.setTextColor(Color.parseColor("#545a58"))

                        isshowbottomObservableField.set(false)

                        curfrag = mChannelSettingsFragment

                        mFragmentTransaction!!.show(mChannelSettingsFragment!!)

                        mStreamingSettingsFragment!!.mStreamingSettingsViewModel!!.init()
                    }
                }

                mFragmentTransaction!!.commit()
            }
        }

        mMainViewModel!!.run {
            selectBottomItem.observe(this@MainActivity) {
                handlerActive();
                when (it) {
                    0 -> {
                        try {
                            if (mMediaStream != null) {
                                if (!mMediaStream!!.isStreaming()) {
                                    mActivityMainlandBinding!!.ivbottomfirst.setBackgroundResource(R.mipmap.ic_reg)
                                    mActivityMainlandBinding!!.tvbottomfirst.setTextColor(
                                        this@MainActivity.resources.getColor(
                                            R.color.color_01c9a7
                                        )
                                    )
                                } else {
                                    mActivityMainlandBinding!!.ivbottomfirst.setBackgroundResource(R.mipmap.ic_unreg)
                                    mActivityMainlandBinding!!.tvbottomfirst.setTextColor(
                                        this@MainActivity.resources.getColor(
                                            R.color.color_808080
                                        )
                                    )
                                }
                            } else {
                                mActivityMainlandBinding!!.ivbottomfirst.setBackgroundResource(R.mipmap.ic_unreg)
                                mActivityMainlandBinding!!.tvbottomfirst.setTextColor(
                                    this@MainActivity.resources.getColor(
                                        R.color.color_808080
                                    )
                                )
                            }

                            mFragmentTransaction = mFragmentManager!!.beginTransaction()
                            mFragmentTransaction!!.hide(curfrag!!)
                            curfrag = mBasicSettingsFragment
                            mFragmentTransaction!!.show(mBasicSettingsFragment!!)
                            mFragmentTransaction!!.commit()

                            mActivityMainlandBinding!!.lltop.visibility = View.VISIBLE

                            selectRecord = 0
                            mActivityMainlandBinding!!.ivbottomsecond.setBackgroundResource(R.mipmap.ic_notselectrec)
                            mActivityMainlandBinding!!.tvbottomsecond.setTextColor(
                                this@MainActivity.resources.getColor(
                                    R.color.color_808080
                                )
                            )
                            selectAbout = 0
                            mActivityMainlandBinding!!.ivbottomthird.setBackgroundResource(R.mipmap.ic_notselectabout)
                            mActivityMainlandBinding!!.tvbottomthird.setTextColor(
                                this@MainActivity.resources.getColor(
                                    R.color.color_808080
                                )
                            )

                        } catch (e: Exception) {
                            Log.e(TAG, "selectBottomItem 0  Exception  " + e.toString())
                        }
                    }

                    1 -> {
                        record()
                    }

                    2 -> {
                        about()
                    }
                }
            }
        }
    }

    fun handlerActive() {
        mActivityMainlandBinding!!.ivbottomsecond.setBackgroundResource(R.mipmap.ic_notselectrec)
        mActivityMainlandBinding!!.tvbottomsecond.setTextColor(
            this@MainActivity.resources.getColor(
                R.color.color_808080
            )
        )
        mActivityMainlandBinding!!.ivbottomthird.setBackgroundResource(R.mipmap.ic_notselectabout)
        mActivityMainlandBinding!!.tvbottomthird.setTextColor(
            this@MainActivity.resources.getColor(
                R.color.color_808080
            )
        )
    }

    fun record() {
        // 使用协程在主线程启动任务
        CoroutineScope(Dispatchers.Main).launch {
            // 切换到后台线程执行停止录制操作
            withContext(Dispatchers.IO) {
                mMediaStream!!.stopRecord()  // 假设这是耗时操作
            }
            // 停止录制后在主线程更新 UI 和启动新活动
            mBasicSettingsFragment!!.mFragmentBasicsettingsBinding.startRecordBtn.setImageResource(R.mipmap.record_default)

            mActivityMainlandBinding!!.ivbottomsecond.setBackgroundResource(R.mipmap.ic_selectrec)
            mActivityMainlandBinding!!.tvbottomsecond.setTextColor(
                this@MainActivity.resources.getColor(
                    R.color.color_01c9a7
                )
            )

            val intent = Intent(this@MainActivity, RecordListActivity::class.java)

            startActivityForResult(intent, Constant.RECORD_BACK);
        }
    }

    fun about() {
        if (selectAbout == 0) {
            selectAbout = 1
            mActivityMainlandBinding!!.ivbottomthird.setBackgroundResource(R.mipmap.ic_selectabout)
            mActivityMainlandBinding!!.tvbottomthird.setTextColor(
                this@MainActivity.resources.getColor(
                    R.color.color_01c9a7
                )
            )

            mFragmentTransaction = mFragmentManager!!.beginTransaction()
            mFragmentTransaction!!.hide(curfrag!!)
            lastfrag = curfrag
            curfrag = mAboutFragment

            mFragmentTransaction!!.show(mAboutFragment!!)

            mFragmentTransaction!!.commit()

            mActivityMainlandBinding!!.lltop.visibility = View.GONE

            mAboutFragment!!.show()
        } else {
            selectAbout = 0
            mActivityMainlandBinding!!.ivbottomthird.setBackgroundResource(R.mipmap.ic_notselectabout)
            mActivityMainlandBinding!!.tvbottomthird.setTextColor(
                this@MainActivity.resources.getColor(
                    R.color.color_808080
                )
            )

            mActivityMainlandBinding!!.lltop.visibility = View.VISIBLE

            mFragmentTransaction = mFragmentManager!!.beginTransaction()
            mFragmentTransaction!!.hide(curfrag!!)

            curfrag = mBasicSettingsFragment

            mFragmentTransaction!!.show(curfrag!!)

            mFragmentTransaction!!.commit()

            mBasicSettingsFragment!!.initCamera()
        }
    }

    var loclis = LocationListener { location ->
        if (location == null) {
            return@LocationListener
        }
//        Toast.makeText(
//            this@MainActivity,
//            "" + location.longitude + "  " + location.latitude,
//            Toast.LENGTH_LONG
//        ).show()
        SPUtil.setLongitude(this@MainActivity, "" + location.longitude)
        SPUtil.setLatitude(this@MainActivity, "" + location.latitude)

        try {
            if (mMediaStream!! != null) {
                if (mMediaStream!!.isStreaming()) {
                    val isenlocreport = SPUtil.getIsenlocreport(this@MainActivity)
                    if (isenlocreport == 1) {
                        val mDOpe = DOpe.Instance(
                            this@MainActivity,
                            this@MainActivity.getExternalFilesDir(null)!!
                                .getAbsolutePath() + File.separator + Constant.DIR
                        )
                        val ChanListLocal =
                            mDOpe.OperaDatabase(DCon.Chanqueryeffect, "") as List<Chan>
                        if (ChanListLocal.size >= 1) {
                            for (i in ChanListLocal.indices) {
                                mMediaStream!!.setLoLa(i, location.longitude, location.latitude);
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "loclis  Exception  " + e.toString())
        }
    }

    fun Data() {
        locman = this.getSystemService(LOCATION_SERVICE) as LocationManager
        startLoc()

        var num: Long = mDOpe!!.OperaDatabase(DCon.Chanqueryct, "") as Long
        if (num == 0L) {
            val mChan = Chan()
            mChan.ec = 1
            mChan.uid = 1
            mChan.cid = "34020000001310000001"
            mChan.na = "channel1"
            mChan.sta = 1
            ChanIn(mChan)
        }

        mChannelSettingsFragment!!.showChannels()
    }

    fun Chanjudinsert(mChan: Chan?): Boolean {
        return mDOpe!!.OperaDatabase(DCon.Chanjudinsert, mChan) as Boolean
    }

    fun ChanIn(mChan: Chan?): Boolean {
        val Chanjudinsert = Chanjudinsert(mChan)
        return if (Chanjudinsert) {
            inChecChan()
            val Chaninsert = mDOpe!!.OperaDatabase(DCon.Chaninsert, mChan) as Boolean
            if (!Chaninsert) {
                Constant.ChanID--
                mSPHelper!!.put("chanid", Constant.ChanID.toString())
                if (Constant.ChanID == Constant.ChanM) {
                    Constant.ChanF = 1
                    mSPHelper!!.put("chanf", Constant.ChanF.toString())
                    Constant.ChanID = 0
                    mSPHelper!!.put("chanid", Constant.ChanID.toString())
                }
                false
            } else {
                if (Constant.ChanID == Constant.ChanM) {
                    Constant.ChanF = 1
                    mSPHelper!!.put("chanf", Constant.ChanF.toString())
                    Constant.ChanID = 0
                    mSPHelper!!.put("chanid", Constant.ChanID.toString())
                }
                true
            }
        } else {
            false
        }
    }

    fun inChecChan() {
        var chanid = mSPHelper!!.get("chanid", "") as String
        if (chanid == "") {
            val ct = mDOpe!!.OperaDatabase(DCon.Chanqueryct, "0") as Long
            if (ct == Constant.ChanM.toLong()) {
                chanid = "0"
                mSPHelper!!.put("chanid", chanid)
            } else {
                chanid = ct.toString()
                mSPHelper!!.put("chanid", chanid)
            }
        }
        Constant.ChanID = chanid.toInt()
        var chanf = mSPHelper!!.get("chanf", "") as String
        if (chanf == "") {
            val RecordCount = mDOpe!!.OperaDatabase(DCon.Chanqueryct, "0") as Long
            if (RecordCount == Constant.ChanM.toLong()) {
                chanf = "1"
                Constant.ChanF = chanf.toInt()
                mSPHelper!!.put("chanf", chanf)
            } else {
                chanf = "0"
                Constant.ChanF = chanf.toInt()
                mSPHelper!!.put("chanf", chanf)
            }
        }
        Constant.ChanF = chanf.toInt()
        if (Constant.ChanF == 0) {
            if (Constant.ChanID >= 1) {
                val mChan =
                    mDOpe!!.OperaDatabase(DCon.Chanqueryrow, Constant.ChanID) as Chan
                if (mChan == null) {
                    Constant.ChanID--
                }
            }
            Constant.ChanID++
            mSPHelper!!.put("chanid", Constant.ChanID.toString())
        } else {
            Constant.ChanID++
            mSPHelper!!.put("chanid", Constant.ChanID.toString())
        }
    }

    override fun Pergran(requestCode: Int) {
        super.Pergran(requestCode)
        when (requestCode) {
            PeUtil.STORAGE -> {
                Send(Constant.TOINIT, "")

                var has: Boolean =
                    PeUtil.ishasPer(this@MainActivity, Manifest.permission.CAMERA)
                if (!has) {
                    PeUtil.requestPer(this@MainActivity, PeUtil.CAMERA)
                }
            }

            PeUtil.CAMERA -> {
                var has: Boolean =
                    PeUtil.ishasPer(this@MainActivity, Manifest.permission.RECORD_AUDIO)
                if (!has) {
                    PeUtil.requestPer(this@MainActivity, PeUtil.RECORDAUDIO)
                }
            }

            PeUtil.RECORDAUDIO -> {
                mBasicSettingsFragment!!.mHandler.sendEmptyMessage(Constant.OPENCAMERA);

                var has: Boolean =
                    PeUtil.ishasPer(this@MainActivity, Manifest.permission.INTERNET)
                if (!has) {
                    PeUtil.requestPer(this@MainActivity, PeUtil.INTERNET)
                } else {
                    PeUtil.requestPer(this@MainActivity, PeUtil.LOC)
                }
            }

            PeUtil.LOC -> {
                val isen: Boolean = locman!!.isProviderEnabled(LocationManager.GPS_PROVIDER)
                if (!isen) {
                    val i = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    this@MainActivity.startActivity(i)
                }

                startLoc()
            }
        }
    }

    fun startLoc() {
        var locationfreq: Long = ("" + SPUtil.getLocationfreq(this@MainActivity)).toLong()
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            locman!!.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,
                locationfreq * 1000,
                0f,
                loclis
            )
            locman!!.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                locationfreq * 1000,
                0f,
                loclis
            )
        }
    }

    override fun Perteden(v: String) {
        super.Perteden(v)
    }

    override fun Perpeden(v: String) {
        super.Perpeden(v)

    }

    override fun onStart() {
        super.onStart()
    }

    override fun onRestart() {
        super.onRestart()
        mBasicSettingsFragment!!.initCamera()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (mMediaStream != null) {
            if (mMediaStream!!.isStreaming) {
                mMediaStream!!.stopStream()
            }

            mMediaStream!!.stopPreview()
            mMediaStream!!.destroyCamera()
        }

        mBasicSettingsFragment!!.destroyService()

        stopLoc()
    }

    fun stopLoc() {
        locman!!.removeUpdates(loclis)
    }

    fun Dir() {
        Thread {
            mSPHelper = SPHelper.instance(this@MainActivity)

            mDOpe = DOpe.Instance(
                this@MainActivity,
                this@MainActivity.getExternalFilesDir(null)!!
                    .getAbsolutePath() + File.separator + Constant.DIR
            )

            Constant.Root = mSPHelper?.get(Constant.ROOT, "") as String?
            if (Constant.Root.equals("")) {
                Constant.Root = this@MainActivity.getExternalFilesDir(null)!!
                    .getAbsolutePath() + File.separator + Constant.DIR
                mSPHelper?.put(Constant.ROOT, Constant.Root)

                val rootdir: File = File(Constant.Root)
                if (!rootdir.exists()) {
                    rootdir.mkdirs()
                }
            }

            Constant.de = mSPHelper?.get(Constant.DE, "") as String?
            if (Constant.de.equals("")) {
                Constant.de = Constant.Root.toString() + "/de"
                mSPHelper?.put(Constant.DE, Constant.de)
                val ddir: File = File(Constant.de)
                if (!ddir.exists()) {
                    ddir.mkdirs()
                }
            }

            try {
                Thread.sleep(200)
            } catch (e: Exception) {
                Log.e(TAG, "Exception  $e")
            }

            Send(Constant.DATA, "")
        }.start()
    }

    fun Send(args: Int, info: String?) {
        val msg = Message()
        msg.what = args
        msg.obj = info
        mHandler.sendMessage(msg)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(eventBase: Any?) {
        if (eventBase is StartRecord) {

        } else if (eventBase is StopRecord) {

        } else if (eventBase is PushCallback) {
            PushCallback(eventBase as PushCallback)
        }
    }

    fun PushCallback(mPushCallback: PushCallback) {
        // 记录不同等级的日志
        if (mPushCallback!!.code == 3) {
            Logger.getInstance().error(mPushCallback!!.name)
            Toast.makeText(this@MainActivity, mPushCallback!!.name, Toast.LENGTH_LONG).show()
        } else if (mPushCallback!!.code == 4) {
            Logger.getInstance().debug(mPushCallback!!.name)
            Toast.makeText(this@MainActivity, mPushCallback!!.name, Toast.LENGTH_LONG).show()
        } else {
            Logger.getInstance().debug(mPushCallback!!.name)
        }
    }

    fun getSPHelper(): SPHelper? {
        if (mSPHelper == null) {
            mSPHelper = SPHelper.instance(this@MainActivity)
        }
        return mSPHelper!!
    }

    fun toSc() {
        var per: Boolean = PeUtil.ishasPer(this@MainActivity, Manifest.permission.CAMERA)
        if (per) {
            val options = ScanOptions()
            options.setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES)
            options.setPrompt("")
            options.setCameraId(0)
            options.setBeepEnabled(true)
            options.setBarcodeImageEnabled(true)
            options.setOrientationLocked(false)
            options.setBeepEnabled(false)
            val a: Class<*> = options.getCaptureActivity()
            val i: Intent = Intent(this@MainActivity, a)
            i.putExtra(Intents.Scan.CAMERA_ID, 0)
            i.putExtra(Intents.Scan.BEEP_ENABLED, true)
            i.putExtra(Intents.Scan.PROMPT_MESSAGE, "")
            this@MainActivity!!.startActivityForResult(i, Constant.QRCODE);
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            if (requestCode == Constant.QRCODE) {
                if (resultCode == Activity.RESULT_OK) {
                    var re: String? = data!!.getStringExtra(Intents.Scan.RESULT)
                    var re1: String = re!!.substring(re!!.indexOf("?") + 1);
                    val arr: List<String> = re1.split("&")
                    for (i in arr.indices) {
                        val item = arr[i]
                        var v = item.substring(item.indexOf("=") + 1)
                        if (item.startsWith("sipID")) {
                            mBasicSettingsFragment!!.mFragmentBasicsettingsBinding!!.etsipserverid.setText(
                                v
                            )
                        } else if (item.startsWith("sipDomain")) {
                            mBasicSettingsFragment!!.mFragmentBasicsettingsBinding!!.etsipserverdomain.setText(
                                v
                            )
                        } else if (item.startsWith("sipIP")) {
                            mBasicSettingsFragment!!.mFragmentBasicsettingsBinding!!.etsipserveraddr.setText(
                                v
                            )
                        } else if (item.startsWith("sipPort")) {
                            mBasicSettingsFragment!!.mFragmentBasicsettingsBinding!!.etport.setText(
                                v
                            )
                        } else if (item.startsWith("sipPWD")) {
                            mBasicSettingsFragment!!.mFragmentBasicsettingsBinding!!.etsippassword.setText(
                                v
                            )
                        }
                    }
                }
            } else if (requestCode == Constant.RECORD_BACK) {
                mActivityMainlandBinding!!.ivbottomsecond.setBackgroundResource(R.mipmap.ic_notselectrec)
                mActivityMainlandBinding!!.tvbottomsecond.setTextColor(
                    this@MainActivity.resources.getColor(
                        R.color.color_808080
                    )
                )

                if (selectAbout == 0) {
                    mActivityMainlandBinding!!.ivbottomthird.setBackgroundResource(R.mipmap.ic_notselectabout)
                    mActivityMainlandBinding!!.tvbottomthird.setTextColor(
                        this@MainActivity.resources.getColor(
                            R.color.color_808080
                        )
                    )
                } else {
                    mActivityMainlandBinding!!.ivbottomthird.setBackgroundResource(R.mipmap.ic_selectabout)
                    mActivityMainlandBinding!!.tvbottomthird.setTextColor(
                        this@MainActivity.resources.getColor(
                            R.color.color_01c9a7
                        )
                    )
                }

            }


        } catch (e: Exception) {
            Log.e(TAG, "onActivityResult  Exception  " + e.toString())
        }
    }

    fun goTopBaseSetting() {
        mMainViewModel.topfirst()
    }

    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                Constant.TOINIT -> Dir()
                Constant.DATA -> Data()
                Constant.REQUESTPER -> {
                    var per: Boolean = PeUtil.ishasPer(
                        this@MainActivity,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                    if (!per) {
                        PeUtil.requestPer(this@MainActivity, PeUtil.STORAGE)
                    } else {
                        Send(Constant.TOINIT, "")
                    }
                }
                Constant.CHANGEDATA -> {
                    if (mMediaStream == null) return
                    goTopBaseSetting()
                    mMediaStream!!.switchCamera(SPUtil.getCameraid(this@MainActivity))
                    mMediaStream!!.upDateAllowAudio();
                }
                Constant.CHANGE_DATA_RESTART -> {

                    mBasicSettingsFragment!!.mFragmentBasicsettingsBinding.startRecordBtn.setImageResource(
                        R.mipmap.record_default
                    )

                    CoroutineScope(Dispatchers.Main).launch {
                        goTopBaseSetting();
                        mMediaStream!!.switchCamera(SPUtil.getCameraid(this@MainActivity))
                        mMediaStream!!.stopStream();
                        mMediaStream!!.stopPreview()
                        mMediaStream!!.destroyCamera()
                        Logger.getInstance().debug("注销")
                        mBasicSettingsFragment!!.destroyService()
                        Thread.sleep(20)
                        mMediaStream = null
                        mBasicSettingsFragment!!.mHandler.sendEmptyMessageDelayed(
                            Constant.OPENCAMERA,
                            200
                        )
                        withContext(Dispatchers.IO) {
                            Thread.sleep(800)
                        }
                        mMediaStream!!.startStream(); //TODO 重新注册推流
                    }
                }
            }
        }
    }

    fun openRecordPath() {
        val intent = Intent(this, RecordListActivity::class.java)
//        intent.putExtra("key", "Hello, SecondActivity!")
        startActivity(intent)
    }

    fun dpToPx(dp: Int): Int {
        val density = this.resources.displayMetrics.density
        return (dp * density).toInt()
    }
}