package com.example.chemical.ui

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.example.chemical.BuildConfig
import com.example.chemical.ChemicalApp
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivitySplashBinding
import com.example.chemical.utils.NetworkUtils
import com.example.chemical.utils.SharedPreferencesHelper
import com.example.chemical.utils.UiManager
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kongzue.dialogx.dialogs.MessageDialog
import com.lztek.toolkit.Lztek
import com.rc.core.log.RcLog
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.core.util.ApkUpdater
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.client.ApiRepository
import com.tbruyelle.rxpermissions2.RxPermissions
import java.io.File
import java.util.concurrent.ThreadLocalRandom

class SplashActivity : RcBaseActivity<ActivitySplashBinding>() {

    private var mLztek: Lztek? = null
    private var mDeviceNum: String? = null  //设备唯一标识
    private var isOk = false
    private var test: String = ""
    override fun createViewBinding() = ActivitySplashBinding.inflate(LayoutInflater.from(this))

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        requestPermission()
    }

    private fun initView() {
        viewBinding.versionName.text = "版本号：${DeviceUtils.getVersionName(this)}"
        mLztek = Lztek.create(this)
        val toUpperCase = mLztek!!.ethMac.toUpperCase()
        mDeviceNum = toUpperCase.replace(":", "")
        viewBinding.settings.setOnClickListener {
            UiManager.switcher(this, SettingActivity::class.java)
        }
//        SharedPreferencesHelper.clearBeans(this)
        val urlBase = SharedPreferencesHelper.getUrlBase(this)
        if (urlBase != null) {
            HttpConfig.API_BASE_URL = "${urlBase.a}"
            HttpConfig.API_BASE_IMG_URL = "${urlBase.b}"
            HttpConfig.API_BASE_QC_URL = "${urlBase.c}"
            if (urlBase.d != null && urlBase.d.isNotEmpty()) {
                RcLog.info("=====摄像头 ${urlBase.d.toInt()}")
                Constants.FACE_TAG = urlBase.d.toInt()
            }
        }

        val isNetworkAvailable = NetworkUtils.isNetworkAvailable(this)
        if (isNetworkAvailable) {
            // 当前网络可用
            queryAppVersion()
        } else {
            if (!isOk) {
                SPUtils.getInstance()
                    .put("interval", (ThreadLocalRandom.current().nextInt(20, 40) * 1000).toLong())
                // 启动定时任务
                myHandler.start()
                isOk = true
            }

        }
    }


    private fun requestPermission() {

        XXPermissions.with(this)
            .permission(
                Permission.CAMERA,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_PHONE_STATE,
                Permission.RECORD_AUDIO
            )
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (allGranted) {
                        initView()
                    } else {
                        MessageDialog.show("提示", "您必须同意所有权限才可以继续使用", "确定")
                            .setCancelable(false).setOkButtonClickListener { dialog, v ->
                                requestPermission()
                                false
                            }
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    super.onDenied(permissions, doNotAskAgain)
                    if (doNotAskAgain) {
                        MessageDialog.show("提示", "您必须同意所有权限才可以继续使用", "确定")
                            .setCancelable(false).setOkButtonClickListener { dialog, v ->
                                XXPermissions.startPermissionActivity(
                                    this@SplashActivity,
                                    permissions
                                )
                                false
                            }
                    } else {
                        MessageDialog.show("提示", "您必须同意所有权限才可以继续使用", "确定")
                            .setCancelable(false).setOkButtonClickListener { dialog, v ->
                                requestPermission()
                                false
                            }
                    }
                }
            })

    }

//
//    private fun queryAppVersion() {
//        showLoading("版本检测中...")
//        val toDouble = DeviceUtils.getVersionName(this)//获取当前版本号
//        val disposable = ApiRepository.apkVersion(mDeviceNum!!, 3, toDouble.toDouble())
//            .subscribe({ data ->
//                dismissLoading()
//                if (data.needUpgrade) {
//                    when {
//                        data.appInfo.remark != null -> {
//                            //同步进行更新
//                            upDownloadManager(data.appInfo.remark)
//                        }
//                        data.appInfo.url != null -> {
//                            upDownloadManager(data.appInfo.url)
//                        }
//                        else -> {
//                            // 启动定时任务
//                            try {
//                                myHandler.stop()
//                            } catch (e: Exception) {
//
//                            } finally {
//                                myHandler.start()
//                            }
//                            showToast("版本信息不不存在")
//                        }
//                    }
//                } else {
//                    UiManager.switcher(this@SplashActivity, MainActivity::class.java)
//                    finish()
//                }
//            }, { throwable ->
//                dismissLoading()
//                showNetError(throwable)
//                // 启动定时任务
//                try {
//                    myHandler.stop()
//                } catch (e: Exception) {
//
//                } finally {
//                    myHandler.start()
//                }
//            })
//        addDisposable(disposable)
//    }

    private fun queryAppVersion() {
        // TODO 安装并重启本应用
        showLoading("版本检测中...")
        val toDouble = DeviceUtils.getVersionName(this)//获取当前版本号

        //    AIO_MANAGER("aio_manager","管控一体机"),
        //    AIO_CHEMICAL("aio_chemical","化学品一体机"),
        //    AIO_INFOBORD("aio_infobord","电子信息牌"),
        //    AIO_EXAM("aio_exam","学习考试一体机");
        val disposable =
            ApiRepository.getCheck(mDeviceNum!!, "aio_chemical", toDouble.toDouble())
                .subscribe({ data ->
                    dismissLoading()
                    if (!data.needUpgrade) {
                        ChemicalApp.labInfo = data.labInfo
                        ChemicalApp.subjectId = data.labInfo.subjectId
                        ChemicalApp.subjectName = data.labInfo.subjectName
                        ChemicalApp.subRoom = data.labInfo.room
                        UiManager.switcher(this@SplashActivity, MainActivity::class.java)
                        finish()
                    } else {
                        //需要更新
                        if (data.appInfo != null) {
                            when {
                                data.appInfo!!.remark != null -> {
                                    //同步进行更新
                                    upDownloadManager(data!!.appInfo!!.remark)
                                }

                                data!!.appInfo!!.url != null -> {
                                    upDownloadManager(data.appInfo!!.url)
                                }

                                else -> {
                                    // 启动定时任务
                                    try {
                                        myHandler.stop()
                                    } catch (e: Exception) {

                                    } finally {
                                        SPUtils.getInstance()
                                            .put(
                                                "interval",
                                                (ThreadLocalRandom.current()
                                                    .nextInt(20, 40) * 1000).toLong()
                                            )
                                        myHandler.start()
                                    }
                                    showToast("版本信息不不存在")
                                }
                            }
                        } else {
                            UiManager.switcher(this@SplashActivity, MainActivity::class.java)
                            finish()
                        }
                    }
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)
                    if (!isOk) {
                        // 启动定时任务
                        SPUtils.getInstance()
                            .put(
                                "interval",
                                (ThreadLocalRandom.current().nextInt(20, 40) * 1000).toLong()
                            )
                        myHandler.start()
                        isOk = true
                    }
                })
        addDisposable(disposable)

    }


    private fun upDownloadManager(downloadUrl: String) {
        ApkUpdater(this, BuildConfig.APPLICATION_ID, callback = object :
            ApkUpdater.DownloadCallback {
            override fun onProgress(progress: Int) {
                myHandler.stop()
                showLoading("检测到新版本，开始更新（${progress}%）")
            }

            override fun onFailed(errMsg: String?) {
                dismissLoading()
                showToast("下载失败，请检查网络情况重新下载")
                // 启动定时任务
                try {
                    myHandler.stop()
                } catch (e: Exception) {

                } finally {
                    SPUtils.getInstance()
                        .put(
                            "interval",
                            (ThreadLocalRandom.current().nextInt(20, 40) * 1000).toLong()
                        )
                    myHandler.start()
                }
            }

            override fun onSuccess(apkFile: String) {
                dismissLoading()
                installApk(File(apkFile))
//                UiManager.switcher(this@SplashActivity, MainActivity::class.java)
//                finish()
            }

        }).downloadApk(downloadUrl)
    }

    private val myHandler = MyHandler {
        // 在这里执行你的业务操作
        //校验版本更新
        val isNetworkAvailable = NetworkUtils.isNetworkAvailable(this)
        if (isNetworkAvailable) {
            // 当前网络可用
            queryAppVersion()
        } else {
            // 当前网络不可用
            showToast("当前网络不可用")
        }

    }


    class MyHandler(private val callback: () -> Unit) {

        private val handler = Handler()

        //        private val interval: Long = 10 * 60 * 1000 // 10分钟


        private val runnable = object : Runnable {
            override fun run() {
                callback.invoke()
                handler.postDelayed(this, SPUtils.getInstance().getLong("interval", 10000L))
            }
        }

        fun start() {
            handler.postDelayed(runnable, SPUtils.getInstance().getLong("interval", 10000L))
        }

        fun stop() {
            handler.removeCallbacks(runnable)
            handler.removeCallbacksAndMessages(null)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止定时任务
        myHandler.stop()
    }

    /**
     * 安装应用并唤起该应用
     */
    private fun installApk(apkFile: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        if (Build.VERSION.SDK_INT >= 24) {
            // 与AndroidManifest.xml中的authorities配置一致
            val authority =
                BuildConfig.APPLICATION_ID + ".fileprovider"
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val uri = FileProvider.getUriForFile(this@SplashActivity, authority, apkFile)
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
            // 如果需要新任务（Intent.FLAG_ACTIVITY_NEW_TASK），需加uri授权处理
            // grantUriPermission(getApplicationContext(), uri, intent);
        } else {
            val uri = Uri.fromFile(apkFile)
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
        }
        intent.putExtra("IMPLUS_INSTALL", "SILENT_INSTALL")
        // 如果需要新任务
        // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent)
        finish()
    }


}