package com.dlc.eboard.ui

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.dlc.eboard.BuildConfig
import com.dlc.eboard.LabApp
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.ActivitySplashBinding
import com.dlc.eboard.sp.DeviceSp
import com.dlc.eboard.ui.settings.PasswordDialog
import com.dlc.eboard.ui.settings.SettingsActivity
import com.dlc.laboratory.ui.LabMainActivity
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.client.ApiRepository
import com.tbruyelle.rxpermissions2.RxPermissions
import java.lang.ref.WeakReference

/**
 * info
 *
 * @author ReiChin_
 */
class SplashActivity : RcBaseActivity<ActivitySplashBinding>() {

    override fun createViewBinding() = ActivitySplashBinding.inflate(LayoutInflater.from(this))
    private val weakHandler by lazy { WeakReferenceHandler(this) }

    private var count: Int = 0
    override fun initViews(savedInstanceState: Bundle?) {
        RcLog.info(
            "versionName:${DeviceUtils.getVersionName(this)}, versionCode:${
                DeviceUtils.getVersionCode(this)
            }, androidSN:${DeviceUtils.getAndroidSN()}"
        )
        viewBinding.deviceId.text = "设备编号：${DeviceUtils.getAndroidSN()}"
        viewBinding.versionName.text = "版本号：${DeviceUtils.getVersionName(this)}"

        viewBinding.versionName.setOnLongClickListener {
            PasswordDialog(this) {
                val intent = Intent(this, SettingsActivity::class.java)
                startActivity(intent)
            }.show()
            true
        }

        viewBinding.copyRight.setOnLongClickListener {
            PasswordDialog(this) {
                val intent = Intent(this, SettingsActivity::class.java)
                startActivity(intent)
            }.show()
            true
        }

        requestPermission()
    }

    private fun requestPermission() {
        val disposable = RxPermissions(this)
            .request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.RECORD_AUDIO,
            )
            .subscribe { granted ->
                if (granted) {
                    // 登录获取token
                    weakHandler.sendEmptyMessageDelayed(1, 5000)
//                    authLogin()
                } else {
                    AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("您必须同意所有权限才可以继续使用")
                        .setNegativeButton("确定") { _, _ ->
                            requestPermission()
                        }.show()
                }
            }
        addDisposable(disposable)
    }

    /**
     * 登录获取token
     */
    private fun authLogin() {
        RcLog.info("============================count$count")
//        count++
//        if (count>=15){
//            showToast("请检查网络环境或者地址配置")
//            return
//        }
        val disposable = ApiRepository.authOneLogin()
            .subscribe({ success ->
                if (success) {
                    queryAppVersion()
                }
            }, { throwable ->
                //初始化进入后网络反应太慢 重新调用
//                weakHandler.sendEmptyMessageDelayed(1, 5000)
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun queryAppVersion() {
        viewBinding.tips.text = "版本检测中..."
        val disposable = ApiRepository.apkVersion(CommonUtils.getAndroidId())
            .subscribe({ data ->
                if (CommonUtils.stringParseInt(data.version) > DeviceUtils.getVersionCode(this)) {
                    // 有新版本
                    viewBinding.line.visibility = View.VISIBLE
                    viewBinding.tips.text = "检测到新版本，开始更新"
                    viewBinding.progress.text = "（0%）"
                    // 显示版本更新
                    downloadApk(data.apkFileUpload)
                } else {
                    // 没有新版本
                    queryLabConfig()
                }
            }, { throwable ->
                showNetError(throwable)
                queryLabConfig()
            })
        addDisposable(disposable)
    }

    private fun downloadApk(downloadUrl: String) {
        callApkUpdateApi("2")
        ApkUpdater(applicationContext, BuildConfig.APPLICATION_ID, callback = object :
            ApkUpdater.DownloadCallback {
            override fun onProgress(progress: Int) {
                viewBinding.progress.text = "（${progress}%）"
            }

            override fun onFailed(errMsg: String?) {
                callApkUpdateApi("0")
                viewBinding.tips.text = "下载失败，请检查网络情况重新下载"
            }

            override fun onSuccess(apkFile: String) {
                callApkUpdateApi("1")
            }

        }).downloadApk(downloadUrl)
    }

    /*
     * state 0:升级失败; 1:升级成功; 2:升级中
     */
    private fun callApkUpdateApi(state: String) {
        val disposable = ApiRepository.onepcApkUpdate(CommonUtils.getAndroidId(), state)
            .subscribe({ }, { })
        addDisposable(disposable)
    }

    private fun queryLabConfig() {
        showLoading("加载中...")
        val disposable = ApiRepository.queryLabConfig(CommonUtils.getAndroidId())
            .subscribe({ data ->
                LabApp.sLabConfig = data
                queryLaboratoryInfo("1" == data.isStart, data.labId)
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun queryLaboratoryInfo(openEBoard: Boolean, labId: String) {
        val id = if (openEBoard) labId else CommonUtils.getAndroidId()
        val disposable = ApiRepository.laboratoryInfo(openEBoard, id)
            .subscribe({ data ->
                dismissLoading()
                DeviceSp.saveLaboratoryVo(this, data)
                startHomeActivity(openEBoard)
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun startHomeActivity(openEBoard: Boolean) {
        val clazz = if (openEBoard) HomeActivity::class.java else LabMainActivity::class.java
        startActivity(Intent(this, clazz))
        finish()
    }


    // static + 弱引用  防止内存泄露
    class WeakReferenceHandler(obj: SplashActivity) : Handler(Looper.getMainLooper()) {
        private val mRef: WeakReference<SplashActivity> = WeakReference(obj)
        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                authLogin()
            }
        }
    }

    override fun onDestroy() {
        weakHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

}