package com.jld.vod.view
import android.Manifest
import android.app.PendingIntent
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.IPackageInstallObserver
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.text.InputType
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import com.google.gson.Gson
import com.jld.vod.R
import com.jld.vod.base.BaseActivity
import com.jld.vod.config.Config
import com.jld.vod.interfaces.IDownloadCallBack
import com.jld.vod.model.bean.*
import com.jld.vod.service.LatLongService
import com.jld.vod.service.MyAccessibilityService
import com.jld.vod.service.SocketService
import com.jld.vod.utils.AppUtil
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.utils.http.OkHttpDownloadUtils
import com.jld.vod.utils.http.OkHttpUtils
import com.jld.vod.view.widget.UpdateVersionDialog
import com.jld.vod.viewmodel.MainViewModel
import com.jld.vod.viewmodel.SplashViewModel
import com.tbruyelle.rxpermissions2.RxPermissions
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog.ListCallbackSingleChoice
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_splash.*
import okhttp3.Response
import java.io.File
import java.util.*


/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/6/23 17:43
 */
class SplashActivity : BaseActivity(){
    private val TAG:String = "SplashActivity"
    private var gson:Gson?= null
    //获取相关权限
    val permissions = RxPermissions(this)
//    private var progressReminder:TextView?=null
    private var  flag = false
    //private var  flagapk = true
    private lateinit var splashViewmodel: SplashViewModel
    private lateinit var mainViewModel: MainViewModel
    private var progressdialog: ProgressDialog? = null
    private var userId:Long? =null
    private var region:String? =null
    private var totalitem = 0//数据大小
    private var lenitem = 0//当前上传数据下标
    private var failitem = 0;//安装失败数量
    private var deviceSN = ""//设备序列号
    private var flagwifi = true//wifi状态
    private var flagDebug = true //检测状态
    private var timingState = false  //无WiFi连接计时状态
    private var networkFlag = false  //服务器连接状态
    private var runnableTime:Runnable?  = null //无WiFi连接计时器
    private var indexTime = 0 //无WiFi连接时间
    private var flagNoWifiState = true //是否开启没有WIFI检测
    private val mHandler =
        Handler(Handler.Callback { message ->
            when (message.what) {
                1 -> {
                    val id = message.arg1
                    val title = message.obj.toString()
                    progressdialog!!.setTitle("Downloading Map")
                    progressdialog!!.setMessage(title)
                    progressdialog!!.setProgress(id)
                    progressdialog!!.setCancelable(false)
                    progressdialog!!.setCanceledOnTouchOutside(false)
                    progressdialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                    try {
                        progressdialog!!.show()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                        progressdialog!!.dismiss()
                    }
                    if (id == 101) {
                        progressdialog!!.dismiss()
                    }
                }
                2->{
                    val id = message.arg1
                    progressdialog!!.setTitle("Downloading APK ( $lenitem/$totalitem )")
                    progressdialog!!.progress = id
                    progressdialog!!.setCancelable(false)
                    progressdialog!!.setCanceledOnTouchOutside(false)
                    progressdialog!!.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                    try {
                        progressdialog!!.show()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                        progressdialog!!.dismiss()
                    }

                    if (id == 101) {
                        progressdialog!!.dismiss()
                    }
                }
                3->{
                    //处理是否跳转设置座位界面
                    val result: String = message.obj.toString()
                    val resultData = gson!!.fromJson(result, ResultBean::class.java)
                    Log.i(TAG, "handleMessage: 当前位置设置状态$resultData")
                    SharedPrefUtils.putString(this, "flagDebug", resultData.code.toString())
                    if(resultData.flag){
                        //进入调试界面
                        flagDebug = false //停止循环
                        val intent = Intent(this,LinkageSeatSettingsActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }
                4->{
                    //数据加载提示
                    tv_splash_tips.text = message.obj.toString()

                }
                5->{
                    findGameByNoInstall()
                }
                6->{
                    val result: String = message.obj.toString()
                    val resultData = gson!!.fromJson(result, ResultBean::class.java)
                    Log.i(TAG, "网络状态$resultData")
                    if(resultData.flag){
                        // 连接成功
                        networkFlag = true
                    }
                }
            }
            false
        })
    override fun getLayoutId(): Int {
        return R.layout.activity_splash
    }

    override fun initView() {
        super.initView()
        progressdialog = ProgressDialog(this@SplashActivity)
        deviceSN =  AppUtil.getDeviceSN()

        startService(Intent(this, SocketService::class.java))

        //第一次进入标识
        SharedPrefUtils.putBoolean(this,"isFirstShowAds",true)
        //座位号显示
        val seatid = SharedPrefUtils.getString(this,"seatid")
        //欢迎提示
        if (seatid.isNotEmpty())
        {
            when(seatNumberRange(seatid.toInt())){
                1->{
                    //0-99
                    tv_splash!!.textSize = 240F
                }
                10->{
                    //100-999
                    tv_splash!!.textSize = 200F
                }
                100->{
                    //1000+
                    tv_splash!!.textSize = 140F
                }
            }
            tv_splash.text = seatid
        }
    }


    override fun initData() {
        super.initData()
        //初始化gson
        gson = Gson()


        //创建并数据源
        splashViewmodel = ViewModelProvider.AndroidViewModelFactory(application).create(SplashViewModel::class.java)
        mainViewModel = ViewModelProvider.AndroidViewModelFactory(application).create(MainViewModel::class.java)

        //如果WiFi没有连接，循环判断知道WiFi连接再请求网络
        requestWifiState()
        //初始化车辆信息
        initCarInfo()
        //初始游戏安装
        initGameInstall()
        //初始化apk更新
        initApkUpdate()
        //初始化卸载游戏
        initDelGame()

    }
    override fun initEvent() {
        super.initEvent()
        rl_splash.setOnClickListener {
            if (flag)
            {
                go<HomeActivity>()
                finish()
            }
        }
        permissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CHANGE_CONFIGURATION
        ).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Consumer<Boolean?> {
                    @Throws(Exception::class)
                    override fun accept(t: Boolean?) {
                        if (t!!) {
                            LogUtils.logD("同意")
                            //initMain()
                        } else {
                            LogUtils.logD("不同意")
                        }
                    }
                })

        if (!MyAccessibilityService.isRunning) {
            //默认开启全局返回服务
            Settings.Secure.putString(mContext.getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                    "com.jld.vod/com.jld.vod.service.MyAccessibilityService");

            Settings.Secure.putInt(mContext.getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED, 1);
            val mIntnet = Intent(mContext,MyAccessibilityService::class.java)
            startService(mIntnet)
        }
    }
    /**
     * 初始apk版本更新
     */
    private fun initApkUpdate() {
        //1.Apk更新
        var data:String? = null
        splashViewmodel.detectAppUpdatesliveData.observe(this){ res->
            ajaxInfo(getString(R.string.check_for_version_updates)+"....",null)
            LogUtils.logD("检测版本更新---$res")
            //有更新
            if(res != null) {
                data = res
                //2.请求下载apk到服务器接口
                splashViewmodel.previewAPK(res)
                //无更新
            }else{
                finishLoading()
                ajaxInfo(getString(R.string.check_whether_the_vehicle_is_bound)+"....",null)
                splashViewmodel.eqCar(this.userId!!)//检测是否绑定云
            }
        }

        //3.获取apk路径，下载更新
        splashViewmodel.previewAPKliveData.observe(this){res ->
            //有更新
            if(res == "0") {
                flag = true
                finishLoading()
                val bean = DownloadApkBean()
                bean.url = Config.ApiBaseUrl+"/$data.apk"
                UpdateVersionDialog.show(this,bean)
            }
        }
    }

    /**
     * 初始化需要安装的游戏
     */
    private fun initGameInstall() {
        Thread(Runnable {
            ajaxInfo(getString(R.string.inspection_application_welcome)+"....",null)
            try {
                val response: Response = OkHttpUtils.getInstance()
                        .getData(Config.ApiBaseUrl + "/synchronization/findGameInstalledPath/"+deviceSN)
                val res = response.body!!.string()
                val resultData = gson!!.fromJson(res, TerminalInstallBean::class.java)
                if (resultData.flag){
                    var ids:StringBuilder= StringBuilder("")
                    resultData!!.data!!.forEach {
                        if (!detectionApp(it.packname)){
                            if (ids.toString()==""){
                                ids.append(it.tiid.toString())
                            }else{
                                ids.append(",").append(it.tiid.toString())
                            }
                        }
                    }
                    if(ids.isNotEmpty()){
                        val responseDel: Response = OkHttpUtils.getInstance()
                                .getData(Config.ApiBaseUrl + "/synchronization/delGameInstalledPath/"+ids.toString())
                        val resDel = responseDel.body!!.string()
                        val resultData = gson!!.fromJson(resDel, TerminalInstallBean::class.java)
                        if(resultData.flag){
                            //放置主线程上运行
                            handlerGetGameByNoInstall()
                        }
                    }else {
                        handlerGetGameByNoInstall()
                    }
                }else{
                    handlerGetGameByNoInstall()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    /**
     * 初始化车辆信息
     */
    private fun initCarInfo() {
        //获取版本号
        val AppVersion = AppUtil.getVersionCode(this)
        /**
         * 获取系统主页静态资源
         */
        splashViewmodel.findHomePageImgliveData.observe(this){res ->
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    if (res.data != null) {
                        SharedPrefUtils.putString(this, "main_bg_img", res.data.main_bg_img)
                        SharedPrefUtils.putString(this, "main_close_btn", res.data.main_close_btn)
                        SharedPrefUtils.putString(this, "main_logo", res.data.main_logo)
                        ajaxInfo(getString(R.string.resource_loaded_successfully)+"....",null)
                    }
                }
                BaseBean.ERROR -> {
                }
                BaseBean.LOADING -> {
                    showLoading()
                }
            }
        }


        /**
         * 初始化全部语言
         */
        splashViewmodel.findLanguageAllliveData.observe(this){ res ->
            ajaxInfo(getString(R.string.load_language)+"....",null)
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    if (res.data != null) {
                        var languageLid:String?= null
                        //获取缓存
                        var languageId = SharedPrefUtils.getString(this,"language_lid")
                        LogUtils.logD("languageId:$languageId" )
                        //判断缓存值
                        if (languageId.isNotEmpty()){
                            //存在值
                            res.data.forEach(){
                                if (languageId.equals(it.lid)){
                                    languageLid = it.name
                                }
                            }
                        }else{
                            SharedPrefUtils.putString(this, "language_lid", res.data!![0].lid.toString())//缓存语言id
                            languageLid = res.data!![0].name
                        }
                        if (!languageLid.isNullOrEmpty()) {//切换本地语言
                            try {
                                val country = languageLid!!.split("_")
                                LogUtils.logD("language_lid" + country[0] + "==" + country[1])
                                val locale = Locale(country[0], country[1])
                                updateLocale(locale)
                            } catch (e: Exception) {
                                LogUtils.logD("language_lid初始化语言成功:$languageLid" )
                                e.printStackTrace()
                            }
                        }
                    }
                }
                BaseBean.ERROR -> {
                    loaderror(false)//弹框设置 点击取消不回调
                    flag = false
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }



        /**
         * 1.检测APP是否有更新（与云服务器交互）detectAppUpdates
         * 2.下载云apk到本地服务器（与云服务器交互）previewAPK
         * 3.获取本地apk文件流previewAPKByteByLocal
         */
        //车辆信息
        splashViewmodel.carInfoliveData.observe(this){ res ->
            ajaxInfo(getString(R.string.Load_vehicle_information)+"....",null)
            if (res.data != null)
            {
                Log.i(TAG, "initData: 获取车辆信息成功！")
                SharedPrefUtils.putString(this,"carNum",res.data[0].carNum)
                this.region = res.data[0].region
                SharedPrefUtils.putString(this,"region",region)//将车辆地区存入缓存
                SharedPrefUtils.putString(this,"newDate",res.data[0].updateTime)
                Thread(Runnable {
                    try {
                        val response: Response = OkHttpUtils.getInstance()
                                .getData(Config.ApiBaseUrl + "/user")
                        val resData = response.body!!.string()

                        val resultData = gson!!.fromJson(resData, UserBean::class.java)
                        this.userId = resultData[0].userId
                        mainViewModel.findModularAll(this.userId!!)//获取全部模块
                        Log.i(TAG, "initData: 版本信息！$AppVersion")
                        splashViewmodel.detectAppUpdates(this.userId!!,AppVersion)//检测apk更新
//                        LogUtils.logD("获取用户信息$"+this.userId)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }).start()

            }
        }

        /**
         * 获取未绑定的车辆
         */
        splashViewmodel.findCarByUnboundliveData.observe(this){ res ->
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    LogUtils.logD("返回数据:$res")
                    if (!res.data.isNullOrEmpty()){
                        // 创建MutableList可以继续添加修改元素
                        var carid: MutableList<String> = mutableListOf()
                        for (datas in res.data!!) {
                            carid.add(0,datas.carNum)
                        }
                        //弹出绑定车辆对话框
                        showDialogCarList(carid, res.data)
                    }else{
                        ajaxInfo(getString(R.string.no_vehicle)+"....",null)
                    }
                }
                BaseBean.ERROR -> {
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
        /**
         * 判断是否绑定
         */
        //检测车辆是否绑定
        splashViewmodel.eqCarliveData.observe(this){res->
            if (res == "20000") {
                ajaxInfo(getString(R.string.detection_map)+"....",null)
                //本地如果没有地图则下载地图
                val mapFile = File(getExternalFilesDir(null), region + ".map")
                Log.i(TAG, "eqCarliveData: 地图地址:"+mapFile.path)
                if (!mapFile.exists()) {
                    ajaxInfo(getString(R.string.download_map)+"....",null)
                    initDownloadMap(mapFile)
                }else{
                    //地图存在,获取未安装的apk
                    ajaxInfo(getString(R.string.map_loaded_successfully)+"....",null)
                    Log.i(TAG, "eqCarliveData: 进入游戏未安装检测:"+mapFile.path)
                    splashViewmodel.findGameByNoInstall(deviceSN)
                }
            }
        }
    }

    /**
     * 无网络跳转设置
     * @param tmp  点击取消是否回调  [true 回调 | false 不回调]
     */
    private fun loaderror(tmp:Boolean) {

        MaterialDialog.Builder(this)
            .title("Password")
            .inputType(
                InputType.TYPE_CLASS_TEXT
                        or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                        or InputType.TYPE_TEXT_FLAG_CAP_WORDS
            )
            .input("Please enter your password", "", false,
                MaterialDialog.InputCallback { _: MaterialDialog?, input: CharSequence ->
                    if (input.toString() == Config.pwd) {
                        val mIntent = Intent(applicationContext, SettingsActivity::class.java)
                        mIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        startActivity(mIntent)
                        this.finish()
                    }else{
                        loaderror(tmp)
                        Toast.makeText(this,"PassWord Error",Toast.LENGTH_LONG).show()
                    }
                }
            )
            .inputRange(5, 10)
            .onNegative(MaterialDialog.SingleButtonCallback { _, _ ->
                run {
                    if (tmp) {
                        loaderror(tmp)
                    }else{
                        //刷新当前
                        refresh()
                    }
                }
            })
            .positiveText("Confirm")
            .negativeText("Cancel")
            .cancelable(false)
            .show()
    }

    /**
     * 下载安装游戏
     */
    private fun DownloadInstallApk( apkUrl:String,gid:Long) {

        val targetFile = File(this.getFilesDir(), apkUrl)

        OkHttpDownloadUtils.getInstance()
            .download(Config.ApiBaseUrl+"/"+apkUrl, targetFile, object : IDownloadCallBack {
                override fun success(apkfile: File) {
                    //获取包名
                    val packname =  AppUtil.getApkPackName(applicationContext,apkfile.absolutePath)

                    lenitem++
                    LogUtils.logD("apk"+apkfile.absolutePath)
                    val msg = Message()
                    msg.what = 2
                    msg.arg1 = 101
                    msg.obj = "installing apk"
                    mHandler.sendMessage(msg)

                    InstallGame( apkfile.absolutePath,packname,gid)

                    ajaxInfo(getString(R.string.download_games1)+getString(R.string.sum_total)+totalitem+getString(R.string.download_games2)+"${(totalitem-lenitem)}" + getString(R.string.fail_sum)+failitem,null)

                  //  val mPm = mContext.packageManager
                    //val isOk = SilentInstall.silentInstall(mPm, apkfile.absolutePath)

                    //  LogUtils.logD("安装状态"+isOk)
                    // val isOk = SilentInstall.install(apkfile.absolutePath)


                }
                override fun progress(progress: Int) {

                    val msg = Message()
                    msg.what = 2
                    msg.arg1 = progress
                    mHandler.sendMessage(msg)
                }

                override fun failed(throwable: Throwable) {
                    LogUtils.logE(TAG, "下载apk失败")
                    val msg = Message()
                    msg.what = 2
                    msg.arg1 = 101
                    msg.obj = "installing apk"
                    mHandler.sendMessage(msg)
                    lenitem++
                    failitem++
                    ajaxInfo(getString(R.string.download_games1)+getString(R.string.sum_total)+totalitem+getString(R.string.download_games2) +"${(totalitem-lenitem)}"+ getString(R.string.fail_sum)+failitem,null)

                    LogUtils.logD("lenitem$lenitem==$totalitem")
                    if (lenitem == totalitem)
                    {
                        lenitem = 0
                        totalitem = 0
                        splashViewmodel.getNuInstallGame(deviceSN)//开始卸载游戏
                    }
                }
            })
    }
    /**
     * 通知主线程获取未安装apk
     */
    fun handlerGetGameByNoInstall(){
        val msg = Message()
        msg.what = 5
        mHandler.sendMessage(msg)
    }
    /**
     * 获取未安装apk
     */
    fun findGameByNoInstall(){
        splashViewmodel.findGameByNoInstallliveData.observe(this){ res->
            ajaxInfo(getString(R.string.get_no_app_installed)+"....",null)
            when (res?.code) {
                BaseBean.SUCCESS -> {
                    LogUtils.logD("走到这")
                    val list = res.data
                    if(list!!.size != 0) {
                        totalitem = res.data.size//总共待安装的数组数量
                        LogUtils.logD("GameObserver安装数$totalitem")
                        val apkFile = File(this.getFilesDir(),"")
                        if (apkFile.exists())
                        {
                            if (AppUtil.deleteDir(apkFile))
                            {
                                LogUtils.logD("游戏包缓存清空")
                            }else{
                                LogUtils.logD("游戏包清空失败")
                            }
                        }
                        for ((index ,e)in list.withIndex())
                        {
                            DownloadInstallApk(e.apkUrl,e.gid)
                        }

                    }else{

                        splashViewmodel.getNuInstallGame(deviceSN)//开始卸载游戏
//                        ajaxInfo(getString(R.string.data_loading_successfully)+"...",null)
//                        Thread(Runnable {
//                            Thread.sleep(1500)
//                            ajaxInfo(getString(R.string.welcometext),null)
//                        }).start()
                    }
                }
                BaseBean.ERROR -> {
                    loaderror(false)//弹框设置 点击取消不回调
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }

    /**
     * 卸载游戏
     */
    private fun initDelGame() {
        LogUtils.logD("开始卸载游戏")

        splashViewmodel.NuInstallGameLiveData.observe(this) { res ->
            ajaxInfo(getString(R.string.del_game)+"....",null)
            when (res?.code) {
                BaseBean.SUCCESS -> {

                    var delnum = 0
                    if (!res.data.isNullOrEmpty()){
                        LogUtils.logD("res"+res.data)
                        for (datas in res.data) {
                            val isDelPackName = quietUnInstallApk(datas.packName)
                            delnum++
                            if (isDelPackName)
                            {
                                //卸载成功，请求接口删除数据
                                splashViewmodel.delInstallPath(datas.tid.toString())
                            }
                            //卸载完成，进入欢迎模式
                            if (delnum == res.data.size)
                            {
                                flag = true
                                ajaxInfo(getString(R.string.welcometext),null)
                            }
                        }

                    }else{
                        flag = true
                        ajaxInfo(getString(R.string.welcometext)+"....",null)
                    }
                }
                BaseBean.ERROR -> {
                    flag = true
                    ajaxInfo(getString(R.string.welcometext)+"....",null)
                    Toast.makeText(this, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
    }



    /**
     * 弹出绑定车辆对话框
     */
    fun showDialogCarList(data: MutableList<String>, data1: List<FindCarByUnboundBean>) {
        MaterialDialog.Builder(this)
            .title("Select")
            .items(data)
            .canceledOnTouchOutside(false)
            .itemsCallbackSingleChoice(
                0,
                ListCallbackSingleChoice { dialog: MaterialDialog?, view: View?, which: Int, text: CharSequence ->
                    splashViewmodel.binding(data1[which].ciId)
                    flag = true
                    refresh()//刷新
                    true // allow selection
                })
            .positiveText("Confirm")
            .negativeText("Cancel")
            .show()
    }

    /**
     * 刷新
     */
    private fun refresh() {
        finish()
        val intent = Intent(this, SplashActivity::class.java)
        startActivity(intent)
    }

    fun detectionApp(packageName:String):Boolean{
        val manager = this.packageManager
        val launchIntentForPackage = manager.getLaunchIntentForPackage(packageName)
        return launchIntentForPackage != null
    }

    /**
     * 下载map文件
     * @param mapFile
     * @param MAP_FILE
     */
    private fun initDownloadMap(mapFile: File) {
        LogUtils.logD("下载地图")
        OkHttpUtils.getInstance()
            .download(Config.ApiBaseUrl+"/"+region+".map", mapFile, object : IDownloadCallBack {
                override fun success(apkfile: File) {
                   // Log.i("splash", "mapfile=" + apkfile.absolutePath)
                    val msg = Message()
                    msg.what = 1
                    msg.arg1 = 101
                    msg.obj = "checking map package"
                    mHandler.sendMessage(msg)
                    //地图下载完成,获取未安装的apk
                    ajaxInfo(getString(R.string.map_download_successfully)+"....",null)
                    splashViewmodel.findGameByNoInstall(deviceSN)
                }

                override fun progress(progress: Int) {
                    val msg = Message()
                    msg.what = 1
                    msg.arg1 = progress
                    msg.obj = mapFile.absolutePath
                    mHandler.sendMessage(msg)
                    if (progress < -1)
                    {
                        if (mapFile.exists()) {
                            mapFile.delete()
                        }
                    }
                }
                override fun failed(throwable: Throwable) {
                    throwable.printStackTrace()
                    if (mapFile.exists()) {
                        mapFile.delete()
                    }
                }
            })
    }

    /**
     * 检查wifi是否处开连接状态
     * @return
     */
     fun isWifiConnect() {
        //请求服务器
        Thread(Runnable {
            try {
                val response: Response = OkHttpUtils.getInstance()
                    .getData(Config.ApiBaseUrl + "/sys/HQ")
                val res = response.body!!.string()
                val msg = Message()
                msg.what = 6
                msg.obj = res
                mHandler.sendMessage(msg)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()

//        请求成功返回true


//        if (Config.Breed){
//            //有线VOD不检测WIFI
//            return true
//        }
//        val connManager: ConnectivityManager? = this.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
//        val mWifiInfo: NetworkInfo = connManager!!.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
//        return mWifiInfo.isConnected()
    }

    /**
     * 切换语言
     */
    protected fun updateLocale(locale: Locale?) {
        try {
            val config = this.resources.configuration
            val dm = resources.displayMetrics
            config.locale = locale
            resources.updateConfiguration(config, dm)
            //  recreate()
        } catch (e: Exception) {
            // Intentionally left blank
        }
    }

    //页面关闭执行此方法
    override fun finish() {
        super.finish()
        mHandler.removeCallbacksAndMessages(null)
    }
    //加载数据项提示
    fun  ajaxInfo(message:String,schedule:Int?){
        val msg = Message()
        msg.what = 4
        msg.obj = message
        mHandler.sendMessage(msg)
    }

    /**
     * 获取当前座位号范围
     */
    private fun seatNumberRange(sid:Int):Int{
        if (sid<100) return 1
        if (sid in 100..999) return 10
        return 100
    }

    /**
     * 心跳请求wifi状态
     */
    private fun requestWifiState() {
        mHandler.postDelayed(Runnable {
            //  LogUtils.logD("isWifiConnect"+isWifiConnect())
            if (flagwifi) {
                ajaxInfo(getString(R.string.internet_connection)+"....",null)
                isWifiConnect()
                if (networkFlag) {//wifi状态  isWifiConnect()
                    //调用方法
                    offNoWiFiConnectionTiming()//关闭计时
                    splashViewmodel.findLanguageAll()
                    splashViewmodel.getCarInfo()
                    splashViewmodel.getCarRunInfo()
                    splashViewmodel.findHomePageImg()
                    finishLoading()
                    flagwifi = false
                    getDebugStatus(deviceSN)

                } else {
                    //重新调用
                    requestWifiState()
                    onNoWiFiConnectionTiming()//开启计时
                    showLoading()
                }
            }
        }, 1500)
    }
    /**
     * 开启无WiFi连接计时
     */
    private fun onNoWiFiConnectionTiming(){
        if (!timingState && flagNoWifiState){//未开启--开启定时
            timingState = true  //开启计时状态
            LogUtils.logD("没有WIFI计时：开始计时")
            noWifiTimer()//计时
        }else{// 已开启 检测时间
            if (indexTime>180){//时间大于180S--开启密码框
                //弹窗
                flagNoWifiState = false
                LogUtils.logD("没有WIFI计时： 关闭计时")
                offNoWiFiConnectionTiming()//关闭计时
                //弹窗
                loaderror(true)
            }
        }
    }

    /**
     * 定时器
     */
    private fun noWifiTimer(){
        runnableTime = Runnable {
            indexTime++
            LogUtils.logD("没有WIFI计时：当前计时$indexTime")
            noWifiTimer()
        }
        mHandler.postDelayed(runnableTime,1000)
    }
    /**
     * 关闭无WiFi计时
     */
    private fun offNoWiFiConnectionTiming(){
        timingState = false  //开启计时状态
        indexTime = 0  //恢复初始值
        mHandler.removeCallbacks(runnableTime)
    }

    /**
     * 循环检测进入设置座位界面--3S
     */
    private fun getDebugStatus(id:String){
        mHandler.postDelayed(Runnable {
            Thread(Runnable {
                try {
                    val response: Response = OkHttpUtils.getInstance()
                            .getData(Config.ApiBaseUrl + "/sys/getDebugStatus?id=$id")
                    val res = response.body!!.string()
                    val msg = Message()
                    msg.what = 3
                    msg.obj = res
                    mHandler.sendMessage(msg)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }).start()
            if (flagDebug){
                getDebugStatus(id)
            }
        }, 10000)
    }

    /**
     * 静默卸载 系统签名
     */
    private fun quietUnInstallApk(packagename: String):Boolean {
        try {
            val intent = Intent()
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val sender = PendingIntent.getActivity(mContext, 0, intent, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val mPackageInstaller = mContext.packageManager.packageInstaller
                mPackageInstaller.uninstall(packagename, sender.intentSender) // 卸载APK
                return true
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return false
        }
        return false
    }
    override fun onDestroy() {
        super.onDestroy()
        if (progressdialog != null)
        {
            progressdialog!!.dismiss()
        }
    }

    /**
     * 安装apk
     */
    fun InstallGame(fileName: String?, packageName: String?,gid:Long) //
    {
        if (fileName == null || fileName.length == 0) {
            return
        }

        val file =  File(fileName);
        if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
            return
        }
        val uri: Uri = Uri.fromFile(file)
        var installFlags = 0
        val pm = packageManager
        try {
            val pi: PackageInfo? = pm.getPackageInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES) //
            if (pi != null) {
                installFlags = installFlags or PackageManager.INSTALL_REPLACE_EXISTING
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        val observer = PackageInstallObserver(gid)
        pm.installPackage(uri, observer, installFlags, packageName) //下面有详细
    }

    //用于返回游戏安装状态
    inner class PackageInstallObserver(gids: Long) : IPackageInstallObserver.Stub() {
        var gid :Long = 0
        init {
            this.gid = gids
        }
        override fun packageInstalled(packageName: String?, returnCode: Int) { //如果returnCode == 1就为成功
            LogUtils.logD("GameObserver $packageName 下载完成安装完成.且更新安装状态：$returnCode")
            //是否安装成功
            if (returnCode == 1) {
                try {
                    splashViewmodel.updateGameInstallState(gid.toString(),packageName!!,deviceSN)
                }catch (e:Exception) {
                    e.printStackTrace()
                }
                if (lenitem == totalitem) {
                    lenitem = 0
                    totalitem = 0

                    splashViewmodel.getNuInstallGame(deviceSN)//开始卸载游戏
                }

            }else{
                LogUtils.logD("游戏安装失败？")
                failitem++

                if (lenitem == totalitem) {
                    lenitem = 0
                    totalitem = 0
                    splashViewmodel.getNuInstallGame(deviceSN)//开始卸载游戏

                }
            }

        }
    }
}