package com.casic.electric.detector.view

import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import com.casic.electric.detector.BuildConfig
import com.casic.electric.detector.R
import com.casic.electric.detector.extensions.appendDownloadUrl
import com.casic.electric.detector.extensions.initLayoutImmersionBar
import com.casic.electric.detector.utils.FileType
import com.casic.electric.detector.utils.LoadingDialogHub
import com.casic.electric.detector.utils.LocaleConstant
import com.casic.electric.detector.vm.VersionViewModel
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.callback.OnDownloadListener
import com.pengxh.kt.lite.extensions.createDownloadFileDir
import com.pengxh.kt.lite.extensions.downloadFile
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.vm.LoadState
import com.pengxh.kt.lite.widget.dialog.AlertControlDialog
import kotlinx.android.synthetic.main.activity_version_control.*
import kotlinx.android.synthetic.main.include_base_title.*
import java.io.File

class VersionControlActivity : KotlinBaseActivity() {

    private val kTag = "VersionControlActivity"
    private val progressDialog by lazy { ProgressDialog(this) }
    private lateinit var versionViewModel: VersionViewModel

    override fun initData(savedInstanceState: Bundle?) {
        versionView.text = "Version ${BuildConfig.VERSION_NAME}"

        //初始化下载对话框
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
        progressDialog.setProgressDrawable(resources.getDrawable(R.drawable.download_progress))
        progressDialog.setCanceledOnTouchOutside(false)
        progressDialog.setCancelable(false)

        versionViewModel = ViewModelProvider(this)[VersionViewModel::class.java]
        versionViewModel.versionResult.observe(this) {
            if (it.version.toInt() > BuildConfig.VERSION_CODE) {
                AlertControlDialog.Builder()
                    .setContext(this)
                    .setTitle("提示")
                    .setMessage("有新版本，是否更新？")
                    .setNegativeButton("稍后再说")
                    .setPositiveButton("立即下载")
                    .setOnDialogButtonClickListener(object :
                        AlertControlDialog.OnDialogButtonClickListener {
                        override fun onConfirmClick() {
                            downloadApk(it.path)
                        }

                        override fun onCancelClick() {

                        }
                    }).build().show()
            } else {
                "已是最新版本，无需更新".show(this)
            }
        }
    }

    override fun initEvent() {
        leftBackView.setOnClickListener { finish() }

        updateLayout.setOnClickListener {
            versionViewModel.getApplicationVersion()
        }
    }

    override fun initLayoutView(): Int = R.layout.activity_version_control

    override fun observeRequestState() {
        versionViewModel.loadState.observe(this) {
            when (it) {
                LoadState.Loading -> LoadingDialogHub.show(this, "检查版本中，请稍后")
                else -> LoadingDialogHub.dismiss()
            }
        }
    }

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        initLayoutImmersionBar(rootView)
        titleView.visibility = View.GONE
    }

    private fun downloadApk(url: String?) {
        progressDialog.setMessage("下载新版本中...")
        progressDialog.show()
        if (url.toString().isBlank()) {
            "抱歉，版本下载失败".show(this)
            return
        }
        /**
         * http://139.198.18.188:8090/ems/apk/EMSCJTX202011052026(V3.14.0).apk
         * */
        val downloadPath = url!!.appendDownloadUrl(FileType.APK)
        Log.d(kTag, "downloadApk => $downloadPath")
        //开始下载
        downloadPath.downloadFile(createDownloadFileDir().toString(), object : OnDownloadListener {
            override fun onDownloadStart(totalBytes: Long) {
                progressDialog.max = totalBytes.toInt()
            }

            override fun onProgressChanged(currentBytes: Long) {
                progressDialog.progress = currentBytes.toInt()
            }

            override fun onDownloadEnd(file: File?) {
                progressDialog.dismiss()
                progressDialog.progress = 0
                //安装APK
                installApk(file)
            }
        })
    }

    private fun installApk(apkPackage: File?) {
        if (apkPackage == null) {
            "安装文件异常，无法安装".show(this)
            return
        }
        val intent = Intent(Intent.ACTION_VIEW)
        val data: Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判断版本大于等于7.0
            data = FileProvider.getUriForFile(this, LocaleConstant.APP_AUTHORITY, apkPackage)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // 给目标应用一个临时授权
        } else {
            data = Uri.fromFile(apkPackage)
        }
        /**
         * android 10
         * content://com.casic.app.smartwell.fileprovider/smartWell/Download/1.0.1.apk
         * */
        intent.setDataAndType(data, "application/vnd.android.package-archive")
        startActivity(intent)
    }
}